Send array with ajax request to php

前端 未结 5 846
逝去的感伤
逝去的感伤 2021-02-08 03:37

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:

相关标签:
5条回答
  • 2021-02-08 04:05

    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"}

    0 讨论(0)
  • 2021-02-08 04:10

    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'];
    }
    
    ?>
    
    0 讨论(0)
  • 2021-02-08 04:24

    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 :-)

    0 讨论(0)
  • 2021-02-08 04:28

    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_4then 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));
    ?>
    0 讨论(0)
  • 2021-02-08 04:30

    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));
    ?>
    
    0 讨论(0)
提交回复
热议问题