Skip to content
Advertisement

How to send the value of jquery variable to PHP variable in an Array?

I’m pretty new to Jquery and PHP and I’m trying to get the values of checkboxes in a filter form and sending to php. I’d like to figure out how to store the PHP variable as an array of all the boxes checked.

My form:

<input type="checkbox" name="applications[]" <?php echo $selected['applications/food-applications/sugar-reduction/'] ?> id="sugar-reduction" value="applications/food-applications/sugar-reduction/" onchange="$('#app_filter').submit();" >
<input type="checkbox" name="applications[]" <?php echo $selected['applications/food-applications/binding-systems/'] ?> id="binding-systems" value="applications/food-applications/binding-systems/" onchange="$('#app_filter').submit();" >
<input type="checkbox" name="applications[]" <?php echo $selected['applications/food-applications/shelf-life-extension/'] ?> id="shelf-life-extension" value="applications/food-applications/shelf-life-extension/" onchange="$('#app_filter').submit();" >

Script:

$("#app_filter").submit(function() {
                                
    event.preventDefault();
    
        var checkbox_value = "";
        $(":checked").each(function () {
            var ischecked = $(this).is(":checked");
            if (ischecked) {
                checkbox_value += $(this).val() + ", ";
            }
        });
        console.log(checkbox_value);
        return false;
});
                                            

With all three boxes checked it is successfully showing the values in the console like this:

applications/food-applications/sugar-reduction/, applications/food-applications/binding-systems/, applications/food-applications/shelf-life-extension/, 

I’d like to store the values in an array and in a PHP variable. Ideally like this…

array(applications/food-applications/sugar-reduction/, applications/food-applications/binding-systems/, applications/food-applications/shelf-life-extension/,)

Is that possible? Any guidance would be greatly appreciated!

Advertisement

Answer

Use $(this).serialize() to encode all the form inputs. You can then access them in PHP just as you would with normal form submission.

$("#app_filter").submit(function(event) {

  event.preventDefault();
  $.ajax({
      url: $(this).attr("action"),
      type: "post",
      data: $(this).serialize(),
      success: function(response) {
        console.log(response);
      }
    }
  });
});

In PHP, $_POST['applications'] will be an array of all the selected values.

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