Home > Mobile >  ajax response: unexpected non-whitespace character after JSON data
ajax response: unexpected non-whitespace character after JSON data

Time:01-06

I send an ajax request with jquery like this:

 $.post("ajax/myFile.php", {
    myValue: "test"
    }, function(response) {
      console.log($.parseJSON(response))
    })

content of myFile.php

myFunctionA();
myFunctionB();

function myFunctionA() {
   echo json_encode(array('error' => 0, 'message' => "Hello World"));
}


function myFunctionB() {
    echo json_encode(array('error' => 0, 'message' => "Hello again"));
}

my console.log result:

Uncaught SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 44 of the JSON data

how can I handle this? :/

CodePudding user response:

You can't return multiple JSON values from your script. You need to combine them into a single value.

echo json_encode([myFunctionA(), myFunctionB()]);

function myFunctionA() {
   return array('error' => 0, 'message' => "Hello World");
}


function myFunctionB() {
    return array('error' => 0, 'message' => "Hello again");
}

This will return both results as elements of an array in JavaScript.

  • Related