I'm getting an error when trying to call an REST service using ajax. I'm trying to track down the error. The xhr.message is always coming in as undefined. Is there a better way to get the exact message as to why it is erroring?
$.ajax({
url: 'myurl.com/post/',
type: 'post',
data: query,
cache: false,
error: function (xhr, status, error) {
alert(JSON.stringify(xhr.message));
alert(JSON.stringify(status));
alert(JSON.stringify(error));
}
});
First, you should be using the newer (non-deprecated) format to make ajax calls
Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.
Here's an example:
$.ajax({
url: 'myurl.com/post/',
type: 'post',
data: query,
cache: false
})
.done(function(data) {
alert(JSON.stringify(data));
})
.fail(function (xhr, status, error) {
alert(JSON.stringify(xhr.message));
alert(JSON.stringify(status));
alert(JSON.stringify(error));
});
Second, message isn't a property (I don't think?) of the $.ajax call; it's statusthat you want, and it's just a text string. Try console.log(status), and same for xhr and error instead, and inspect the console to see what's being returned and what you want to retrieve.
Related
I am sending username and password as request parameter to the server in AJAX and trying to show the response message. But not able to showing the response message.In fiddler it is showing the response message. But while on the browser screen it is not showing.PLEASE somebody help me out where i am wrong or need to change anything..
I have written like this-
$(document).ready(function () {
$("#btnCity").click(function () {
$.ajax({
type: "POST",
url: "http://test.xyz.com/login",
crossDomain: true,
contentType: "application/json; charset=utf-8",
data: { username: "abc", password: "1234" },
dataType: "JSONP",
jsonpCallback: 'jsonCallback',
async: false,
success: function (resdata) {
alert(resdata);
},
error: function (result, status, err) {
alert(result.responseText);
alert(status.responseText);
alert(err.Message);
}
});
});
});
TL;DR: I guess the problem is on the server side of your code (that we don't know yet).
At first: I don't know why it fails for you. I've taken your code and ran it against a public available JSONP API, that returns the current IP of your system and it worked.
Please try yourself using the URL: http://ip.jsontest.com/.
So most probably, the server doesn't return the right response to the JSONP request. Have a look at the network tab in developer tools. With your current code, the answer of the server should be something like:
jsonCallback({'someResponseKeys': 'someResponseValue'});
Note: The header should contain Content-Type:application/javascript!
BTW, even if this doesn't for now solve your problem - here are some tweaks, I'd like to advice to you:
Don't set async to false, at the documentation of jQuery.ajax() says:
Cross-domain requests and dataType: "jsonp" requests do not support synchronous
operation.
You don't need to set a jsonpCallback, because jQuery will generate and handle (using the success function a random one for you. Quote from the docs:
This value will be used instead of the random name automatically generated by jQuery. It is preferable to let jQuery generate a unique name as it'll make it easier to manage the requests and provide callbacks and error handling.
So here comes my code:
$(document).ready(function () {
$("#btnCity").click(function () {
$.ajax({
type: "POST",
url: "http://ip.jsontest.com/",
crossDomain: true,
data: { username: "abc", password: "1234" },
dataType: "JSONP",
success: function (resdata) {
console.log("success", resdata);
},
error: function (result, status, err) {
console.log("error", result.responseText);
console.log("error", status.responseText);
console.log("error", err.Message);
}
});
});
});
A working example can be found here.
Another solution, like Yonatan Ayalon suggested, can be done with a predefined function and then setting the jsonpCallback explicitly to the function that should be called.
if you see the response in Fiddler, it seems that the issue is in the callback function.
you are doing a jsonP call - which means that you need a callback function to "read" the response data.
Do you have a local function that calls "jsonCallback"?
this is a simple jsonP request, which initiates the function "gotBack()" with the response data:
function gotBack(data) {
console.log(data);
}
$.ajax({
url: 'http://test.xyz.com/login' + '?callback=?',
type: "POST",
data: formData,
dataType: "jsonp",
jsonpCallback: "gotBack"
});
You can try with the following methods and close every instance of chrome browser in task manager, then open browser in web security disable mode by the command "chrome.exe --disable-web-security"
success: function (resdata) {
alert(resdata);
alert(JSON.stringify(resdata));
},
And the better option to debug the code using "debugger;"
success: function (resdata) {
debugger;
alert(resdata);
alert(JSON.stringify(resdata));
},
I wanted to retrieve data using ajax, when open the url in browser it showing data but when i execute this url in ajax code error msg function is running however data is showing in browser.
url: "http://live.nayatel.com/?json=1"
$(document).ready(function() {
$.ajax({
type: "GET",
url: "http://live.nayatel.com/?json=1",
cache: false,
success: onSuccess,
error: onError
});
});
its a wordpress site and i used a plugin to retrive its data working in browser but not giving response text.
I have two suggestions, since I am not that sure about your problem.
a) Try changing
success: onSuccess,
to
success: function(data, status) {
onSuccess(data, status);
},
b) If that fails, try adding
crossDomain: true,
I have a very basic ajax call to alert the data that was reported from the server
$.ajax({
type: "POST",
url: "/someform/act", //edit utl to url
data: { changed: JSON.stringify(plainData) }, //edit to include
success: function(data) {
alert(data); //data not $data
},
error: function() {
//error condition code
}
});
According to the docs on the jquery website regarding data field on the success callback, it says that data returned is the data from the server. However for some strange reason when I alert $data, I get [object Object]
I was expecting to see something like this, since that is what the server would send back
<status>0</status>
EDIT:
data is also passed along as the POST
You need to use JSON.stringify(data) in the alert to get anything readable.
Also, $data is a completely different variable name than data.
alert() prints the string representation of the arguments - hence if you pass an object, you'll get [object Object].
To inspect data, use console.log(data) better.
If you server send a JSON, you need to put dataType: 'json' to your ajax call. Be aware there's some mistake in your ajax call.
$.ajax({
type: "POST",
url: "/someform/act", // NOT 'UTL',
data: {
key: value,
key2: value2
},
// or data: plaindata, // If 'plaindata' is an object.
dataType: 'json',
success: function(data) {
console.log(data); // As moonwave99 said
},
error: function() {
//error condition code
}
});
EDIT
When sending data, you should send an object. jQuery will handle the array to sned it to the server. So if plain data is an object, it should be like this
data: plainData,
If you're sending data via $.ajax({...}), the Network tab of your browser inspector might be showing [object Object] in the Payload (Chrome) / Request (Firefox) sub-tab, like in the following image (Firefox):
The reason for this might be in the way you're forming your AJAX call. Specifically:
$.ajax({
url: '/ajax/example-endpoint',
data: {'fooKey':fooData,'barKey':barData},
type: 'post',
cache: false,
contentType: false, // this one will turn your data into something like fooKey=fooData&barKey=barData
processData: false, // and this one will make it [object Object]:""
beforeSend: function() {
// whatever it is you need to do
},
success: function(data) {
// do stuff
},
error: function(desc, err) {
// do stuff
}
});
When combined, contentType: false and processData: false turn your data into [object Object], because you're actually telling your AJAX call to ignore the content type of whatever is being sent, and not to process it.
If it's IIS, try creating a site outside of the Default Web Site (for example localhost/ajax1). For example a new site ajax1, place it not in the DefaultAppPool, but in your pool, for example ajax1. Try http://ajax1
I upgraded my page from using jquery 1.4.4 to jquery 1.9.1 and suddenly my ajax calls stopped working. If i revert to jquery 1.4.4 it works again. I am getting below error.
No conversion from text to string
Below is my code
$.ajax({ url: "/Reporting/RunQuery",
type: "Post",
data: { prm_Query: qrytxt }, dataType: "string",
error: function (XMLHttpRequest, status, error) {
debugger;
alert("The following error occured while adding data: " + error);
},
success: function (data) {
debugger;
$('#divQuerytextarea').html('').append(data);
}
});
My call to /Reporting/RunQuery succeeds and it has valid return string in the RunQuery method. Then it falls into error: of ajax call with 'No conversion from text to string' error.
Not finding much in google for this. Any help is appreciated.
I agree with Kevin. I was having the same problem just because I've put :
dataType: JSON
instead of :
dataType: "json"
after what everything worked fine.
Be aware that this "dataType" property commes from the HTTP head where there is the MIME type wich is the type of the resource called by the HTTP request. So there is no "string" type. You should use "text" instead (if you want a string, of course).
I'm successfully posting to my controller with the following code, however, success is never being hit only error. What am I doing wrong?
JS:
$.ajax({
url: '/Home/Subscribe',
type: 'POST',
dataType: 'json',
data: { email: $('#sube').val() },
success: function (data) {
// get the result and do some magic with it
alert(data.foo);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
Controller:
[HttpPost]
public JsonResult Subscribe(string email)
{
return Json(new { foo = "bar", baz = "Blech" });
}
In IE, press F12 to open developer tools. Go to Network tab and click on Start Profiler. Send a request to your Subscribe action - in a list below you will see details of sent request and returned status code. Double click on request to see details - you can then see body of your response. If the request failed with a server error, you will see that error in a body of your response.
One wrong thing I see with your code is that you have hardcoded the url:
url: '/Home/Subscribe'
You should never do this. You should always use url helpers when generating urls in an ASP.NET MVC application:
url: '#Url.Action("Subscribe", "Home")'
Also you are saying that the error callback is always hit but you didn't say what you observed in FireBug or Chrome Developer toolbar when you tried to analyze the AJAX request. If you had done this you would have seen the exact cause of failure for the request because you would have seen what request is sent to the server and what response does the server sends back to the client.
The following is my jQuery ajax snippet that works. Your controller looks right. I assume you have verified it is actually getting called by using a breakpoint.
var p = {
email: $('#sube').val()
};
$.ajax({
url: '#Url.Action("Subscribe", "Home")'
type: 'POST',
data: JSON.stringify(p),
dataType: "text json",
contentType: "application/json",
success: function (data) {
// get the result and do some magic with it
alert(data.foo);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});