jquery not properly serializing json in ajax call - javascript

Let me start by saying I am not extremely familiar with Javascript and I cannot figure out what is going on here.
I have the following function:
self.search = function () {
var searchTerms = {
"City": this.cityName,
"State": this.stateName,
"StoreNumber": this.storeNumber,
};
$.ajax("/api/SearchApi", {
data: searchTerms,
type: "POST", contentType: "application/json",
success: function (result) {
alert(result);
}
}
});
When I submit, what happens is that instead of submitting a nice JSON object as expected, it submits a JSON objected formatted as so: "City=testing&State=AL&StoreNumber=test "
Ideally I would like to use a GET method that passes the object to my server so that I can return the results, but when I use a get method, it simply appends the above to the API call url resulting in a URL request formed as so: http://localhost:57175/api/SearchApi?City=testing&State=AL&StoreNumber=test
Any help would be appreciated.

Make sure you add the dataType of JSON to your $.ajax({ }); object. That should solve the problem!
$.ajax({
// ...
data : JSON.stringify( searchTerms ), // Encode it properly like so
dataType : "json",
// ...
});

2 Things
Add the json content type(not the data type) to your ajax object important to note is the charset your server is using in this case utf-8.
Use the Json2 Library to stringify and parse Json when sending and retrieving it can be found here : https://github.com/douglascrockford/JSON-js/blob/master/json2.js
$.ajax({
url: URL,
type: "POST",
//Stringify the data you send to make shure its properly encoded
data: JSON.stringify(DATA),
//This is the type for the data that gets sent
contentType: 'application/json; charset=utf-8',
//This is for the data you receive
dataType: "json"
}).done(function(data) {
var dataYouGet = JSON.parse(data);
}).fail(function(xhr, ajaxOptions, thrownError) {
}).always(function(data) {
});

Related

Populate a html div with json data received from a server

I need to have a html div populated with the json data received from the server which is a json-rpc server and it retruns an application/jsson-rpc content type and i can see the result in the chrome and firefox dev tools... I need to view it as part of the page inside a given div
i have this script to populate the mybox div but it gives nothing
var returnedinfo;
var request = $.ajax ({
url: "/url",
type: "POST",
data: JSON.stringify(data),
success: function(json) {
alert("success sent ajax");
$("#mybox").html(json);
returnedinfo = json;
});
I also tied having the populating function outside the ajax block when the request is done
request.done(function(msg) {
$("#mybox").text(msg);
});
This just return an empty array like this
[object Object]
and nothing else help will be appreciated.
you need to append the key of the json item.
$("#mybox").html(json.key);
Add dataType to your ajax request.
var request = $.ajax ({
url: "/url",
type: "POST",
data: JSON.stringify(data),
dataType: "json",
success: function(json) {
alert("success sent ajax");
$("#mybox").html(json);
returnedinfo = json;
});
try this my working example
look contentType and html function to replace html of mybox element
$.ajax({
type: 'POST',
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
url: 'url',
success: function (dataRes) {
$('#mybox').html(dataRes);
},
error: function(a,b,c) {
}
});
Note that in this case dataRes in success function is an html string like <strong>test</strong>. If your server side function returns a json object you should add dataType: 'json' to ajax request and then you can use properties of dataRes object like here $('#mybox').html(dataRes.property1);

How to use the response of Ajax Post

I make an ajax POST request to post JSON data to server, and I get a simple text response. I can see that everything works fine because it is shown in the browser's debugger. However, I cannot use it.
callajax1(Callback);
function callajax1(callbackfn) {
$.ajax({
type: "POST",
url: myUrl,
data: JSON.stringify({ Data: data }),
contentType: "text/plain; charset=utf-8",
dataType: "json",
success: function (data2) {
callbackfn(data2);
},
failure: function (errMsg) {
}
});
return false;
}
function Callback(data) {
alert(data);
}
No alert is showing.
You say that you are getting a "simple text response" back, but your JavaScript (dataType: "json") says to ignore the content type of the response and parse it as JSON.
Perhaps (since you are sending JSON and claiming it is plain text) you are confusing dataType (override the content type the server returns) and contentType (describe the data you are sending).
If the response is "simple text" and not JSON then you can't parse it as JSON. Either return JSON or use dataType: 'text'.
if result of ajax is text, datatype should be text
if result of ajax is html, datatype should be html
if result of ajax is json, datatype should be json
if result of ajax is xml, datatype should be xml
dataType tell jQuery to parse result in given dataType, default is 'text', though jQuery is intelligent enough to detect which conversion is required.
you can see the answer here:
http://jsfiddle.net/justtal/x9re9/
function callajax1(callbackfn) {
$.ajax({
type: "GET",
url: 'https://gdata.youtube.com/feeds/api/videos',
/*data: JSON.stringify({ Data: data }),*/
/*contentType: "text/plain; charset=utf-8",*/
/*dataType: "json",*/
success: function (data2) {
callbackfn(data2);
},
failure: function (errMsg) {
callbackfn(errMsg);
}
});
return false;
}
var Callback = function (data) {
alert(data);
}
callajax1(Callback);

Get parameter from JSON

In data from server I get the following JSON:
{
"response": {
"upload_url": "http:\/\/cs9458.vk.com\/upload.php?act=do_add&mid=6299927&aid=-14&gid=0&hash=73e525a1e2f4e6a0f5fb4c171d0fa3e5&rhash=bb38f2754c32af9252326317491a2c31&swfupload=1&api=1&wallphoto=1",
"aid": -14,
"mid": 6299927
}
}
I need to get upload_url. I'm doing:
function (data) {
var arrg = JSON.parse(data);
alert(data.upload_url);
});
but it doesn't work (alert doesn't show).
How do I get parameter upload_url?
It looks like you need to access arrg, not data. Also you need to access the 'response' key first.
function (data) {
var arrg = JSON.parse(data);
alert( arrg.response.upload_url);
}
There are several correct answers here, but there is one trigger that decides how you should handle your returned data.
When you use an ajax request and use JSON data format, you can handle the data in two ways.
treat your data as JSON when it returns
configure your ajax call for JSON by adding a dataType
See the following examples:
returned data string:
{"color1":"green","color2":"red","color3":"blue"}
ajax call without dataType:
$.ajax({
method: "post",
url: "ajax.php",
data: data,
success: function (response) {
var data = JSON.parse(response);
console.log(data.color1); // renders green
// do stuff
}
});
ajax call with dataType:
$.ajax({
method: "post",
url: "ajax.php",
dataType: "json", // added dataType
data: data,
success: function (response) {
console.log(response.color1); // renders green
// do stuff
}
});
In your case you probably used JSON.parse() when the call was already configured for JSON. Hope this makes things clear.
If response is in json and not a string then
alert(response.id);
or
alert(response['id']);
otherwise
var response = JSON.parse('{"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}');
response.id ; //# => 2231f87c-a62c-4c2c-8f5d-b76d11942301
Your code has a small error. try:
function (data) {
var arrg = JSON.parse(data);
alert(arrg.response.upload_url);
});

