Pass array to ajax request in $.ajax()

JqueryAjaxArraysJson

Jquery Problem Overview


I want to send an array as an Ajax request:

info[0] = 'hi';
info[1] = 'hello';

$.ajax({
  type: "POST",
  url: "index.php",
  success: function(msg){
    $('.answer').html(msg);
  }
});

How can I do this?

Jquery Solutions


Solution 1 - Jquery

info = [];
info[0] = 'hi';
info[1] = 'hello';


$.ajax({
   type: "POST",
   data: {info:info},
   url: "index.php",
   success: function(msg){
     $('.answer').html(msg);
   }
});

Solution 2 - Jquery

Just use the JSON.stringify method and pass it through as the "data" parameter for the $.ajax function, like follows:

$.ajax({
    type: "POST",
    url: "index.php",
    dataType: "json",
    data: JSON.stringify({ paramName: info }),
    success: function(msg){
        $('.answer').html(msg);
    }
});

You just need to make sure you include the JSON2.js file in your page...

Solution 3 - Jquery

NOTE: Doesn't work on newer versions of jQuery.

Since you are using jQuery please use it's seralize function to serialize data and then pass it into the data parameter of ajax call:

info[0] = 'hi';
info[1] = 'hello';

var data_to_send = $.serialize(info);

$.ajax({
    type: "POST",
    url: "index.php",
    data: data_to_send,
    success: function(msg){
        $('.answer').html(msg);
    }
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPoonam BhattView Question on Stackoverflow
Solution 1 - JqueryDiodeView Answer on Stackoverflow
Solution 2 - JqueryFarligOpptredenView Answer on Stackoverflow
Solution 3 - JqueryDivinesLightView Answer on Stackoverflow