Ajax HTTP request changes JSON with array in request body - javascript

The JSON response body of the HTTP request is being distorted on the server side. It has one key and its element is an array. This is my HTTP request using jQuery ajax:
function dbInsert(event_arr) {
$.ajax({
url: "http://localhost:5000/insertdata",
type: "POST",
data: JSON.stringify(event_arr),
success: function(events) {
console.log("TestInsert was successfully executed");
},
error: function(textStatus, errorThrown) {
console.error("The following error occurred: " + textStatus, errorThrown);
}
});
When I print JSON.stringify(event_arr) to console, this is what it looks like:
{"results": [{"event_client": "name1","event_date": "date1"}, {"event_client": "name2", "event_date": "date2"}]}
Then, on the server side, here are my various attempts at understanding the response body and playing around with the JSON format:
// returns [object, Object], cannot be passed into JSON.parse
console.log(request.body);
var temp = JSON.stringify(request.body);
var temp2 = JSON.parse(temp);
// prints {"{\"results\":":{"{\"event_name\":\"name1\",\"event_date\":\"date1\"},{\"event_name\":\"name2\",\"event_date\":\"date2\"}":""}}
console.log(temp);
// prints { '{"results":': { '{"event_name":"name1","event_date":"date1"},{"event_name":"name2","event_date":"date2"}': '' } }
console.log(temp2);
The JSON.stringify() that was called in my dbInsert() seems to mess up how the JSON is read, and I don't how to work around this internal formatting error!

You need to set: contentType: "application/json", in your $.ajax({}) function.
Something like this:
function dbInsert(event_arr) {
$.ajax({
url: "http://localhost:5000/insertdata",
type: "POST",
data: JSON.stringify(event_arr),
contentType: "application/json",
success: function(events) {
console.log("TestInsert was successfully executed");
},
error: function(textStatus, errorThrown) {
console.error("The following error occurred: " + textStatus, errorThrown);
}
});
}

Related

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 return Json data by calling an web-service through AJAX?

I have a web service which returns JSON data below code I am using for calling the web service.
jQuery.ajax({
url: 'http://localhost:5606/xyz',
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: '{"a":"b"}',
success: function(responses, textStatus, XMLHttpRequest) {
alert(responses);
},
error: function(xhr, err) {
console.log("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
console.log("responseText: " + xhr.responseText);
},
complete: function() {}
});
};
it return output of alert in success function as [object object] but I want it in proper json format.
You must read JSON.stringify()
use alert(JSON.stringify(data))
Example:
var response = {};
response.status ="success";
response.data="Your data";
alert(response); //It will give you [object object]
console.log(response); //Gives JSON data in console
alert(JSON.stringify(response)); //Alerts json string
if(response.status == "success")
//Pass response.data to the next webservice it will still be in the json format.

How to parse response as json object for cross domain ajax call?

I'm making a cross domain ajax call. When I heat the link directly from my browser, I get the json strin as follows:
But when I'm making an ajax call to this same URL, I'm not getting the json in my response. My ajax request is as follows:
$.ajax({
url: "http://172.16.201.14:801/api/apiclearing?trackNo=" + $scope.BillClearingModel.BillTrackingNo + "&&tokenNo=~Ice321",
dataType: 'jsonp',
success: function(response) {
console.log(response);
alert("Success");
},
error: function(response) {
console.log(response);
alert("Failed");
}
});
What Im getting in console is as follows:
Full Object is as follows:
What I'm missing here? Thanks.
Would you mind trying this:
var datastring = { "trackNo" : "160822000037" };//try this
//var datastring = "trackNo=160822000037"; //or this
$.ajax({
type: 'POST',//you may try the GET type
url: "https://172.16.201.14:801/api/apiclearing",
dataType: 'json',// try jsonp as well
data: datastring,
contentType: 'application/json',
crossDomain: true, //newly added
success: function(data, status, jqXHR) {
console.log(data);
console.log(status);
console.log(JSON.stringify(data));//to string
alert("Success");
},
error:function(jqXHR, textStatus, errorThrown) {
alert("Status:"+ textStatus + " Error:" + errorThrown);
}
You may consider as well to add Access-Control-Allow-Origin to your server like Access-Control-Allow-Origin: http://yourdomain-you-are-connecting-from.com in php

Ajax call error with JSON

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);
}
});

Get location from JSON in javascript

I am working now in a phonegap android application, I need the user's current address, so that i have used this
JSON api.
This is my code to get data for location updates from JSON api
$.ajax('http://maps.googleapis.com/maps/api/geocode/json?latlng=26.9008773,75.7403539&sensor=true', {
dataType: 'jsonp',
timeout: 3000,
data: {
_method: 'GET'
},
success: function (data,status) {
if (data._status != 200) {
console.log('received error', data._status);
// handle error
}else{
console.log('received data', data);
// do something useful with the data
}
},
error: function(data,status) {
var myObject = JSON.stringify(data);
console.log("Data Returned is " + myObject);
console.log("Status is " + status);
alert('error');
},
complete: function(data, status) {
alert('complete');
}
});
Every time it goes on error section , then the complete section, never goes into the success part.
the console output is :
12-10 11:11:34.393: I/Web Console(10620): Data Returned is {"readyState":4,"status":404,"statusText":"error"} at file:///android_asset/www/index.html:263
12-10 11:11:34.393: I/Web Console(10620): Status is error at file:///android_asset/www/index.html:264
Can anyone tell me, where exactly the problem is ?
If I remember correctly the default security policy in PhoneGap is to block all network access. You need to whitelist http://maps.googleapis.com.
The api you request does not support jsonp, the final request will like this:
http://maps.googleapis.com/maps/api/geocode/json?callback=jQuery18309743240959942341_1386656119920&latlng=26.9008773,75.7403539&sensor=true&_method=GET&_=1386656120107
with the callback param, but the output is still json, not javsscript file like
jQuery18309743240959942341_1386656119920(jsonDataHere...)
Take a look at this: https://developers.google.com/maps/documentation/javascript/examples/geocoding-reverse, it request url like this
https://maps.googleapis.com/maps/api/js/GeocodeService.Search?5m2&1d40.714224&2d-73.96145200000001&7sUS&9sen&callback=_xdc_._4cni6z&token=46423
And the output is:
_xdc_._4cni6z && _xdc_._4cni6z( { ....
That's jsonp.
ajax_call ='http://maps.googleapis.com/maps/api/geocode/json?latlng=26.9008773,75.7403539&sensor=true';
$.ajax({
type: "GET",
url: ajax_call,
cache:false,
dataType: "json",
success: function(response){
$.each(response.results, function(key, value) {
//alert(value.formatted_address);
console.log(value.formatted_address);
});
}
}).done(function() {
})

Categories