skip to Main Content

i am sending data from multiple checkboxes via ajax to php.
This is the html:

<input type="checkbox" class="get_value" value="PHP" />PHP <br />  
<input type="checkbox" class="get_value" value="ASP" />ASP <br />  
<input type="checkbox" class="get_value" value="JSP" />JSP <br />  
<input type="checkbox" class="get_value" value="Python" />Python <br />                      

<button type="button" name="submit" class="btn btn-info submit">Submit</button> 

The js:

$(document).on('click' , '.submit' , function() { 

    var languages = [];  
    $('.get_value').each(function(){  
        if($(this).is(":checked"))  
            {  
                 languages.push($(this).val());  
            }  
    });  
    languages = languages.toString();  
    $.ajax({  
        url:"",  
        method:"POST",  
        data:{languages:languages},  
        success:function(data){  
                $('#result').html(data);  
        }  
    }); 

});

And the php:

if(isset($_POST["languages"]))  { 
    $checkboxfiles[] = $_POST["languages"]; 
    foreach ($checkboxfiles as $checkboxfile) {
        echo $checkboxfile.'<br />';
    }   
    exit;            
} 

When checking 3 checkboxes, the echo gives me an output like this: PHP,ASP,JSP

How can i get rid of the comma and make an echo like this:

PHP
ASP
JSP

3

Answers


  1. Try to add this in the foreach loop:

    $checkboxfile = str_replace(',', '', $checkboxfile);
    
    Login or Signup to reply.
  2. If it is a comma separated string, you could explode on a comma and loop the values

    foreach ($checkboxfiles as $checkboxfile) {
        foreach(explode(',', $checkboxfile) as $value) {
            echo $value.'<br />';
        }
    }
    
    Login or Signup to reply.
  3. Replace the komma with <br> if in HTML otherwise you could use n. Notice: you have to use double quotes " if you need to use n

    if(isset($_POST["languages"]))  { 
        $checkboxfiles[] = $_POST["languages"]; 
    
        foreach ($checkboxfiles as $checkboxfile)
        {
            echo str_replace(',', '<br>', $checkboxfile) . '<br>';
        }             
    } 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search