13

I have an HTML form and send data to php file when hitting submit button.

$.ajax({
    url: "text.php",
    type: "POST",
    data: {
        amount: amount,
        firstName: firstName,
        lastName: lastName,
        email: email
    },
    dataType: "JSON",
    success: function (data) {
        console.log("ok");
        $("#result").text(data);
    }
});

In PHP:

<?php
    $amount      = $_POST["amount"];
    $firstName   = $_POST["firstName"];
    $lastName    = $_POST["lastName"];
    $email       = $_POST["email"];
    if(isset($amount)){
        $data = array(
            "amount"     => $amount,
            "firstName"  => $firstName,
            "lastName"   => $lastName,
            "email"      => $email
        );
        echo json_encode($data);
    }
?>

The result is [object object]. I want a type like:

{"Amount":"12.34", "FirstName":"Any", "LastName":"Tester", "Email":"a.test@something.com"}

What have I done wrong?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
SPG
  • 6,109
  • 14
  • 48
  • 79
  • 8
    `The result is [object object]`... yes, that's what you'll get if JS casts an object to a string. Your JSON may be correct; you're just not examining it properly. Try using `console.log()` instead. Also, use the dev tools to look at the http response that PHP sends back -- you should be able to see exactly what the data looks like. – Spudley Oct 15 '13 at 12:23
  • In terms of dev tools you can give FirePHP4Chrome a spin. – James P. Oct 15 '13 at 12:25
  • 1
    Are you setting the content header from PHP to be application/json? – dlp Oct 15 '13 at 12:26
  • 2
    I agree with Spudley and if you just want to ensure try to console.log or alert data.Amount or data.FirstName and it will give you the value. – Sumit Gupta Oct 15 '13 at 12:31

5 Answers5

22

Code example with JSON.stringify:

<html>
    <head>
       <title>jQuery Test</title>
       <script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
       <script type="text/javascript">
           $(document).ready(function() {
               $("#submit").click(function(){
                   $.ajax({
                       url: "text.php",
                       type: "POST",
                       data: {
                           amount: $("#amount").val(),
                           firstName: $("#firstName").val(),
                           lastName: $("#lastName").val(),
                           email: $("#email").val()
                       },
                       dataType: "JSON",
                       success: function (jsonStr) {
                           $("#result").text(JSON.stringify(jsonStr));
                       }
                   });
               });
           });
       </script>
    </head>

    <body>
        <div id="result"></div>
        <form name="contact" id="contact" method="post">
            Amount: <input type="text" name="amount" id="amount"/><br/>
            firstName: <input type="text" name="firstName" id="firstName"/><br/>
            lastName: <input type="text" name="lastName" id="lastName"/><br/>
            email: <input type="text" name="email" id="email"/><br/>
            <input type="button" value="Get It!" name="submit" id="submit"/>
        </form>
    </body>
</html>

text.php

<?php
    $amount      = $_POST["amount"];
    $firstName   = $_POST["firstName"];
    $lastName    = $_POST["lastName"];
    $email       = $_POST["email"];
    if(isset($amount)){
        $data = array(
            "amount"     => $amount,
            "firstName"  => $firstName,
            "lastName"   => $lastName,
            "email"      => $email
        );
        echo json_encode($data);
    }
?>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jenson M John
  • 5,499
  • 5
  • 30
  • 46
5

Your object is most likely being passed properly. It's the way you're capturing the result that returns [object object] as @Spudley explained. The console doesn't know how to display the construct but you can display specific attributes using the object.attribute syntax. Use console.log() on the JS side or the code below for a prettified output.

// Indent with tabs
// Data is the parameter sent to the success function in the ajax handler
JSON.stringify( data , null, '\t');

From How can I pretty-print JSON in (unix) shell script?

Also Temporarily remove dataType on the ajax handler if you sense there's a bug somewhere. Getting the ouput to show on a GET request should do. Change this back to POST for any operation that modifies something like a database delete or alter.

Lastly, modify the header as shown in @GroovyCarrot's answer. If you're using Chrome the extra whitespace seems to be a bug: Tab and pre wrapped around JSON output in Chrome

Community
  • 1
  • 1
James P.
  • 19,313
  • 27
  • 97
  • 155
4

Try adding

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

At the top of your PHP script and see what you get back

Hope that helps!

Edit: Forgot to mention you should access your values like so: data.amount

GroovyCarrot
  • 514
  • 3
  • 6
  • good idea yet it will not solve the problem :) Like James Poulson sais the json object is passed correctly but the objects toString method returns [object object] – VDP Oct 15 '13 at 12:33
  • It is really unnecessary, as `jQuery` really does not care about it – baldrs Oct 15 '13 at 12:33
  • I did add a comment on correctly accessing returned values for the JSON object, I agree this answer was a tad brief – GroovyCarrot Oct 15 '13 at 13:45
1

You cannot directly insert a JSON object to a dom. JSON object toString() method will always give u [object object], that is why you are getting this. You ve to parse the data by using JSON.stringify(data) or you have to run $.each(data,function(val){ $("#result").append(val) }).

Harry Bomrah
  • 1,658
  • 1
  • 11
  • 14
0

You're converting resulting object to string instead of displaying it.

Instead of result, if you want print object inside some wrapper, you can do something like this:

var text = '{';

for(var i in data) {
  var value = data[i];

  text += '"'+i+'":"'+value+'", ';
}

text += '}';

$('#result').text(text);

But you may consider that console.log is much easier and faster way to see the response in json format.

baldrs
  • 2,132
  • 25
  • 34