2

I am sending json object from jquery using ajax post and i want to parse through it using php and send the same object back. The post is successful so my object is going there but I am not getting appropriate response. I am sending first name and last name from the html form but the response json object I get is in my console is:-

response : [object Object]

When i try to see the php side in the browser I get errors like :-

<br />
<b>Notice</b>:  Trying to get property of non-object in <b>C:\xampp\htdocs\jsonTest\process.php</b> on line <b>8</b><br />
<br />
<b>Notice</b>:  Trying to get property of non-object in <b>C:\xampp\htdocs\jsonTest\process.php</b> on line <b>9</b><br />
{"firstname":null,"lastname":null}

I have seen posts on stackoverflow talking about above error but the scenario was different than mine. And I am indeed sending json object from jquery side so I dont know why am i even getting this error. In "network" console i can see that it successfully sends json object.

Here is my jquery part:-

$("#userDataForm").submit(function(e){
    e.preventDefault();
    var formData={
        fname:$("#fname").val(),
        lname:$("#lname").val()
    };
    $.ajax({
        type:'post',
        url:'process.php',
        dataType:'json',
        data:JSON.stringify(formData),
        contentType: "application/json",

        success:function(response){
            var response= $.trim(response);
            console.log("response : "+response);
        }
    });
});

Here is the html form I am using:

<form id="userDataForm">
        <input type="text" placeholder="Firstname" name="fname" id="fname" />
        <input type="text" placeholder="Lastname" name="lname" id="lname" />
        <input type="submit" value="submit" name="submit">
    </form>

And this is php part:-

<?php
    header('Content-type:application/json');
   $request = file_get_contents('php://input');
   $input=json_decode($request);
    $jsonResponse=array(
                'firstname' => $input->fname,
                'lastname'  => $input->lname
                );

    echo json_encode($jsonResponse);

?>

I have gone through several stackoverflow posts for my error but so far i havent been able to come across any post where json object is sent from ajax and also recieved from php. Also, I would like to know how isset($_POST) will fit in this scenario of the code since I am sending json object instead of a regular form data.

