0

I'm trying to display some data from the ajax response as below.

$.post(
            '/tests/elementary/'+($(this).attr('data-test-id'))+'/get-details', // location of your php script
            {
            }, // any data you want to send to the script
            function( data ) {  // a function to deal with the returned information
                if(data.taken =='false'){
                    alert('ok')
                }
                else {

                    $('#test_name').empty().append(data.information);
                    $('#test_point').empty().append(data.details['score']);
                    $('#test_date').empty().append(data.updated_at);


                    for(var i=0;i<data.testlog.length;i++) {
                        var temp = data.testlog[i];
                        $("#test_details_body").append("<tr> <td>"+ (i+1) +"</td> <td>"+temp['operand1']+' '+temp['operator']+' '+temp['operand2']+"</td><td>"+temp['user_answer']+"<td>"+temp['correct'] +"</td><tr>")
                    }



                }
            });
        });

But I'm getting Uncaught SyntaxError: Unexpected token o error.

response:

{
    "success":"true",
    "taken":"true",
    "details":"{\"id\":2,\"user_id\":1,\"test_id\":9,\"token\":\"682c5de08481081b940364416cdce99d\",\"score\":80,\"attempts\":2,\"created_at\":\"2015-02-16 02:09:12\",\"updated_at\":\"2015-02-16 02:09:12\",\"course_id\":7}",
    "information":"sample test exam",
    "updated_at":"16-Feb-2015 02:02:12",
    "testlog":[
        {"id":21,"test_id":9,"user_id":1,"operand1":1,"operand2":10,"operator":"+","answer":11,"user_answer":11,"answering_time":"00:00:00","created_at":"2015-02-16 02:53:11","updated_at":"2015-02-16 02:53:11","token":"682c5de08481081b940364416cdce99d","correct":"1"},
        {"id":22,"test_id":9,"user_id":1,"operand1":2,"operand2":10,"operator":"+","answer":12,"user_answer":12,"answering_time":"00:00:00","created_at":"2015-02-16 02:53:15","updated_at":"2015-02-16 02:53:15","token":"682c5de08481081b940364416cdce99d","correct":"1"},
        {"id":23,"test_id":9,"user_id":1,"operand1":3,"operand2":10,"operator":"+","answer":13,"user_answer":0,"answering_time":"00:00:00","created_at":"2015-02-16 02:53:18","updated_at":"2015-02-16 02:53:18","token":"682c5de08481081b940364416cdce99d","correct":"1"},
        {"id":24,"test_id":9,"user_id":1,"operand1":4,"operand2":10,"operator":"+","answer":14,"user_answer":0,"answering_time":"00:00:00","created_at":"2015-02-16 02:53:25","updated_at":"2015-02-16 02:53:25","token":"682c5de08481081b940364416cdce99d","correct":"0"},
        {"id":25,"test_id":9,"user_id":1,"operand1":5,"operand2":10,"operator":"+","answer":15,"user_answer":0,"answering_time":"00:00:00","created_at":"2015-02-16 02:53:29","updated_at":"2015-02-16 02:53:29","token":"682c5de08481081b940364416cdce99d","correct":"1"}
    ]
}

enter image description here

php script for fetching data

public function getTestDetails($id){

        $exists = Testresult::where('user_id', Auth::id())->where('test_id', $id)->first();

        if($exists==null){
            return Response::json(["success"=>"true", "taken"=>"false"]);
        }
        else{

            $updated_at = date("d-M-Y H:m:s", strtotime($exists->updated_at));
            $testLog = Testlog::where('token', $exists->token)->get();

            $info = Test::where('id', $id)->pluck('name');
            return Response::json(["success"=>"true", "taken"=>"true",
                                    "details"=>"$exists",
                                    "information"=>$info,
                                    "updated_at"=>$updated_at,
                                    "testlog"=>$testLog]);
        }


    }

Am I doing it right?

