Skip to content
Advertisement

Get different values of same string in PHP

I have checkboxes of categories in a form. When checkbox is changed, from is submitted through ajax and get the values in PHP.

//form

foreach($somethings and $something){
    <input class="input_sale_category" type="checkbox" name="category" value="something->value" />`
}

I get the form data and submit through ajax

      $('.input_sale_category').click(function() {
        var formData = $('#filter_sale_form').serialize();

        jQuery.ajax({
          type: 'GET',
          url: myurl,
          data: formData
          
          success: function(response) {
            console.log(response);
          },
          error: function (request, status, error) {
            alert(request.responseText);
          }
        });
      });

In PHP, I am getting input fields as a string

category=nexus-chair-offer&category=office-desks&category=office-storage

I tried to get the inputs values of category using explode, parse_str but could not get all the values of category

parse_str($str, $output);

var_dump($output);

How can I achieve this? Regex seems an option, but I not good at regex.

Advertisement

Answer

Issue is in you html code, You are using same ‘name’ property in all of you input tag What this will do is only sand 1 value to backend.

change you input tag like this

foreach($somethings and $something){
<input class="input_sale_category" type="checkbox" name="category[]" value="something->value" />`
}

check this answer as well, it might help, Get checkbox values using checkbox name using jquery

You can also get values manually and pass it in ajax request’s data

var checkboxes_value = []; 
   $('.input_sale_category').each(function(){  
        //if($(this).is(":checked")) { 
        if(this.checked) {              
             checkboxes_value.push($(this).val());                                                                               
        }  
   }); 
//checkboxes_value will be array of checked checkboxes

                         
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement