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

5
  • $.POST (jquery) and $_POST in php.. Or.. $.AJAX (jQuery) and either $_POST or $_GET according to your preferences. Commented Apr 22, 2014 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 Commented Apr 22, 2014 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: stackoverflow.com/questions/2013728/… Commented Apr 22, 2014 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 Commented Apr 22, 2014 at 17:05
  • Have you tried using json? Commented Apr 22, 2014 at 17:08

2 Answers 2

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){
    ...
}
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.