0

I create JSON-data with the following php code:

if($res =  $db->query('Select row1 from table1')){
    while($row = $res->fetch_row()){
        $json[] = $row;
    }
}
sort ($json);
$json = json_encode($json);
echo $json;

The result is [["1"],["2"],["3"]].
When I try to fetch this data with jquery ajax

<div id="output">JSON will be put here</div>
<script language="javascript" type="text/javascript">
    $(function ()   {
    $.ajax({
                url: 'json.php',
                dataType: 'json',
                data: '', 
                error: function(request,error) {
                            alert(error);
                            },
                success: function(data) {
                    var json = data[0];
                    alert(json);
                    $('#output').html(json+", ");
                    }
                });
            });

it says: "parseerror".
I searched a lot (here at Stack Overflow), but my jQuery version seem to be right (1.7.2) and reformating the JSON-outpu did not help (I deleted the opening brackets and tried a lot of other things).
Any ideas?

6
  • Are you sure there's no other output on the page? I'd bet there is. Commented Jul 25, 2013 at 12:54
  • 1
    $.parseJSON( data ); Commented Jul 25, 2013 at 12:55
  • 1
    "The result is [["1"],["2"],["3"]]" - How did you determine this? Commented Jul 25, 2013 at 12:59
  • I tried parsing that string and it worked. Are you sure that's the string your php CGI is returning? Aren't you missing response headers? Commented Jul 25, 2013 at 13:20
  • If I directly access the website with the php code it returns [["1"],["2"],["3"]]. But if I then open the page with ajax JSON call it doesn't replace the output div and sends the error message. I was unsure if it's correct JSON sythax but I verified it with JSONLint and learned that php created a JSON array. Commented Jul 26, 2013 at 7:36

4 Answers 4

2

Parse the data return in ajax result,

var retData= JSON.parse(data);
Sign up to request clarification or add additional context in comments.

2 Comments

if dataType: 'json' is specified you don't have to.
i've got errors with it, too. dataType seems to don't take an effect sometime :(
0

You should check if you get an object before using it:

if(typeof data != 'object')
    data = $.parseJSON(data);

Sometime it is interpreted as a string and you have to convert it first

1 Comment

The OP said they get "parseerror". Does that not imply that jQuery has tried to parse the string before calling the function?
0

I don't think you need to push it in an array. Your query is already an array. SO try to only json_encode() and that alert the data what you get and try to access the data by using data.somevariable( at least that is how I access my json data in the ajax).

Hope it helps

9 Comments

Could you explain this a little more practically?
Well the $row data you get from the database ia already an array. I don't see a reason why you should insert it to another array. Then you json_encode($row) and then try to read it back in ajax. First you alert so you see what structure you get. For example in table1 you have a field called name. You will get the name with data.name. I hope i was clear enough
You are selecting row1 form the database. if($res = $db->query('Select row1 from table1')){ while($row = $res->fetch_row()){ $json[] = $row; --> don't use this } } Just use $row= $res->fetch_row(); and then json_encode($row); and try to access you data.
Ok, then I was right. I already tried this but this way I only get the first value of the row ["1"].
Well then check out what does you query return. As far as i know you can access the json data this way -- > data.VARIABLENAME not like you access the array with data[1].
|
0

Verify the content type of the response header (you can see this in any modern browser's network console). It needs to be coming back as application/json. Any other type may cause your Javascript to fail. Before echoing the JSON in your PHP file, try adding:

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

This will explicitly and correctly set the response content type. Keep in mind, this in contingent upon your return string being valid JSON in the first place, which it seems to be.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.