Christie
Christie

Reputation: 45

SyntaxError: JSON.parse: unexpected character error in AJAX call

I'm an engineering intern at a software company, and my current project is to create an HTML page that uses AJAX and PHP to get data from a database. I've never posted on this site before, I've always looked for similar posts and used the info I find. I've been looking for a solution to my problem for the last 2 hours or so. My AJAX call returns the error: "SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data."

I've tried lots of things, namely:

  1. Adding dataType: 'json' to the options in $.ajax.
  2. Adding header("Content-type: application/json"); to the PHP code.
  3. Using console.log($.parseJSON(data)) in the success function.
  4. Reformatting my code in PHP to include quotes or not include them in the array

It seems like the problem is in the formatting of the data my page receives from my PHP script, which is as follows:

header('Content-type: application/json');
$testarray = array("Name" => 'America', "Code" => '12345');
echo json_encode($testarray);

In my jquery segment, I want to retrieve JSON data from my PHP script (which will eventually use a MySQL DB) and add the data as elements in my list box, CountriesList. My AJAX call is as follows:

$.ajax({
     cache: false,
     url: 'results.php',
     method: 'POST',
     dataType: 'json',
     data: "",
     success: function (data, textStatus, jqXHR){
           //I get an error with the following line
           var jsonData = JSON.parse(data);
           $(jsonData).each(function (i, element)
           {
                 var htmlSelect = document.getElementById("CountriesList");
                 var opt = document.createElement("option");
                 opt.text = element.Name;
                 opt.value = element.Code;
                 htmlSelect.options.add(opt);
            });
            },
            error: function(jsXHR, textStatus, errorThrown)
            {
                        alert('Error: ' + errorThrown)
            }
             });

It's possible that there are other errors in this code since I haven't been able to debug past this formatting issue. When I open the PHP script by itself, I get this as a response: {"Name":"America","Code":"12345"}. Which, as far as I'm aware, is correctly formatted JSON.

I'm at a loss. Any help is appreciated.

Upvotes: 2

Views: 1660

Answers (3)

Egg Vans
Egg Vans

Reputation: 944

Ill put this as an answer.

As I said in my comment the data variable is already a JSON object. So you should be able to access each element like so:

for(var i in data){
    if(data.hasOwnProperty(i){
        $('#CountriesList').append($("<option></option>").attr("value",data[i].Value).text(data[i].Name));
    }
}

Your test array is just an associative array whereas the javascript is expecting an array of associative arrays. Try

$testarray = array();
$testarray[] = array('Name'=>'America', 'Value'=>'12345');
$testarray[] = array('Name'=>'Europe', 'Value'=>'54321');

Upvotes: 2

JoniJnm
JoniJnm

Reputation: 722

The variable data is in JSON format, jQuery does it for you if you add dataType: json or the php header.

So you have to change:

var jsonData = JSON.parse(data);
By:
var jsonData = data;

Upvotes: 0

39otrebla
39otrebla

Reputation: 1442

If you need POST, this should work (you don't need to parse an array encoded by PHP in json):

$.post('results.php', // url
        {argOne: "test", argTwo: "test"}, // post data
        function(jsonResponse) { // callback

            $(jsonResponse).each(function (i, element) {
                // do your things
            });
         },'json');

If you can use GET method:

$.getJSON("results.php", function(jsonResponse) { 

    $(jsonResponse).each(function (i, element) {
        // do your things
    });                           
});

Upvotes: -1

Related Questions