Unexpected token in JSON at positon 0 - javascript

I always get Unexpected token in JSON at positon 0 in my code
the echo json will be
["pen","pencil","apple","cat","dog"]
and the console will get Uncaught SyntaxError: Unexpected token p in JSON at position 0
php code :
<?php
include 'Connect_2.php';
header('Content-Type: application/json;charset=utf-8');
$Store_int =$_GET['num'];
#execute sql function and return result
$sql = "SELECT * FROM `store` WHERE `Place_int` = ".$Store_int;
mysqli_select_db($link,"web");
$link -> set_charset("utf8");
$result = mysqli_query($link,$sql);
$arr = array();
while ($row = mysqli_fetch_object($result)){
$p =(string) $row -> Name;
$arr[]=$p;
}
//print_r($arr);
$jsonArr = json_encode($arr,JSON_UNESCAPED_UNICODE);
echo ($jsonArr);
mysqli_free_result($result);
mysqli_close($link);
?>
.js code
function getArr(store_int){
var jsArray = new Array();
$.ajax({
url: "fromSQL_store.php",
data: {
num: store_int
},
type: "GET",
dataType: "json",
success: function(data) {
jsArray = JSON.parse(data);
//jsArray = data;
},error: function(data,XMLHttpRequest, textStatus, errorThrown){
console.log(textStatus);
console.log(errorThrown);
}
});
//alert(jsArray.length);
console.log(jsArray[0]);
return jsArray;
}
if I use jsArray = data ;the console(jsArray[0]) will show undefined.

It's already JSON. Don't call jsArray = JSON.parse(data); Instead, just treat data like a JSON object.
Instead of console(jsArray[0]) call console(jsArray) The data object doesn't seem to be an array.
Also, it looks like you're console.log is being called right after you send the ajax request, which isn't giving you any time to receive the response to populate the object, so it's going to be empty. Put the console.log in the success callback of the ajax request.
JSON.parse() throws this error when it's parsing something that's already JSON which is really annoying since it sure would be nice if it instead just returned the original JSON back to you or at least threw a more precise error like "Error: This is already JSON."

May be your response header Content-Type is text/html instead of application/json.
Hence, If the response header is text/html you need to parse the text into JSON Object but if the response header is application/json then it is already parsed into JSON Object.
The solution is to set correct Content-Type header.
If response header (Content-Type) is text/html :
var jsonObj = JSON.parse(responseData);
If response header (Content-Type) is application/json :
var jsonObj = responseData;

Related

Sending JSON data with jQuery not working

Simple request being made
var username = {'username' : 'tom'};
var request = $.ajax({
url : 'test.php',
method : 'GET',
data : JSON.stringify(username),
dataType : 'json'
});
request.done(function(response) {
response = JSON.parse(response);
console.log(response);
});
request.fail(function(xhr, status, error) {
console.log(error);
});
PHP:
<?php
echo json_encode(array("bar" => "bar"));
?>
Still getting error, no idea why
that's because the server is returning a non valid JSON string. Try to check what the server is returning. This may happen if your server is throwing an error. In your case, I think the error you are trying to parse is not a JSON string. You might want to check that out as well.
You can use this link to validate your JSON.

JSON.parse is an “undefined” object [duplicate]

This question already has answers here:
How to parse JSON data with jQuery / JavaScript?
(11 answers)
Closed 5 years ago.
I created json with php. Data coming with ajax. But JSON.parse is giving an “undefined” object. Why ?
Php CODE
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
echo json_encode($emparray);
Ajax CODE
$.ajax({
type: "GET",
url: "http://localhost:8080/xxx.php/",
success: function (msg, result, status, xhr) {
var obj= JSON.parse(msg);
alert(obj.name);// giving undefined
},
error: function (error) {
}
});
json
[{"name":"eng","a":"sdf"}]
Your JSON is an array, meaning you'll have to point to the index of the object before accessing the property.
This code should work:
console.log(obj[0].name); //Returns "eng"
If your JSON array was something like this:
[{"name":"eng","a":"sdf"}, {"name":"esp", "a":"abc"}]
Then obj[1].name would return "esp".
You should obj[0].name
Because you are accessing the name property of the of the first element of the array.
A better way to get data from server
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
echo json_encode(array("data"=>$emparray));
Put all the json response on a key which is data here then at front end define that the server response is in JSON by dataType and then there is no need to parse data by JSON.parse()
msg.data.length will provide you the validaton on if the data received from server is empty or not which will prevent the undefined error
$.ajax({
type: "GET",
dataType: "JSON",
url: "http://localhost:8080/xxx.php/",
success: function (msg, result, status, xhr) {
var obj= msg.data;
if(msg.data.length){
alert(msg.data[0].name);// wll give name at 0 index
}
},
error: function (error) {
}
});