user1012181
  • 8,648
  • 10
  • 64
  • 106
  • 3
    What line of code does the error relate to? – Craicerjack Feb 16 '15 at 23:52
  • If `data` is a JavaScript object, then you don't need to `JSON.parse(...)` if data is a JSON String, before your loop you should parse it so something like `data = JSON.parse(data)` and remove that parse from your loop. – Arthur Weborg Feb 16 '15 at 23:55
  • 1
    A *"shortest form of code"* would include an example of `data` / `data.testlog` – Phil Feb 16 '15 at 23:56
  • @ArtyMcFly: Actually the data has several type of response. One string, one json and another json array. – user1012181 Feb 16 '15 at 23:56
  • possible duplicate of [I keep getting "Uncaught SyntaxError: Unexpected token o"](http://stackoverflow.com/questions/8081701/i-keep-getting-uncaught-syntaxerror-unexpected-token-o) – Craicerjack Feb 16 '15 at 23:56
  • @Phil: Will update it now. – user1012181 Feb 16 '15 at 23:57
  • I don't understand your edit. Where did it come from? Why is some of it an object literal and some of it JSON string (ie, the `details` property)? If that's a dump of `data` (presumably **after** being parsed from an XHR response body), then each `testlog` array entry is already an object literal and does not need parsing – Phil Feb 17 '15 at 00:03
  • @user1012181, thank you for posting your data. How are you generating that JSON String on the server? For better practice, the entire initial JSON String should be parsed on a single `JSON.parse(...)` call, instead of incrementing through it and calling `JSON.parse(...)` on various segments. I suspect that your JSON string generation should be tweaked slightly. – Arthur Weborg Feb 17 '15 at 00:07
  • @ArtyMcFly: Should I provide the php script also? – user1012181 Feb 17 '15 at 00:12
  • Screenshots don't answer anything. Why don't you simply include the code where you assign `data`. If it comes from an XHR, what methods are you using to fetch it? – Phil Feb 17 '15 at 00:13
  • @Phil: I added the php script for fetching the data. – user1012181 Feb 17 '15 at 00:18
  • **How do you assign a value to `data`**? Why are you purposefully avoiding providing the one piece of the puzzle required to let anyone help you? Also, `"details"=>"$exists"` seems wrong in your PHP. If `$exists` is an object, you shouldn't be casting it to a string. Just use `'details' => $exists` – Phil Feb 17 '15 at 00:22
  • @user, most people seem to be asking you where your code block exists for parsing the returned AJAX response. Are you using jquery? Raw XHR? How are you making the call to the PHP script to receive your data payload? – sctskw Feb 17 '15 at 00:23
  • The mistake in your PHP code led you to think you had to use `JSON.parse` but you don't. See @ArtyMcFly's answer below – Phil Feb 17 '15 at 00:29
  • @Phil: Yes, that PHP error was a mistake. I corrected it. Still the same problem persisting. – user1012181 Feb 17 '15 at 00:31
  • 2
    Perhaps because you're still using `JSON.parse`? If your code has changed, edit your question. Also, again in your PHP, use real booleans (`true` and `false`), not strings (`"true"` and `"false"`). Do the same in your JavaScript, ie `if (!data.taken)` – Phil Feb 17 '15 at 00:32

2 Answers2

2

You are on the correct track! I think there are two issues here. The first is that you are trying to parse a JavaScript Object into a JavaScript Object. This is visible based on the fact that your screenshot shows the response parsing most of your object correctly via your AJAX call. This is confirmed by the error you are seeing in the console log.

So removing that JSON.parse(...) as below will fix that issue:

for(var i=0;i<data.testlog.length;i++) {
   var temp = data.testlog[i];
   $("#test_details_body").append("<tr> <td>"+ (i+1) +"</td> <td>"+temp['operand1']+' '+temp['operator']+' '+temp['operand2']+"</td><td>"+temp['user_answer']+"<td>"+temp['correct'] +"</td><tr>")
}

The second issue is the generation of your JSON string, which as you discuss in the comments is coming via PHP. This isn't necessary for answering the original question, but for better practice should be corrected. I also think you may have thought you had to parse your array, because you have JSON strings embedded in your JavaScript Object.

I'm a little rusty on PHP but I think this line "details"=>"$exists", should actually be "details"=>$exists

Arthur Weborg
  • 8,280
  • 5
  • 30
  • 67
  • 2
    +1 The PHP fix would also fix some of OP's other JavaScript code. Assuming `Response::json` sets the appropriate headers, jQuery will automatically parse the response body as JSON. OP should never have to use `JSON.parse` – Phil Feb 17 '15 at 00:28
  • Thanks for your support, but it didnt help. The same error is persisting. PHP error was a mistake. Accidentally used the quotes. – user1012181 Feb 17 '15 at 00:28
  • 1
    Did you correct both the PHP and removing the `JSON.parse(...)`? – Arthur Weborg Feb 17 '15 at 00:31
  • 1
    Now it is working very well. :) Thanks for your effort. @Phil: You may also want to post an answer? I could give an upvote. – user1012181 Feb 17 '15 at 00:36
  • @Phil: I did. I also wanted to thank you for your efforts too. ArtyMcFly did a great job too :) – user1012181 Feb 17 '15 at 00:43
  • 3
    @user1012181 There's no need. This answer correctly deduced the problem and provided the correct answer. There's nothing further to add – Phil Feb 17 '15 at 00:43
0

It doesn't look like data.testlog needs to be parsed you could do this

var testlog = data.testlog
for(var i = 0; i < testlog.length; i++){
    var temp = testlog[i]
    $('#test_details_body').append('<tr><td>' + (i+1) + '</td><td>' + temp.operand1 + ' ' + temp.operator + ' ' + temp.operand2 + '</td><td>' + temp.user_answer + '<td>' + temp.correct + '</td><tr>')
}

Also I changed a couple things in your code (spacing, using single rather than double quotes, and using dot notation for call values from an object.)

pizzarob
  • 11,711
  • 6
  • 48
  • 69
  • @user1012181 it doesn't look like testlog is stringified so you wouldn't need to parse it. that would be the reason for the error. I updated my example. – pizzarob Feb 17 '15 at 00:24
  • Good bye `data`. I'd use a different variable – Phil Feb 17 '15 at 00:25