Sending JSON data with jQuery not working - javascript

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.

Related

Unexpected token in JSON at positon 0

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;

Removing the first line from a JSON response

My current code is :
$.getJSON("https://www.domain.com/someapi/callback=?",
function(data){
$.each(data, function(i,item){
alert(item.x);
});
});
Right now I'm getting an error because they're adding a line to the top of my json response. is there a way to get rid of that line?
Thanks!
UPDATE:
I have also tried doing something like this:
$.ajax({
url: "https://www.domain.com/someapi/callback=?",
type: "get",
success: function (data) {
alert(data)
}
});
but it's a crossdomain call, so i get that error.
Make a ajax normal request
$.ajax({
url : "https://www.domain.com/someapi/callback=?",
success : function(result){
// So here we get the result json with an error
// So lets say the response is something like this
/*
There was an error on line 35
{
json : true
}
*/
// So we remove everything before the first '{'
result = result.replace(/[^{]*/i,'');
//We parse the json
var data = JSON.parse(result);
// And continue like no error ever happened
$.each(data, function(i,item){
alert(item.x);
});
}
});
I hope this work. (a cross domain request must be enabled from the server)

Post JSON data to server and parse the response in JavaScript

I need to POST the JSON format data to the server URL. The server will send the response in same JSON format. I need to parse it and get the data. How to do it? please help me with an example.
at client side (to convert into the json)--->
var myJSONText = JSON.stringify(myObject, replacer);
& at server side to get the actual data--->
var dynObj = JsonConvert.DeserializeObject(myJSONText);
php--->
<?php
$jsonTxt = '{"abc":1111,"xyz":222}';
var_dump(json_decode($jsonTxt));
var_dump(json_decode($jsonTxt, true));
?>
You can use JSON.parse() which may be supported in most browsers.
var response = {"success":true, "data":"My data"};
var json_res = JSON.parse(response);
console.log(json_res.data)
Alternatively, if you are using some javascript library, for example jQuery you may have an helper. See this similar question
Should look something like this.
var data = $(":input").serializeArray();
$.ajax({
url: url,
data: JSON.stringify(data),
type: "GET",
dataType: 'json',
contentType: 'application/json'
});
On Server side :
public static function createFromJson( $jsonString )
{
$object = json_decode( $jsonString );
return new self( $object->firstName, $object->lastName );
}

Jquery JSON response handling

I have an ajax query written in jQuery that is returning valid JSON in this format
$.ajax({
type : 'POST',
url : 'ajax/job/getActiveJobs.php',
success : function(data){
if(data[''] === true){
alert('json decoded');
}
$('#waiting').hide(500);
$('#tableData').html(data['content']);
$('#message').removeClass().addClass((data.error === true)
?'error':'success').text(data.msg);
if(data.error === true)
$('#message')
},
error : function(XMLHttpRequest, textStatus, errorThrown){
$('#waiting').hide(500);
$('#message').removeClass().addClass('error').html(data.msg);
} })
I take it this is not correct as it is not displaying the data, if I use
$('#mydiv').html(data);
I get all of the data back and displayed.
any help is really appreciated
Set the dataType to be json so jQuery will convert the JSON to a JavaScript Object.
Alternatively, use getJSON() or send the application/json mime type.
Either set dataType to json or use var json = JSON.parse(data) to do it manually.
EDIT:
I'm adding this because somebody else suggested eval, don't do this because it gets passed straight into a JSON object without any sanitation first, allowing scripts to get passed leading straight into an XSS vulnerability.
The data is the Json so you will want to do this:
success: function (data) {
var newobject = eval(data);
alert(newobject.msg);
}
or do this:
$ajax({
url: url,
data: {},
dataType: "json",
success: function (newObject) {
alert(newobject.msg);
}
});

how to know if the result of an ajax request is json?

I'm doing an ajax request using $.get and as result I could get a simple string or JSON, how to know if the result is JSON (object) or not ?
EDIT:
can I return a string and somehow transform it into object/JSON ?
Its not 100% but server probably set responce header: Content-Type: application/json. So you can try to check it:
$.ajax({
url: 'url',
success: function(data, textStatus, xhr){
var spoiler = xhr.getResponseHeader('Content-Type');
spoiler == 'application/json' ? alert('JSON received') : alert('Not JSON received');
}
});
Sure, it worked only if your server sets its headers in correct way.
One more way - is try to create a function and catch errors you may have.
try {
x = ( new Function('return ' + received_data) )();
}
catch (e) {
console.log('Its not a JSON data... or its invalid.');
}
Use the typeof method to determine if it's an object or a String. If you want to convert a String to a JSON object, and if you trust the source you can use eval. Otherwise use a JSON parser, such as http://www.json.org/json_parse.js
Usually you would expect to know what the data type is, but if for some reason you don't, how about checking the 'Content-Type' header. In theory it should be 'application/json':
function responseHandler() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
if(http_request.getResponseHeader("Content-Type") == 'application/json') {
// JSON
}
else {
// Not JSON
}
}
}
}
Of course, you'll have to check that the server is setting the Content-Type header correctly. Also, not sure if this will work in IE- probably not.
You can use getJSON() instead
http://api.jquery.com/jQuery.getJSON/
For the edit:
You can use
$.ajax({
type: 'get',
cache: false,
url: service,
error: function(XMLHttpRequest, textStatus, errorThrown){
failureFunction(XMLHttpRequest, textStatus, errorThrown);
},
success: function(data){
successFunction(data);
},
dataType: 'text'
});
With dataType Text, and parse for JSON from there.
jQuery.parseJSON( json ) - http://api.jquery.com/jQuery.parseJSON/
You should know. Each url should only return one type of data.
You know how the data is coming and you can do a null check to
Like
if it is a string constructed json , do a Eval of result
IF(EmployeeDetails.SalaryDetails.lenght)
{
forloop()
}

Categories

Resources