简体   繁体   中英

Passing object array via jquery ajax to php not working

I am trying to create an associative array with the record id as the key and order as the value. I then want to pass this via ajax to php where I will foreach through the array and update the records. But it is not working I seem to be getting null at json_decode($_REQUEST['orderArray'], true);

Whats wrong with the code:

jquery :

 //Make project task table rows sortable
$('#Task_table tbody').sortable({
    items: "tr:not(.disable_sort)",//disable sortable on header row
    helper: fixHelperModified, //call helper function
    update: function(event, ui) {
        var order = {};//create object
        $('#Task_table tr').each(function(){//loop through rows
            var id = $(this).children('td:first-child').find(".order_number").attr("rel");
            var order_number = $(this).children('td:first-child').find(".order_number").val();
            //fill object array with keys(task->id) and values (task->order_number)
            order[id] = order_number;
        });

        //convert array to json
        var jsonArray = JSON.stringify(order);
        //prepare POST data
        var dataString = { 'orderArray':jsonArray };

        $.ajax({
            type: "POST",
            url: "index.php?module=Project&action=update_order",
            data: dataString,
            success: function() {
               // location.reload();
            }
        });
    }
});

this sends via post: orderArray {"4b0df1da-8b2d-7776-0026-52d0b3cefbfa":"3","161699ae-6db0-43d6-e85b-52ca07767b0f":"1","8da4cfc3-b56d-12da-e34c-52d09ed0b310":"2"}

The php:

//updates the order of the tasks
function action_update_order(){
    //create object/array from json data
    $orderArray = json_decode($_REQUEST['orderArray'], true);

    var_dump($orderArray);

    foreach($orderArray as $id => $order_number){

        $GLOBALS['log']->fatal('order: '.$order_number[$id]);

        $task = new ProjectTask();
        $task->retrieve($id);
        $task->order_number = $order_number;
        $task->save();
    }
}

As I said I cant seem to foreach through the result of the jasondecode. Also hard to debug as its ajax.

can you try change this

var dataString = { 'orderArray':jsonArray };

to

var dataString = { 'orderArray': order };

由于某种原因,JSON.stringify(order)将Html实体版本的“添加到我的字符串中,因此我需要在php_json_decode之前先在我的php中使用htmlspecialchars_decode();。它似乎可以工作。

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