简体   繁体   中英

Passing object from Javascript to PHP using AJAX

Object:

var obj = [{id: 1, name: "Peter", lastname: "Griffin"}]

Javascript:

$.ajax({
    method: 'post',
    url:'http://api/test.php',
    data: {     
        func: "addtodatabase",
        objectToBePassed: obj   //also tried JSON.stringify(obj)
    },          
    success: function(data) {
       //code here
    }
});

PHP:

$data = json_decode($_REQUEST['objectToBePassed'], true);

I can't seem to make it work. Help?

No, you seem to be confused on this. You do not need to json_decode() that. Once its in the post body. Just access it as it is:

$data = $_POST['objectToBePassed'];

Here is a demo

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