Ajax call error with JSON - javascript

I am making an ajax call below and getting an error I do not understand. The variable response in the success function looks like
{"status": "complete", "username": "test", "error": "0", "message": ""}
however when I call my three alert functions inside the success function, the first one prints out the value above, but the next two print out undefined. I know the error key exists, however the javascript does not recognize it. As a result my window crashes.
$.ajax({
url: '/index.php/api/userLogin',
data: userInfo,
datatype: 'json',
async: 'false',
type: 'POST',
success: function(response)
{
alert(response); //prints correct response
alert(response.error); //prints undefined
alert(response["error"]); //prints undefined
},
error: function(xhr, status, error)
{
var err = eval("(" + xhr.responseText + ")");
//alert("Please Try Again, we had an internal error!");
alert(err.message);
}
});
Can somone explain what is happening and how to fix this?

This is due to a combination of two factors:
The server is sending the JSON with the wrong content type
You've used the wrong capitalization for overriding it
Consequently, jQuery is interpreting the JSON as (probably) plain text (which is why alerting the value gives you the raw JSON and not [Object object]).
You should fix this by making sure the server sends the JSON with:
Content-Type: application/json
Since it looks like you are using PHP, you can do that with:
header("Content-Type: application/json");
You should also either remove datatype: 'json' or change it to dataType: 'json'.

that because response is not parse as JSON object to do that you can do it like this:
$.ajax({
url: '/index.php/api/userLogin',
data: userInfo,
datatype: 'json',
async: 'false',
type: 'POST',
success: function(response)
{
var data = jQuery.parseJSON(response); // <---- Here parse it as JSON
alert(data.error);
// Todo with data
},
error: function(xhr, status, error)
{
var err = eval("(" + xhr.responseText + ")");
//alert("Please Try Again, we had an internal error!");
alert(err.message);
}
});

Related

How do I access this json object inside this api?

I'm trying to access an item in an api so I can start getting data from the json file, but I can't seem to get anything to work. I'm unable to log any of the data I'm trying to access to the console.
$(function() {
$.ajax({
type: 'GET',
url: "xxx",
dataType: 'json',
success: function(data) {
return console.log('success', data);
return console.log(data[0].id);
},
beforeSend: function(xhr, settings) {
xhr.setRequestHeader('Authorization', 'Bearer ' + 'xxx');
}
});
});
It isn't working because you are returning before the second console.log. the return statement is used to exit a function at that line and return the value of the rest of the line. You are returning then trying to do something after the return which actually is never ran.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/return
Remove the return statements and it should work.
$.ajax({
type: 'GET',
url: "xxx",
dataType: 'json',
success: function(data) {
console.log('success', data);
console.log(data[0].id);
},
beforeSend: function(xhr, settings) {
xhr.setRequestHeader('Authorization', 'Bearer ' + 'xxx');
}
});
1) You have a problem with returning before the Id is logged to the console, as you are returning it before your you logging your Id, a return statement ends the function execution. so removing the return will do the work
2) you don't really need to console.log() everything you can just put a 'debugger;' instead of return and you can reload the page with an open console window, it will pause the code execution at the debugger; and you can hover on the 'data' being received in the success function to see all the data being received on a successful AJAX call. hope this helps

Error: Invalid data; couldn't passe JSON object, array, or value

I am having a problem when trying to make POST or PUT requests to Firebase RESTful API...
To make the request I am using Valve's Panorama JavaScript which execution is handled by Google V8 engine.
A GET request (which works without problems) looks like this:
$.AsyncWebRequest("https://<project>.firebaseio.com/-KrFV19WfaC7tfY6qys6.json",
{
type: "GET",
complete: function (data){
$.Msg("WOW: " + JSON.stringify(data));
},
error: function (err){
$.Msg("Error: " + JSON.stringify(err));
},
});
And I get the response:
WOW: {"statusText":"success","responseText":"{\"a\":\"1\"}\u0000","status":200}
But when I try to do a PUT or POST request which code looks like this:
$.AsyncWebRequest("https://<project>.firebaseio.com/game.json",
{
type: "POST",
data: {"A":"B"},
success: function (data){
$.Msg("WOW: " + JSON.stringify(data));
},
error: function (err){
$.Msg("Error: " + JSON.stringify(err));
},
});
I get the next response:
Error: {"statusText":"error",
"responseText":"{\n \"error\" : \"Invalid data; couldn't parse JSON object, array, or value.\"\n}\n\u0000",
"status":400}
Can somebody help me understand what could be the problem?
Update
According to this piece of code
you have to wrap your object in a payload property:
data: {payload: JSON.stringify({ "A": "B" })},
Have to tried to use JSON.stringify() around your request data object?
Like:
$.AsyncWebRequest("https://<project>.firebaseio.com/game.json",
{
type: "POST",
data: JSON.stringify({"A":"B"}),
success: function (data){
$.Msg("WOW: " + JSON.stringify(data));
},
error: function (err){
$.Msg("Error: " + JSON.stringify(err));
},
});
Also, is there a contentType property in AsyncWebRequest?
So maybe you have to add
contentType: "application/json; charset=utf-8",
to the request object (after the type property for example).

