简体   繁体   中英

Send array with ajax request to php

I created array like this ["9", "ques_5", "19", "ques_4"] . Now I want to send it from JS to PHP but I'm not getting proper results. My JS code is:

$(".button").click(function(e) {

    e.preventDefault();
    $.ajax({
        type    : 'post', 
        cache   : false,
        url     : 'test/result.php',
        data    : {result : stuff},
        success: function(resp) {
            alert(resp);
        }
    });
});

In the above code stuff is an array which contains records. How can I send this array with above code and then in PHP I want to process this array like ques_5 is the key and 9 become the value for that key.

You can pass the data to the PHP script as a JSON object. Assume your JSON object is like:

var stuff ={'key1':'value1','key2':'value2'};

You can pass this object to the php code in two ways:

1. Pass the object as a string:

AJAX call:

$.ajax({
    type    : 'POST',
    url     : 'result.php',
    data    : {result:JSON.stringify(stuff)},
    success : function(response) {
        alert(response);
    }    
});

You can handle the data passed to the result.php as :

$data    = $_POST["result"];
$data    = json_decode("$data", true);

//just echo an item in the array
echo "key1 : ".$data["key1"];

2. Pass the object directly:

AJAX call:

$.ajax({
    type    : 'POST',
    url     : 'result.php',
    data    : stuff,
    success : function(response) {
        alert(response);
    }    
});

Handle the data directly in result.php from $_POST array as :

//just echo an item in the array
echo "key1 : ".$_POST["key1"];

Here I suggest the second method. But you should try both :-)

If you want to send key value pairs, which is what I am seeing, it would be better to use a PHP JSON library (like this one... http://php.net/manual/en/book.json.php )

Then you can send actual key value pairs, using JSON format like... {"ques_5" : "19", "ques_4": "19"}

Try this

var array = ["9", "ques_5", "19", "ques_4"];
console.log(array.join(","));

above code will output string with comma separated like 9,ques_5,19,ques_4 then paste it to ajax call.

And then in php explode that string.

Other possible solutions.

First

var obj = { 'item1': 'value1', 'item2': 'value2' };

$.ajax(
{
    type:  'post', 
    cache:  false ,
    url:  'test/result.php',
    data:  { result : JSON.stringify(obj) },
    success: function(resp)
    {
        alert(resp);
    } 
});

Second

var a = $.JSON.encode(obj);

$.ajax(
{
    type:  'post', 
    cache:  false ,
    url:  'test/result.php',
    data:  { result : a },
    success: function(resp)
    {
        alert(resp);
    } 
});

In PHP File

<?php
    $json = $_POST["data"]
    var_dump(json_decode($json));
?>

You can send the array in json format to the php and then use json_decode function to get back the array like

In ajax call you have to send json for that you need to first make array of the values so that you get it in right form so that you json look like {"ques_5":"9","ques_4":19}

and use in ajax call

 data: JSON.stringify(`your created json`),
 contentType: "application/json; charset=utf-8",
 dataType: "json",

IN PHP it look like

<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
?>

I would like to share a complete example that works for me in order to avoid making each JavaScript function for each PHP function

// on the HTML side a simple JavaScript call from a link

 <a href="javascript:CargaZona('democonllamada', 'tituloprin', {'key1':'value1','key2':'value2'})" >test</a>
<div id='tituloprin' >php function response here!</div>

// on JavaScript side

function CargaZona(fc, div, params) {
    var destino = "#" + div;
    var request = $.ajax({
        url : "inc/phpfunc.php",
        type : "POST",
        data : {
            fc : fc,
            params : JSON.stringify(params)
        },
        dataType : "html"
    });

    request.done(function (msg) {
        $(destino).html(msg);
    });

    request.fail(function (jqXHR, textStatus) {
        alert("Request failed: " + textStatus);
    });
}

// on phpfunc.php page

<?php

$params = "{'key1':'value1','key2':'value2'}"; 
$fc = 'def';
if (isset($_POST['fc']))   {    $fc = $_POST['fc']; }
if (isset($_POST['params']))   {    $params = $_POST['params']; }

switch ($fc) {
    default:
        call_user_func($fc,$params);
}

function democonllamada($params) {
    $params = json_decode("$params", true);
    echo "ok llegaron".$params['key1'];
}

?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM