Sending an array of information

I would like to send a couple of arrays to my php with jquery and json, how do I do this?

Im working with:

$.ajax(
{
url: "script.php",
type: "POST",
data: ???,
dataType: "html",
success: function(tablehtml){
alert(tablehtml);
}
});

Usually I want to send over two arrays, and then the php site will create an html table.

For example: I want to get user information ["Tim", "Alan", "Kate"]for months["June", "July", "August"]

I expect json_decode in my php script, but how do I pack and send two arrays ?: D

+3
source share
5 answers

You don't have to decrypt json on the server side. Suppose you have:

var months = ["June", "July", "August"];
var names = ["Tim", "Alan", "Kate"];

Then you can use $. param to create a serialized view of them suitable for sending as a query string, for example:

$.ajax(
{
    url: "script.php",
    type: "POST",
    data: $.param( { names: names, months: months } ),
    dataType: "html",
    success: function(tablehtml){
        alert(tablehtml);
    }
});

PHP "" "" , , , :

foreach($_POST['names'] as $name) {
    echo 'Name is: ' . $name . '<br />'; 
}
+2

JSON.stringify(), :

$.ajax({
  url: "script.php",
  type: "POST",
  data: JSON.stringify({users: usersArray, months: monthsArray}),
  dataType: "html",
  success: function(tablehtml){
    alert(tablehtml);
  }
});

usersArray monthsArray - . PHP, , users months.

, JSON (IE < 8), json2.js, ... .

+1

, , JSON :

var json = '{"users":["'+users.join('","')+'"],"months":["'+months.join('","')+'"]}';

$.ajax({
    url: "script.php",
    type: "POST",
    data: json,
    dataType: "html",
    success: function(tablehtml) {
        alert(tablehtml);
    }
});
+1

:

$.ajax(
{
url: "script.php",
type: "POST",
data:usersArray+'-|-'+monthsArray,
dataType: "html",
success: function(tablehtml){
alert(tablehtml);
}
});

In this case, usersArray and monthsArray are simply variable names for existing JSON arrays.

and then explode this line in php

$arr = explode('-|-',$_REQUEST['data'])

and then

$userArray = json_decode($arr[0])

$monthsArray = json_decode($arr[1])

I did this in my project and it works great

0
source

You should fortify your javascript array (serialize the value) with JSON.stringify (on the json site) and send it like this:

data:"myData="+JSON.stringify(myVar),

You will get this value in $ _POST ['myData'] and json_decode.

0
source

Source: https://habr.com/ru/post/1780421/


All Articles