Json object returned from PHP with json_encode() , but then invalid json object in my javascript

I echo a simple associative array read from a mySQL table back to my jquery b.m.o the json_encode($array) method. However, my .ajax call fails back in the jquery and it seems due to the object not being a valid json object. I did some debugging in chrome and under the network tab verified the response preview- does indeed look to be in perfect json format:
{"UserName":"DehanL","UserPassword":"admin","UserEmail":"dehan#rocketmail.com"}
Here is my php:
<html>
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbName ="dbPodiumPro";
$inUsername = $_POST["name"];
$inPassword = $_POST["password"];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbName);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Use the dbPodiumPro
mysqli_select_db($conn,"dbPodiumPro");
$sql = "SELECT * FROM users WHERE UserName='$inUsername' AND UserPassword ='$inPassword' ";
$result = mysqli_query($conn,$sql);
// Fetch one row
$row=mysqli_fetch_assoc($result);
//Check to see if the username and password combo exists
if(!empty($row['UserName']) AND !empty($row['UserPassword']))
{
//$_SESSION['UserName'] = $row['UserPassword'];
//echo $_SESSION;
echo json_encode($row);
}
else { echo "Be gone imposter!"; }
$conn->close();
?>
</body>
</html>
Then the jquery:
$.ajax({
type: 'POST', // define the type of HTTP verb we want to use (POST for our form)
url: 'php/loginrequest.php', // the url where we want to POST
data: formData, // our data object
dataType: 'json' // what type of data do we expect back from the server
})
// using the done promise callback
.done(function (data) {
console.log("ajax done callback");
})
.fail(function (data) {
console.log(data, "ajax failed callback");
var IS_JSON = true;
try {
var json = $.parseJSON(data);
} catch (err) {
IS_JSON = false;
}
console.log(IS_JSON);
});
Your PHP starts like this:
<html>
<body>
Whatever else it outputs after that, it isn't going to be valid JSON.
I did some debugging in chrome and under the network tab verified the response preview
Look at the raw preview. You seem to be looking at the rendered HTML preview.
You don't need to parseJSON when you have added dataType as JSON option in the AJAX.
The data you are getting after ajax is completed is already in JSON format.
"json": Evaluates the response as JSON and returns a JavaScript object. The JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. As of jQuery 1.9, an empty response is also rejected; the server should return a response of null or {} instead. (See json.org for more information on proper JSON formatting.)
Docs: http://api.jquery.com/jQuery.ajax/
The data inside fail method is not what you've passed from server. It is the information related to the request.
If you are encoding your password using MD5 and the likes, Json will not encode you can choose to unset the password from you your array or define the column you want to select from your database excluding password column.
Change your ajax as
$.ajax({
type:"POST",
url: 'php/loginrequest.php',
data:$("#form_id").serialize(),
dataType:"json",
success: function(data)
{
alert(data.UserName);
}
});
you can use both data:formData or data:$("#form_id").serialize(),
if you are getting alert message then everything is working fine

Loop Through json_encoded PHP Array in JavaScript

