mhrvatin
mhrvatin

Reputation: 154

jquery won't accept json_encode() data

I'm using the following piece of code to send data from a form to a php script that will do some calculations using a class:

$.ajax({
    type: "POST",
    url: "test2.php",
    data: values,
    success: function(returnedData) {
        $("#result").html(returnedData);
    },
    error: function(){
        alert("failure");
        $("#result").html('error while submitting');
    }
});

My PHP script creates an array which I encode with JSON and then echo

$jsonString = array(
    'monthText' => $Month->getMonthText($month),
    'gross' => $formatGross,
    'net' =>  $formatNet
    );
echo json_encode($jsonString);

So far so good. But I'm not very keen on displaying the raw JSON. I'd like to format the text before it's written to the document. I've tried $.parseJSON() and $.getJSON() but none of them work. The jQuery docs says it needs a string but isn't json_encode() making my array to a string? Isn't echo making it a string? Why am I getting the error Uncaught SyntaxError: Unexpected token { in my jQuery-file? My theory is that it doesn't have single quotes around it.

I've tried using header('Content-type: application/json') in my PHP script and I've also tried dataType: json in my AJAX POST but nothing is working.

What am I doing wrong?

Upvotes: 0

Views: 3408

Answers (3)

Patrick Evans
Patrick Evans

Reputation: 42736

From the comments it sounds like you are using json_encode wrong. Store each piece of data into an array and then encode the array.

$data = array();
for($i=0;$i<$something;$++) {
   $data[] = array(
      'monthText' => $Month->getMonthText($month),
      'gross' => $formatGross,
      'net' =>  $formatNet
    );
}

echo json_encode($data);

Then your Javascript would need to be

$.ajax({
    type: "POST",
    url: "test2.php",
    dataType:"json",
    data: values,
    success: function(returnedData) {
        //returnedData will now be an array Object
        for( var i=0; i<returnedData.length; i++ ) {
           $("#result").html(returnedData[i].monthText);
        }
    },
    error: function(){
        alert("failure");
        $("#result").html('error while submitting');
    }
});

Upvotes: 4

Iqbal Malik
Iqbal Malik

Reputation: 602

Add dataType in your ajax call like this.

$.ajax({
    type: "POST",
    dataType:"json",
    url: "test2.php",
    data: values,
    success: function(returnedData) {
        $("#result").html(returnedData);
    },
    error: function(){
        alert("failure");
        $("#result").html('error while submitting');
    }
});

Upvotes: 0

Rajesh
Rajesh

Reputation: 3778

for parsing, use jQuery.parseJSON(returnedData);

Upvotes: 0

Related Questions