Can't query JSON using jQuery

I'm using jQuery to grab some JSON data. I've stored it in a variable called "ajaxResponse". I cant pull data points out of it; I'm getting ajaxResponse.blah is not defined. typeof is a string. Thought it should be an object.
var getData = function (url) {
var ajaxResponse = "";
$.ajax({
url: url,
type: "post",
async: false,
success: function (data) {
ajaxResponse = data;
}
});
return ajaxResponse;
},
...
typeof ajaxResponse; // string
ajaxResponse.blah[0].name // ajaxResponse.blah is not defined
make sure you specify option dataType = json
$.ajax({
url: url,
type: "post",
dataType: "json",
async: false,
success: function (data) {
ajaxResponse = data;
}
});
Q8-coder has the right of it, but to give you some details: your server is really passing back a string that you've formatted into JSON. You'll need to tell jQuery what to expect, otherwise it just assumes it received a string.
Add the following to your $.ajax options:
dataType: "json"
Also, refer to the jQuery API for examples and documentation for these options.

Passing js object as json to jquery?

I have the following but it's not working, I read somewhere on the stackoverflow that it works like this but I can't seem to get it to work.. it errors... am I doing something wrong?
If I do pass data like this - it works -- so I know my service is working
//THIS WORKS
data: "{one : 'test',two: 'test2' }"
// BUT SETTING UP OBJECT doesn't work..
var saveData = {};
saveData.one = "test";
saveData.two = "tes2";
$.ajax({
type: "POST",
url: "MyService.aspx/GetDate",
data: saveData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg.d);
},
error: function(msg) {
alert('error');
}
});
I believe that code is going to call .value or .toString() on your object and then pass over the wire. You want to pass JSON.
So, include the json javascript library
http://www.json.org/js.html
And then pass...
var saveData = {};
saveData.one = "test";
saveData.two = "tes2";
$.ajax({
type: "POST",
url: "MyService.aspx/GetDate",
data: JSON.stringify(saveData), // NOTE CHANGE HERE
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg.d);
},
error: function(msg) {
alert('error');
}
});
According to this blog post, the reason it doesn't work when you try to pass the object is that jQuery attempts to serialize it. From the post:
Instead of passing that JSON object through to the web service, jQuery will automatically serialize and send it as:
fname=dave&lname=ward
To which, the server will respond with:
Invalid JSON primitive: fname.
This is clearly not what we want to happen. The solution is to make sure that you’re passing jQuery a string for the data parameter[...]
Which is what you're doing in the example that works.
My suggestion would be to use the jquery-json plug-in and then you can just do this in your code:
...
data: $.toJSON(saveData),
...

Categories