0

I'm currently using jQuery's $.get() to process IDs entered in a text field with a database. It currently works quite well, especially the PHP which can handle multiple comma-separated entries.

The issue I'm having is with jQuery; more specifically, JSON parsing. The PHP file returns an array of arrays, which is used to manipulate a <table>. While it works with single entries, i.e. "12346", it doesn't work with multiple entries, such as "123456,789101".

The error is specifically thrown at Line 77: var serverData = $.parseJSON(data)[0];

Here's the stack trace

Uncaught SyntaxError: Unexpected token s in JSON at position 2
    at Function.parse [as parseJSON] (<anonymous>)
    at Object.<anonymous> (myScript.js:77)
    at u (jquery.min.js:2)
    at Object.fireWith [as resolveWith] (jquery.min.js:2)
    at k (jquery.min.js:2)
    at XMLHttpRequest.<anonymous> (jquery.min.js:2)

Here is what my code looks like so far:

PHP:

$sql = "SELECT * FROM students";
$stmt = $pdo->prepare($sql);
$stmt->execute();
//Database access is arbitrary
while ($row = $stmt->fetch()) { //iterate through db results
  $student_array[$row['sid']] = array(
    'name' => $row['name'],
    'advisory' => $row['advisory']
  );
}

$json_params[] = array(
  "students" => $student_array, /* The array of arrays */
  "success" => "n students were checked in, nice!" /* generic message */
  "failure" => "m students couldn't be accessed"
);

echo json_encode($json_params);

jQuery:

$.get("check-in.php", {value: inputValue}).done(function(data) {
  var serverData = $.parseJSON(data)[0];
  if (serverData.success) {
    $.each(serverData.students, function(sid, tableValues) {
      /* Create a <tr> based on the information (using the key as the SID,
       * name, and advisory, and insert that <tr> into a table */
    });
  }
}

This might be the culprit, which is the JSON text causing the issue:

[{
  "students": {
    "245680":{"name":"John Doe","advisory":"9"},
    "135791":{"name":"Jane Smith","advisory":"7"}
  },
  "success":"2 students were checked in!"
}]

I'm quite puzzled as it's been working fine with single number entries. I've looked at solutions to "parsing JSON arrays of arrays" on this site, but I've tried all the suggestions for those. Any help is greatly appreciated!

4
  • What is the error message? Commented Jul 13, 2018 at 4:11
  • Completely forgot, I'll edit the post Commented Jul 13, 2018 at 4:12
  • use console.log to print out the json data and make sure it looks correct (or better yet, learn how to use the debugger that's built into the browser) Commented Jul 13, 2018 at 4:16
  • The JSON string in my post is copied from the console Commented Jul 13, 2018 at 4:18

2 Answers 2

2

I don't see the need to make $json_params as an array. It is stored outside of looping and executed only once. Just remove [] part. THe code will look like this.

$json_params = array(
    "students" => $student_array, /* The array of arrays */
    "success" => "n students were checked in, nice!" /* generic message */
    "failure" => "m students couldn't be accessed"
);

In your jQuery, you can simply retrieve JSON result without having to access key array. [0] isn't necessary as [] in $json_params is removed.

var serverData = $.parseJSON(data);
Sign up to request clarification or add additional context in comments.

7 Comments

Yeah, are you sure you're not getting any kind of Error or Warning in your PHP output? Maybe that's what is messing with the JSON, the response from PHP MUST BE valid JSON from byte 0 to the end.
yeah, no error or warning in php output. I suspect about the array access in this js code. $.parseJSON(data)
PHP is free of any errors; it does exactly as intended. I'll try this
PHP looks like this: $json_params = array(); $json_params["students"] = $success_array; $json_params["success"] = $result_success; and jQuery looks like this: var serverData = $.parseJSON(data);. Issue still persists
what's the output of serverData?
|
1

Your code has this:

var serverData = $.parseJSON(data)[0];

but it's failing because data is already an object (not a json string that needs to be parsed).
Try this:

var serverData = data[0];

5 Comments

I'll give this a try
console.log() says serverData.success is undefined :/
i've tested this (browser side) with your json data and it works. is it possible that you used console.log incorrectly?
are you looking at the console output or are you looking at the return value of console.log?
Correction, console.log(data) is what I used to get the JSON string. console.log(serverData) shows the Object itself. So I suppose it's not an issue with JSON but with jQuery

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.