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);
Related
Hello I'm performing a GET request on a RESTful Rails resource, like so:
function getGroups(category) {
$.ajax({
type: 'GET',
url: 'http://localhost:3000/groups.json',
data: JSON.stringify({"access_token":"569669d8df0456", "category":category }),
success: function(data) {alert(data)},
contentType: "application/json",
dataType: 'json'
});
});
getGroups("own_groups");
The problem is that Webrick server errors out like this:
ERROR bad URI
`/groups.json?{%22access_token%22:%22569669d8df0456%22,%22category%22:%22own_groups%22}'.
It must be something related with how the JSON data is parsed, because I am having no problems with another GET request WITHOUT JSON data, and a POST request WITH JSON data...
Update: adding code for POST request (where JSON.stringify is required)
function addGroup(name, description) {
$.ajax({
type: 'POST',
url: 'http://localhost:3000/groups.json',
data: JSON.stringify({"access_token":"569669d8df0456", "group_name":name, "group_description":description}),
success: function(data) { alert("ok")},
contentType: "application/json",
dataType: 'json'
});
};
addGroup("nice group", "full of people");
Do not use JSON.stringify. Simply put:
data: {"access_token":"569669d8df0456", "category":category },
Moreover, you do not need to specify complete url http://localhost:3000/groups.json, it can be just simply groups.json
I have an AJAX script like this
function savetoDB(inp) {
var userID = (FB.getAuthResponse() || {}).userID;
jQuery.ajax({
url: URL,
type: 'GET',
data:{ 'input': JSON.stringify(inp) },
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: true,
success: function(msg) {
console.log(msg);
alert(msg);
}
});
}
The problem I am facing is that the php returns (echo's) some string , but I am unable to see it in alert.
I used the inspect element and Inside inspect element I can see the Response, and also the status is 200, what could be the reason that it is not showing the response in alert?
You are returning a JSON object, so it won't show in alert, which only displays strings. Convert it to a string first:
success: function(msg) {
console.log(msg);
alert(JSON.stringify(msg));
}
Replace "URL" with the actual url of file you're extracting data from otherwise you'll get an empty response as is the case.
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);
In this SO post I learned how to get a return value from an AJAX call:
function CallIsDataReady(input) {
$.ajax({
url: "http://www.blah.com/services/TestsService.svc/IsDataReady",
type: "GET",
contentType: "application/json; charset=utf-8",
data: input,
dataType: "json",
success: function (data) {
if (!data) {
setTimeout(function (inputInner) { CallIsDataReady(inputInner); }, 1000);
}
else {
//Continue as data is ready
callUpdateGrid(input);
}
}
});
}
$(document).ready(function () {
var input = { requestGUID: "<%=guid %>" };
CallIsDataReady(input);
});
This function calls its web service wich does return true. The problem is that inside the following callUpdateGrid, the logging shows that that web service method is not getting called from the $.ajax call:
function callUpdateGrid(input) {
console.log(input);
$.ajax({
url: "http://www.blah.com/services/TestsService.svc/GetContactsDataAndCountbyGUID",
type: "GET",
contentType: "application/json; charset=utf-8",
data: input,
dataType: "json",
success: function (data) {
var mtv = $find("<%= RadGrid1.ClientID %>").get_masterTableView();
console.log(data);
mtv.set_dataSource(data.d.Data);
mtv.dataBind();
}
});
}
Anyone know what is wrong?
It is always a good idea to include an error handler function as one of the options passed to $.ajax. For example, add this code after your success functions:
,
error: function(jqXHR, textStatus, errThrown) {
console.log("AJAX call failed");
console.log(errThrown);
}
That will log at least a bit of information if the $.ajax call doesn't succeed.
EDIT
According to your comment, this logs
SyntaxError: Invalid character
And in fact, I now see that you are giving a plain JavaScript object as the data option passed to $.ajax, but indicating that it is a JSON object in the dataType field. You need to actually convert the input object into JSON yourself, like so:
data: JSON.stringify(input),
dataType: 'json',
Alternatively, you could simply format input as a JSON object in first place, like so:
var input = { "requestGUID": "<%=guid %>" };
The quotes around the field name requestGUID are sufficient, in this case, to give you a JSON object.
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) {
});