1

I am new to jQuery. I have got an error when I try to get data from fileresult.php.

fileresult.php

$return_arr = array();
$row_array['status'] = 'Ok';
$row_array['message'] = 'good'
array_push($return_arr, $row_array);
echo json_encode($return_arr);

JSON output

[{"date":"2014-03-15","status":"ok","message":"good"}]

get_result.js

$.post('file.php', $("form").serialize(), function(data) {
    var status = data['status'];
    alert(status);  
});

When I alert data, it shows undefined. Somebody please help me. How can I show the correct data.

SamV
  • 7,548
  • 4
  • 39
  • 50
Thameem
  • 3,426
  • 4
  • 26
  • 32
  • 2
    Have you tried parsing the JSON data first? `data = JSON.parse(data);`? – SamV Mar 15 '14 at 11:36
  • 1
    at your $.post() set as last param 'json' .. $.post(url, function(){}, 'json') and add exit at your php code after the echo – Svetoslav Mar 15 '14 at 11:38
  • @Svetlio Never understood this, why is there a need to add `exit` after echoing out JSON data? After that echo the scripts execution ends anyway. – SamV Mar 15 '14 at 11:39
  • @Svetlio If you get worried about additional outputs then something is wrong with the application, you should know what outputs data in the application. `exit` just feels like "I'm not sure if my application will output any extra data, let's put it in there just in case." I feel that if this is your thought process then the application is not built correctly. – SamV Mar 15 '14 at 11:46
  • @SamV Its good to be sure that your code is perfect, but never trust it 100% specially if you are working in a team :) – Svetoslav Mar 15 '14 at 11:53
  • @Svetlio I agree with the team aspect ;) – SamV Mar 15 '14 at 11:54

1 Answers1

5

You have two problems.

You are outputting "HTML"

PHP defaults to claiming that its output is HTML. jQuery will see this claim and treat it as such instead of parsing it as JSON.

Override PHP's default with:

header("Content-Type: application/json");

You have an array

You are accessing data.status but the top level data structure you are outputting is an array so you need data[0].status with that data.

You don't have multiple objects though, so (unless you plan to add more in the future) it would make more sense to return

{"date":"2014-03-15","status":"ok","message":"good"}

instead of

[{"date":"2014-03-15","status":"ok","message":"good"}]

So remove everything to do with $return_arr and:

echo json_encode($row_array);
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335