I am having an issue with looping through an array that was passed from PHP through an Ajax request.
For some reason my javascript thinks that either every character is a part of the array or my response variable is just being passed as a string.
Here is my javascript:
<script>
$(function() {
$.ajax({
url: "/dev/editButton/get_names.php",
success: function(response) {
console.log(response);
}
});
});
</script>
And here is my PHP:
<?php
include '../portfolio/libraries/settings.php';
$connect = mysqli_connect($HOST, $DB_USER, $DB_PASS, $DATABASE);
$query = "SELECT * FROM AUTH_User";
$result = mysqli_query($connect, $query);
$names = array();
while ($row = mysqli_fetch_array($result)) {
array_push($names, $row['FirstName']." ".$row['LastName']);
}
echo json_encode($names);
?>
The response that I get looks like this:
["Test Person","Test2 Person"]
However, if I loop through this using javascript or just print out response[0] I get each character as part of the array. The first element would be [, next would be ", etc.
I would like Test Person to be one element and Test2 Person to be another.
Does anybody know what I am doing wrong? Thanks!
You need to use JSON.parse on the response. Wihtout calling that function you are just getting the index of characters in the JavaScript string.
var resultArray = JSON.parse(response);
resultArray[0]; //Should Be "test Person"
The result of the .ajax method is interpreted according to the Content-Type header of the response. If it is incorrect or not specified, the response variable will contain the raw json code as a string.
So one solution is change the PHP code by adding this line:
header("Content-Type: text/json");
Docs:
The type of pre-processing depends by default upon the Content-Type of
the response, but can be set explicitly using the dataType option. If
the dataType option is provided, the Content-Type header of the
response will be disregarded.
You can parse that text to an object, or you can let JQuery do that for you by specifying a datatype in the call. The response parameter will then hold the object instead of the raw json string.
Docs:
If json is specified, the response is parsed using jQuery.parseJSON
before being passed, as an object, to the success handler. The parsed
JSON object is made available through the responseJSON property of the
jqXHR object.
$(function() {
$.ajax({
url: "/dev/editButton/get_names.php",
datatype: "json",
success: function(response) {
console.log(response);
}
});
});
In this particular situation, you can use
success: function(response) {
response = eval(response);
console.log(response);
}
But this is bad practice.
Really the best solution here is to modify your ajax call as follow:
$(function() {
$.ajax({
url: "/dev/editButton/get_names.php",
datatype: 'json',
success: function(response) {
console.log(response);
}
});
});
The specified datatype, will request the returned data to be json, and the jquery will automatically parse it to a javascript object.
You must parse JSON to array. You can do this using the following code:
var arr = $.parseJSON(response);
Now arr[0] should be "Test Person".
You can do it the hard way, or this way:
First, you need to specify the return type for AJAX.
$(function() {
$.ajax({
url: "/dev/editButton/get_names.php",
dataType: "json",
success: function(response) {
console.log(response);
}
});
});
Alternatively, you could do it this way:
$(function() {
$.getJSON("/dev/editButton/get_names.php", function(response) {
console.log(response);
});
});
For this to work, you will need to specify the HTML headers accordingly in PHP:
<?php
include '../portfolio/libraries/settings.php';
$connect = mysqli_connect($HOST, $DB_USER, $DB_PASS, $DATABASE);
$query = "SELECT * FROM AUTH_User";
$result = mysqli_query($connect, $query);
$names = array();
while ($row = mysqli_fetch_array($result)) {
array_push($names, $row['FirstName']." ".$row['LastName']);
}
header("Content-Type: application/json");
echo json_encode($names);
exit();
?>
The exit(); is just for safety so you wouldn't ruin the valid JSON format.
JSON stands for JavaScript Object Notation, so you should not have to do anything complicated there. Here is a simple loop you could use for example:
for(var i in response) {
console.log(response[i]);
}
Alternatively, if the response is not an array but an object with properties, you could loop through the object properties by getting the right keys first:
var objKeys = Object.keys(response);
for(var i in objKeys) {
var key = objKeys[i];
console.log(response[key]);
}
I hope this helps!

Prototype believes JSON from PHP is string

I have the following code in JS:
new Ajax.Request('http://www.some_random_url.com',
{
parameters: { start : this.start, stop : this.stop },
method: 'post',
onSuccess: function(transport){
var response = transport.responseText || "no response text";
alert("Success! \n\n" + response.posts);
$(response.posts).each( function(item) {
alert(item.title);
}
},
onFailure: function(){ alert('Something went wrong...') }
});
and then I have the following code in PHP. The function takes an array as an argument, and is meant to output JSON.
function view_api($array) {
header('Content-type: application/json');
echo json_encode(array('posts'=>$array));
}
Still, it seems to be treated by prototypejs as a string. When response is alerted, everything is fine. But the each loop in JS says response.posts is undefined.
Do you know why?
If it's returning the JSON as a string then you should parse it first.
var data = JSON.parse(payload);
use evalJSON() to typecast the response in JSON object as
var response = transport.responseText.evalJSON() || "no response text";
set evalJSON: 'force' in the prototype ajax request options. then use var response = transport.responseJSON
A neat trick with prototype.js is that you can pass the following headers and it will automatically be converted to json.
header('X-JSON: (' . json_encode($data) . ')');
header('Content-type: application/x-json');

Categories

Resources