Rajat Bansal
  • 183
  • 1
  • 14
  • 1
    There has to be an error decoding the json in `$input=json_decode($request);`. Try `var_dump( $input ):` – Hasse Björk Nov 28 '15 at 22:48
  • 1
    I'm pretty sure you don't need to be json Stringifying your data out in the ajax call, or json_decoding it. Since you're declaring data type as JSON, it's for both input and output. Try just passing the object as data, and then accessing it directly as an object or an indexed array in your $request variable or as $_POST. That's how I use ajax/php, and it works fine for me. – Logan Bentley Nov 28 '15 at 22:52
  • @HasseBjörk : var_dump($request) or var_dump($input)? because if there is problem in json_Decode then even var_dump wont work because $input would be wrong isnt it? – Rajat Bansal Nov 28 '15 at 22:53
  • Logan is correct, `dataType:'json'` is for the response, not the request. – rjdown Nov 28 '15 at 22:54
  • Yes, try both! var_dump( $input ) will show you if you get an array or an object, correct spellings and so on. I would use the variable $_POST to read the posted data though! – Hasse Björk Nov 28 '15 at 22:54
  • @LoganBentley: But i need to have json request and response no matter what. In that case, i dont know other option than stringifying because only after stringifying i can see json object in my network console. Also as far as I know 'dataType' is only for the type of response you want and not the type you send. So many tutorials send simple object data and use that data type when they want json back – Rajat Bansal Nov 28 '15 at 22:59
  • @RajatBansal What do you mean by you "need to have json request and response"? Why does the request have to be json? HTTP Post methods are capable of having arrays and other complex data sent to them, there's no need to json encode it. The encoding only needs to be in your response. I'll post an answer with the code so you can try it. – Logan Bentley Nov 28 '15 at 23:02
  • @LoganBentley : my issue is that the front end form would be java based which my other team is working on. They have specifically said that they will send me json objects and my php should be able to handle it and give a json response back. So i thought it would be good to know how it would work if front end is plain html form too – Rajat Bansal Nov 28 '15 at 23:03
  • 1
    @RajatBansal Then your issue is different from what your example is. When using POST, there will always be a variable name (at least, anything I've ever seen). You never get just a string, you get an array or object with different elements or attributes, with different values. So, they may be sending you data: {info: "jsonencoded string here"}. Hence, you need to know what variable name they're sending, and then run json_decode on that variable on your PHP side. – Logan Bentley Nov 28 '15 at 23:10
  • @Logan Bentley: I get your point. Thanks for clarifying. So at this point of time I shouldnt be worried about front end. So then i should just focus on sending the response back rather than worrying about front end. – Rajat Bansal Nov 28 '15 at 23:14
  • 1
    @RajatBansal Until you get more clarification from them, yes, that's what I recommend. Get it working with the simple form data for first/last name without encoding or decoding the request, to make sure you have the flow set up, no server setting issues, etc. Once you have that, and know exactly how they'll be sending you the data, you can add in the proper line of "json_decode" and modify any of the variables you need to because of it. – Logan Bentley Nov 28 '15 at 23:17
  • @LoganBentley: just so you know. I had used this stackoverflow post answer http://stackoverflow.com/questions/12693947/jquery-ajax-how-to-send-json-instead-of-querystring to send json from ajax – Rajat Bansal Nov 28 '15 at 23:20
  • 1
    @HasseBjörk : I get 'nulls' when i try to do var dump. Why does it happen? Coz i am able to successfully POST . – Rajat Bansal Nov 28 '15 at 23:31
  • Well, you are not getting any data through if you get NULL from var_dump($request) . Why send the form as json and not just post it and read the $_POST array? (I am not too familiar with jQuery) – Hasse Björk Nov 28 '15 at 23:34
  • @HasseBjörk : I agree everybody is suggesting that. You can see the comments exchanged with others before. However, I was just thinking what if backend is java and I have jquery on front end and the back end person wants json to be sent? Thats why i thought if we could send and recieve json. – Rajat Bansal Nov 28 '15 at 23:36
  • @RajatBansal See my answer. – Rajdeep Paul Nov 29 '15 at 00:00

2 Answers2

1

Try changing ajax data part to:

data: {
   data: JSON.stringify(formData)
},

and receive request in php like this:

$request = $_POST['data'];

EDIT: Full tested code

Html:

<form id="userDataForm">
    <input type="text" placeholder="Firstname" name="fname" id="fname" />
    <input type="text" placeholder="Lastname" name="lname" id="lname" />
    <input type="submit" value="submit" name="submit">
</form>

JS:

  $('#userDataForm').submit(function(e){
         e.preventDefault();
         var formData={
            fname:$('#fname').val(),
            lname:$('#lname').val()
         };
         jQuery.ajax({
            type: 'POST',
            url: 'process.php',
            dataType: 'json',
            data: {
               data: JSON.stringify(formData)
            },
            success: function(res) {
               alert(res);
            }
         });
      });

PHP:

  if (isset($_POST['data'])) {
      $request = $_POST['data'];
      $input = json_decode($request);
      $jsonResponse = array(
            'firstname' => $input->fname,
            'lastname'  => $input->lname
      );
      echo json_encode($jsonResponse);
   }
Rajat Bansal
  • 183
  • 1
  • 14
Sam Ivichuk
  • 999
  • 1
  • 10
  • 22
  • could you be more specific because when i tried that straightaway it produced weird format in the payload under Network "data=%7B%22fname%22%3A%22rajat%22%2C%22lname%22%3A%22bansal%22%7D" and i got another error on php side when i replaced initial $request with yours "
    Notice: Undefined index: data in C:\xampp\htdocs\jsonTest\process.php on line 4

    " along with first 2 errors i was originally getting.
    – Rajat Bansal Nov 28 '15 at 23:10
  • @RajatBansal I've edited my answer. Please try to reproduce the code, it is working on my server and echo's right values. If it won't work for you, it means you have some special server configuration – Sam Ivichuk Nov 28 '15 at 23:40
  • Yours worked but then I observed that you were not sending JSON response back from php. So in you code in jquery i added "dataType:json" and then instead of echoing out individual values I created a json array like this "$jsonResponse=array( 'firstname' => $input->fname, 'lastname' => $input->lname ); echo json_encode($jsonResponse);" and echoed out after encoding it as json and wow I got exactly what I wanted. Your way actually helped. So please make this edit and i will accept ur answer – Rajat Bansal Nov 28 '15 at 23:56
1

You can do something like this: (tested)

HTML

<form id="userDataForm">
    <input type="text" placeholder="Firstname" name="fname" id="fname" />
    <input type="text" placeholder="Lastname" name="lname" id="lname" />
    <input type="submit" value="submit" name="submit">
</form>

jQuery

    $(document).ready(function(){
        $("#userDataForm").submit(function(e){
            e.preventDefault();
            var formData={
                fname:$("#fname").val(),
                lname:$("#lname").val()
            };
            $.ajax({
                type:'post',
                url:'process.php',
                dataType:'json',
                data:JSON.stringify(formData),
                contentType: "application/json",

                success:function(response){ 
                    // process json object
                    console.log(response.fname);
                    console.log(response.lname);
                },
                error: function(jqXHR, textStatus, errorThrown){
                    alert(errorThrown);
                }
            });
        });
    });

process.php

<?php

    $json_array = json_decode(file_get_contents("php://input"), true);
    $my_array = array();
    foreach($json_array as $key => $value){
        $my_array[$key] = $value;
    }
    echo json_encode($my_array);

?>

Since in your case, you are submitting a JSON in the body, you have to read it from this stream. Usual method of $_POST superglobal won't work here.

Quoting from PHP Manual:

php://input is a read-only stream that allows you to read raw data from the request body.

Rajdeep Paul
  • 16,887
  • 3
  • 18
  • 37
  • thanks for an alternative solution. But if you look at my last comment on above answer , the POST super global worked too in that case. So now I know two ways to do it, thanks for your answer – Rajat Bansal Nov 29 '15 at 00:00
  • You're welcome. :) I just wanted to show that even if you send JSON object with ajax request, you can still process it using read-only stream. – Rajdeep Paul Nov 29 '15 at 00:03