1

I am using PHP with RESTful API, I have a problem with GET request. My function returns an array of objects, which i can see in my browser if I press F12->Network->function.php->Response

This is what is in response:

{"data":[{"content":"test123","user_id":"2","user_email":"0","username":"admin","ad_id":"1","date":"2020-03-28"}]}

Now going back to $.ajax method,if i try to parse this JSON data, it parses to "1" instead to the array of objects. Below is my $.ajax method and function that loads these objects

 $.ajax({method:"GET", url:"api.php/loadComment/"+$('#ad_id').val(),done:function(data){
   $comments = JSON.parse(data);
    console.log($comments);
}});  

switch method in my api.php file, this succesfully loads objects into $comments:

switch($method){
     case 'GET':
        $comments["data"] = Comment::returnAll($db,$request[1]);
        echo json_encode($comments);
        break;
}
John Doe
  • 23
  • 5

1 Answers1

0

Your ajax call isn't built properly as the .done handler must be outside the ajax call itself, i.e.:

<script>
    $.ajax({
        method: "GET",
        url: "api.php/loadComment/" + $('#ad_id').val()
    }).done(function (data) {
        $comments = JSON.parse(data);
        console.log($comments);
    });
</script>
mitkosoft
  • 5,262
  • 1
  • 13
  • 31
  • Thanks for the reply! Error has changed, now I get **Uncaught SyntaxError: Unexpected token o in JSON at position 1** So I believe there is something wrong with parsing/JSON format, but I tried to parse my data with an online JSON parser and it parses it fine.. – John Doe Mar 30 '20 at 10:27
  • what `console.log(data)` is saying into the `.done` handler? – mitkosoft Mar 30 '20 at 10:32
  • 1
    **EDIT**: Found the problem, as data is already an object, I dont need to parse it as Javascript Interpreter does it already. Code is now changed to this: `$.ajax({ method: "GET", url: "api.php/loadComment/" + $('#ad_id').val() }).done(function (data) { console.log(data); });` Answer in this thread: [link](https://stackoverflow.com/questions/15617164/parsing-json-giving-unexpected-token-o-error) – John Doe Mar 30 '20 at 10:34
  • Great! Enjoy the rest of the day then :) – mitkosoft Mar 30 '20 at 10:35