how to use ajax to get a json file in github

I want to use ajax to get a json file in github, I wrote this code:
$.ajax({
url: "https://rawgit.com/nianyuyu/play_javascript/master/1.json",
type:"get",
dataType:'json',
success: function(data){
console.log(data);
},
error:function() {
console.log("err");
}
});
but I always get "err" and I check the network , it gets the data
How can I solve this problem, thank you!
Since you have included dataType:'json', in your request, jQuery will validate the returned JSON. In this case, the returned JSON has a semi-colon at the end of the body which is not valid JSON.
{
"name":"Bill Gates",
"street":"Fifth Avenue New York 666",
"age":56,
"phone":"555 1234567"
};
Remove the semi-colon to prevent the error handler from being called.
I think you are getting a parse error which is causing the issue, you can fix the json response or you can remove data type json from you request.
You will get parse error, if your json response is not valid and you are using dataType: 'json'. you can change it dataType: 'text'
$.ajax({
url: "https://rawgit.com/nianyuyu/play_javascript/master/1.json",
type:"get",
dataType: 'text',
error: function(data){
//debugger;
alert('err');
},
success:function(data) {
alert(data);
}
});
Reference: jQuery returning "parsererror" for ajax request
1.json file is incorrect. At the end there is a semi colon. Remove that semi colon and it will work fine.
if you dont have access to that file then you can use the following code.
$.ajax({
url: "https://rawgit.com/nianyuyu/play_javascript/master/1.json",
type:"get",
dataType:'text',
success: function(data){
console.log(JSON.parse(data.substring(0, data.length - 1)));
},
error:function() {
console.log("err");
}
});
Here I basically get the string and trim its last character and then parse the string back to JSON object.
You are receiving the data in error because you are expecting a JSON response where as the actual response is not a valid JSON.
It has semicolon at the end, it makes a invalid JSON.
Try dataType as text. Here you go with the example https://jsfiddle.net/sfjxsdsx/1/
$.ajax({
url: "https://rawgit.com/nianyuyu/play_javascript/master/1.json",
type:"get",
dataType:'text',
success: function(data){
console.log(data);
},
error:function() {
console.log("err");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Based on the error, parsererror, the url doesn't seem to return valid JSON, while the call expects it to be JSON (dataType: 'json')
You can tell jQuery to parse it as text (using dataType: 'text') and then convert it to JSON manually using JSON.parse.
You'll have to trim out the last ; before you parse.
On a side note, you can use the parameter passed into the error callback to print out the error.
Fixed code:
$.ajax({
url: "https://rawgit.com/nianyuyu/play_javascript/master/1.json",
type: "get",
dataType: 'text',
success: function(response) {
if (!response)
return;
response = response.slice(0, -1); // trim ";" at the end
var data = JSON.parse(response); // convert to object
console.log(data);
},
error: function(err) {
console.log(err);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

jquery ajax request with json throwing parsererror

I have searched lot of on this issue and tried almost everything but it doesn't seem to be work so posting it here.
I am trying to make jquery ajax call to ashx handler by passing json data. But my request doesnt reach till handler GetBalance.ashx
code :
var mydata = {};
$.ajax({
url: 'Handlers/GetBalance.ashx?type=authenticateRequest',
type: 'post',
dataType: 'json',
cache: false,
data: mydata,
success: function (data) {
},
error: function (xhr, status) {
console.log(status);
console.log(xhr.responseText);
}
});
in console it prints
parsererror
(empty string)
What i am doing wrong ? It should reach till .ashx before it gives any response parse error
Edit:
Changed as suggested by answer
Replace your line
data: mydata,
with
data: JSON.stringify(mydata),
contentType: "application/json",

AJAX call returning data but failing

I've been trying to make an ajax call to retrieve some data from a database but i don't know why is returning an error.
there's the code
$('#afegir_pagament').submit(function() {
var import_pagament = $('#import_pagament').val();
var id_reserva = $('#id_reserva_hidden').val();
url = "afegir_pagament.php";
data = {import: import_pagament, id_reserva: id_reserva};
$.ajax({
url: url,
dataType: 'application/json',
type: 'post',
data: data,
complete: function(xhr, statusText) {
console.log(xhr.responseText);
},
success: function(responseText) {
$('#pag_import_pagat_propietari').val(responseText.total);
},
error: function(req, status, err) {
alert('Error');
}
});
return false;
});
console.log(xhr.responseText) returns {"total":"230.00"}
ERROR: no conversion from text to application/json
Could somebody help me?
"application/json" is not a valid value for the dataType property. Change it to "json".
See here (comment #7):
Thanks for the report, but this is not a jQuery bug. application/json is not a valid value for the dataType property.
Just change application/json to datatype :"json" and exactly what you trying to do inside the
success function ..if you trying to display this value in your text field just try this..
$("#pag_import_pagat_propietari").attr("#yourid",responseText.total);

Categories