Join the Stack Overflow Community
Stack Overflow is a community of 6.5 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I am trying to send JSON object from Javascript/Jquery to PHP and I am getting and error msg in my console. What am I doing wrong. I am new to JS and PHP.

JQuery file:

$(document).ready(function() {
    var flickr = {'action': 'Flickr', 'get':'getPublicPhotos'};
    // console.log(typeof(flickr));
    var makeFlickrCall = function(flickrObj){
        $.ajax({
            url: '../phpincl/apiConnect.php',
            type: 'POST',
            data: flickrObj
        })
        .done(function(data) {
            console.log("success");
            console.log(JSON.stringify(data));
        })
        .fail(function() {
            console.log("error");
        })
        .always(function() {
            console.log("complete");
        });
    };

    makeFlickrCall(flickr);
});

PHP file

<?php       
    $obj = $_POST['data'];
    // print_r($obj);
    return $obj;
?>
share|improve this question
1  
what is the error? – Eddie Who May 20 '14 at 3:43
    
the console.log error .fail and .always msg is displayed on my console window. – Vish May 20 '14 at 3:45
    
try print_r($_POST) to see the result. – Amit Garg May 20 '14 at 3:45
    
this suggests that you want to send the variable flickrObj as data, you need to make that a global variable,what is in that? – tinybyte May 20 '14 at 3:45
1  
You have to use $_POST['action'] to get the value of action and $_POST['get'] to get the value of get. if you just want to return it the echo json_encode($_POST);. – Amit Garg May 20 '14 at 3:57
up vote 3 down vote accepted

Excellent answer by Phil, however since the OP title says

send json object from javascript (not jQuery ) to php

this is how to do it with (vanilla) javascript, in case it helps somebody looking for this method:

var jsondata;
var flickr = {'action': 'Flickr', 'get':'getPublicPhotos'};
var data = JSON.stringify(flickr);

var xhr = new XMLHttpRequest();
xhr.open("POST", "../phpincl/apiConnect.php", !0);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send(data);
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
        // in case we reply back from server
        jsondata = JSON.parse(xhr.responseText);
        console.log(jsondata);
    }
}

Notice we still need to convert the server's response into a javascript object using JSON.parse()

Now, on the server side (based on Phil's answer) if you are sending back a response to the client, you could do:

header('Content-type: application/json');
$json = file_get_contents('php://input');
$json_decode = json_decode($json, true); 
$json_encode = json_encode($json_decode);
echo $json_encode;

NOTE:

The reason behind decoding first and then encoding back the raw json input is to properly escape slashes in (possible) URLs within the data, e.g.

json_encode will convert this URL

http://example.com

into

http:\/\/example.com

... which is not the case in the OP but useful in some other scenarios.

share|improve this answer
    
Thanks for the response JFK, My title does say Javascript but the I've specified Javascript/Jquery in the description. – Vish Aug 10 '15 at 17:11
    
@Vish : no problem, I was just providing a way to do it with javascript only in case somebody doesn't want to include jQuery – JFK Aug 10 '15 at 20:26
1  
appreciate your effort and I'm happy to know both ways to tackle the problem :) – Vish Aug 10 '15 at 20:53

The standard jQuery .ajax() method uses the data property to create an x-www-form-urlencoded string to pass in the request body. Something like this

action=Flickr&get=getPublicPhotos

Therefore, your PHP script should not look for $_POST['data'] but instead, $_POST['action'] and $_POST['get'].

If you want to send a raw JSON data payload to PHP, then do the following...

Set the AJAX contentType parameter to application/json and send a stringified version of your JSON object as the data payload, eg

$.ajax({
    url: '../phpincl/apiConnect.php',
    type: 'POST',
    contentType: 'application/json',
    data: JSON.stringify(flickrObj),
    dataType: 'json'
})

Your PHP script would then read the data payload from the php://input stream, eg

$json = file_get_contents('php://input');

You can then parse this into a PHP object or array...

$dataObject = json_decode($json);
$dataArray = json_decode($json, true);

And, if you're just wanting to echo it back to the client..

header('Content-type: application/json');

// unmodified
echo $json;

// or if you've made changes to say $dataArray
echo json_encode($dataArray);
share|improve this answer
    
what do I need to do to make the post work $_POST['data'] and return the object back to javascript? – Vish May 20 '14 at 4:01
    
@Vish I've updated my answer – Phil May 20 '14 at 4:39
    
@Phil Very helpful answer, can I make the php send back execution progress several times of whats going on at the moment?, cause my php execution is too long. – Yousif Jul 15 '15 at 11:58

Use:

makeFlickrCall( { data: JSON.stringify( flickr )} );

Instead of

makeFlickrCall(flickr);

Your server-side script should receive your JSON as follows:

data="{"action":"Flickr","get":"getPublicPhotos"}"
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.