1

I have arrays and variables in JQuery and I want to know that Can I POST both arrays and variables from single $ajax jquery request to my php page. If yes then How will I post data from Jquery and how will i handle in PHP page.

var get_id = [], get_product= [];  //Array
    var day = $("#day").val();  // Variable
    var month = $("#month").val(); // Variable
    var year = $("#year").val();   // Variable

Thanks

  • $.POST (jquery) and $_POST in php.. Or.. $.AJAX (jQuery) and either $_POST or $_GET according to your preferences. – briosheje Apr 22 '14 at 16:57
  • your answer is correct for only variables, but my question is how can i post variable and array both in single $ajax request – explorecode Apr 22 '14 at 16:59
  • You can pass literally everything through ajax.. you can either pass a string, a number or an array using the same method. Check this: http://stackoverflow.com/questions/2013728/passing-javascript-array-to-php-through-jquery-ajax – briosheje Apr 22 '14 at 17:01
  • I am getting output as **Array** text when I am using $_POST['id']; Where `id` is an array POSTED by jquery $ajax request – explorecode Apr 22 '14 at 17:05
  • Have you tried using json? – briosheje Apr 22 '14 at 17:08

2 Answers2

2

If you want to send complex data types, such as arrays, it's easier to JSON encode your data, and decode it on the PHP side:

var data = {
    get_id : get_id,
    get_product : get_product,
    day : day,
    month : month
};

$.post('url', { data : JSON.stringify(data) }, function(response){
    // success
});

On the PHP side:

$data = json_decode($_POST['data']);

echo $data->day;
foreach($data->get_product as $p){
    ...
}
MrCode
  • 63,975
  • 10
  • 90
  • 112
0

No need to encode/decode into/from JSON. Keep it simple and just post the data object as is:

$.ajax('/index.php', {
   type: 'POST',
   data: {
      get_id:[],
      get_product:[],
      day: $("#day").val(),
      month: $("#month").val(),
      year: $("#year").val()
   }
});

On the PHP side, you can see the post data:

var_dump($_POST); // post is a keyed (nested) array.
ronnbot
  • 1,241
  • 1
  • 9
  • 5