0

I was looking at this post: SyntaxError: Unexpected token o in JSON at position 1

Exactly my issue. But when I try to remove the parse, I then get the error: Cannot read property '0' of undefined.

Here is my original excerpt:

$.ajax({
        type:"POST",
        url:"getuser.php",
        data: 'person='+str,
        success: function(response){
            var result = JSON.parse(response);
            var data = result.rows;
                $("#id").val(data[0].id);
                $("#card").val(data[0].card);
                $("#name").val(data[0].name);
                $("#type").val(data[0].type);
                $("#cabin").val(data[0].cabin);
                $("#birthdate").val(data[0].birthdate);
        }
    });

My incoming data from getuser.php is:

{"id":"16758","card":"221","name":"Spongebob","type":"Staff","cabin":"24","town":"Bikini Bottom","birthdate":"07/14/1986"}

So if I remove the parse and make it:

success: function(response){
            var data = response.rows;

It gives me the property 0 of undefined.

Here is a fiddle excluding the request from php: http://jsfiddle.net/vzwbop2t/

Any ideas? I am looking to edit a user, so I need the database values to populate the inputs in the form, so then any modifications, and it's saved back to the user.

Thanks.

dota_fan
  • 47
  • 7
  • What do you get from `console.log(response);`? If your endpoint sets the `content-type: application/json` header, then jQuery may've parsed the data for you into an object already. This is the case in the jsfiddle example. The `response` is _already_ an object and doesn't need to be `JSON.parse`d. – gen_Eric Jun 24 '21 at 21:00
  • 1
    Also, there is no `rows` array in your data. That is just a single object, no arrays. So, you may just need `$("#id").val(response.id);` – gen_Eric Jun 24 '21 at 21:02
  • Rocket, you are correct, I was overlooking it wasn't a set of rows for once! It is working without the rows breakdown. Put that in as an answer to get credit. – dota_fan Jun 24 '21 at 21:26

1 Answers1

1

When using jQuery's $.ajax, it checks the content-type header returned by the server. If it's set to application/json, then it runs JSON.parse() for you.

This means your response may already be an object (and not a string that needs to be "parsed").

Also, your data is a single object, not an array of objects, there is no row property/array. You just need to use $("#id").val(response.id);, etc.

gen_Eric
  • 223,194
  • 41
  • 299
  • 337