Mico
Mico

Reputation: 497

Post JavaScript Object using jQuery

my JS is creating objects that look like this:

enter image description here

Now I want to post it to a PHP page.

What I tried is this:

var json = JSON.stringify(item_contents);
console.log(json);

jQ.post(
    "http://somedomain.com/headlines/save_items/", 
    json,
    function(data){
        console.log("Data: ");
        console.log(data);
        alert("first success");
    },
    "json"
)
.success(function() { 
    alert("second success"); 
})
.error(function(data) { 
    alert("error: "); 
    console.log(data);
})  
.complete(function() { 
    alert("complete"); 
});

...and the output is always an error. I'm using cakePHP.. Any help? TIA!!!

EDIT:

Currently, what i have on my php page is:

echo print_r($_POST);

and im getting a blank or undefined ouput..

Upvotes: 0

Views: 694

Answers (2)

zb'
zb'

Reputation: 8059

If you really want to post json, set variable name.

jQ.post(
    "http://somedomain.com/save_items.php", 
    {json: json}, //<--HERE
    function(data){
        console.log("Data: ");
        console.log(data);
        alert("first success");
    },
    "json"
)
.success(function() { 
    alert("second success"); 
})
.error(function(data) { 
    alert("error: "); 
    console.log(data);
})  
.complete(function() { 
    alert("complete"); 
});

In php use echo $_POST['json'];

you also may want to just post object itself:

jQ.post(url,object,function(data)
           {
                 console.log('success',data);
            }
           ,"json")
            .error(function(data) { 
                console.log('error',data);
             });

in php use echo json_encode($_POST); be sure that somedomain.com is the same where js is.

Upvotes: 0

Yograj Gupta
Yograj Gupta

Reputation: 9869

Post your json string with in a json literal object in your post function

like { content: json }, -- and get this "content" in $_POST

jQ.post(
    "http://somedomain.com/save_items.php", 
    { content: json }, 
    function(data){

and in PHP try with

echo print_r($_POST["content"]);

Upvotes: 1

Related Questions