I have an AJAX call:
$('#testyo').click(function(){
$.ajax({
type: 'GET',
url: "../messages/drew",
dataType: 'JSON',
success:function(data){
alert(data);
},
error: function(data)
{
console.log(data);
alert("Error: "+data);
}
});
return false;
});
It should be successful, but I get the alert("Error: "+data) alert. The data is [object Object]. So the alert just says Error: [object Object]
In my console.log(data)
Object {readyState: 4,
getResponseHeader: function,
getAllResponseHeaders: function,
setRequestHeader: function,
overrideMimeType: function…}
abort: function ( statusText ) {always: function () {complete: function () {done: function () {error: function () {fail: function () {getAllResponseHeaders: function () {getResponseHeader: function ( key ) {overrideMimeType: function ( type ) {pipe: function ( /* fnDone, fnFail, fnProgress */ ) {progress: function () {promise: function ( obj ) {readyState: 4responseText: "drew"setRequestHeader: function ( name, value ) {arguments: nullcaller: nulllength: 2name: ""prototype: Object__proto__: function Empty() {}<function scope>state: function () {status: 200statusCode: function ( map ) {statusText: "OK"success: function () {arguments: nullcaller: nulllength: 0name: ""prototype: Object__proto__: function Empty() {}<function scope>then: function ( /* fnDone, fnFail, fnProgress */ ) {__proto__: Object
As you can see it does show the responseText: "drew" which is what I want. I'm just curious to know why is passing through my fail function, and not my success. Please let me know if there is anything else you would need to help me solve this.
According to the jquery documentation, the error parameter takes three inputs as parameters:
error:
Type: Function( jqXHR jqXHR, String textStatus, String errorThrown )
A function to be called if the request fails. The function receives
three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a
string describing the type of error that occurred and an optional
exception object, if one occurred. Possible values for the second
argument (besides null) are "timeout", "error", "abort", and
"parsererror". When an HTTP error occurs, errorThrown receives the
textual portion of the HTTP status, such as "Not Found" or "Internal
Server Error."
The errormessage, and the error can be viewed if you modify the error function to take three parameters input and access the second argument to know what the error string is.
If you do this, it becomes easy to spot the error and know why the request failed. Once you spot the error, it becomes easy to fix it.
unexpected token probably means you've got a corrupted JSON response from the server. Also make sure the response the server component sends is of type JSON.
Set the response type in the server, for example, if the response is json:
response.setContentType("application/json");
See Also:
What is the correct JSON content type?
Refer: http://api.jquery.com/jquery.ajax/
I see you get a 200 response but probably your server returns the wrong content type for json or it's completely invalid json.
In Firefox with firebug or chrome try to inspect the response and response headers like content type.
https://stackoverflow.com/a/11112320/1641941
When your responseText returns "drew", your response is not JSON, but String. Remove dataType: 'JSON' and jQuery will use auto detection. Then success function will be called.
JSON should be something like {"myText": "drew"}.
Related
AJAX error is being returned as Success. How to return JSON error from ASP.NET MVC? Could you tell me what I'm doing wrong? Thank you.
[HttpPost]
public JsonResult Register(int EventID)
{
try
{
// code
return Json(new { success = true, message = "Thank you for registering!" });
}
catch (Exception ex)
{
return Json(new { success = false, message = ex.Message });
}
}
$.ajax({
url: "#Url.Action("Register", "Home")",
type: "post",
dataType: "json",
contentType: "application/json",
data: JSON.stringify(postData),
success: function(data) {
},
error: function (data) {
}
});
The error function gets executed only when the HTTP Response Code is not HTTP 200 Ready. You handle the error in the server-side and return proper response, which will be picked up by success function in the AJAX call. Instead, use the status variable in your JSON and handle it on the client side:
success: function(data) {
if (typeof data == "string")
data = JSON.parse(data);
if (data.success) {
// Code if success.
} else {
// Code if error.
}
},
From the docs (scroll down to the error section):
A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and cross-domain JSONP requests. This is an Ajax Event.
The Ajax error method is hit only when you get a Yellow Screen Error in the server side. In your scenario you are handling the error using try catch and returning a valid response. So this is not considered as a error but a valid response. Remove your try catch so that Ajax will pick up the error event, else if you want to show the actual error message from server then you can use the success property to decide if the response was a success or a error , its similar to what Praveen has already posted in his answer.
success: function(data) {
if (data.success) { //as you are passing true/false from server side.
// Code if success.
} else {
// Code if error.
}
},
All of my other searches yield responses about cross-domain requests. It appears that I'm not having a problem with that. I'm getting a response from the recaptcha server, but it's not being interpreted correctly.
<script>
function verifyCaptcha() {
jQuery.ajax({
method: "POST" ,
url: "https://www.google.com/recaptcha/api/siteverify",
data: { secret: "xxxxxxxxxxxxxxxxxxx" , response: "<% $recaptcha_response %>" },
dataType: 'jsonp' ,
success: function( result ) {
alert( result.success ) ;
},
error: function( xhr ) {
alert('Request Status: ' + xhr.status + ' Status Text: ' + xhr.statusText + ' Response Text: ' + xhr.responseText);
}
})
}
onload=verifyCaptcha ;
</script>
This function lives in a page that's the target of a submitted form. When I check fireBug for the results, I get this in my alert message:
Request Status: 200 Status Text: success Response Text: undefined
And the response captured by FireBug is
{
"success": true
}
It seems that it gets mad without the parens wrapped around the returned JSON which I thought were supposed to come free with dataType: 'jsonp'
How do I resolve the success of this?
UPDATE
Adding additional return parameters to the error funcion: ( xhr , message , errorThrown ) produced the following:
Request Status: 200
Status Text: success
Response Text: undefined
Message: parsererror
ErrorThrown: Error: jQuery1120043068059910713263_1455115913634 was not called
I'm guessing that the jQuery1120043068059910713263_1455115913634 was not called message is the callback function randomly named by jQuery. Does this mean that I need to add something to my logic, or that the reCaptcha server does not indeed support jsonp ?
Setting the dataType to "json" gives me a request status of 0.
UPDATE 2
I added this to my function:
jsonp: false,
jsonpCallback: 'onJSONPLoad',
and my errorThrown text changed to:
Error: onJSONPLoad was not called which leads me to conclude that reCaptcha does not support jsonp. Can anyone confirm this?
I guess the Answer is:
The POST method is not available for jsonp, only GET
update:
As well as in the comment stated setting the dataType to"json" and it will automatically converted to jsonp, maybe try that
also you can add a third argument to the error function
error: function( xhr, message, errorThrown ) {
and errorThrown maybe is more explicit
I am making the following jquery ajax call to a codeigniter php function:
$.ajax({
type:"POST",
url: "AjaxUpdate/getHtml",
data:{ u : 'http://stackoverflow.com/' },
dataType: 'json',
success: function(data) {
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log('error');
console.log(jqXHR,textStatus, errorThrown);
}
});
The requested php function is :
public function getHtml() {
$url = $_POST['u'];
$result = file_get_contents($url);
return json_encode($result);
}
How can I fix this?
edit: the error in the console shows:
error
reply_detail:4667 Object {readyState: 4, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function…} "parsererror" SyntaxError: Unexpected end of input {stack: (...), message: "Unexpected end of input"}message: "Unexpected end of input"stack: (...)get stack: function () { [native code] }set stack: function () { [native code] }__proto__: Error
Some things may be happening.
I don't know PHP, but is getHtml REALLY returning a JSON?
Maybe it is failing to parse the returning content. There are other options in the JQuery $.ajax dataType property.
It isn't executing the success function, because it might be failing at some point. Try adding an error function and log the data. The JQuery documentation is very helpful and rich.
Also, try to change to data: JSON.stringify({ u : 'http://stackoverflow.com/' }), at least in ASP.NET I have to do it every time.
Are you sure you are calling the function inside the file?
You need to invoke the function by calling it.
getHtml();
I am using jquery post ajax request to do something. the page submit.php return json value and sometime if fatal error occure it return nothing.
I cant determine the ajax return value or not. So how can this possible.
Here are the code i use:-
$.post( 'submitVoice.php', $('#frmVerify').serialize(), function( data ) {
//some code
}, 'json');
Thanks.
You can add .done and .fail handlers (or .then) in a chain after your $.post call:
$.post(...)
.done(function(data, testStatus, jqXHR) { /* use data here */ })
.fail(function(jqXHR, textStatus, errorThrown ) { /* error handling here */ });
Note that in neither case can you return a value to the caller. If you need to do this, return the result of $.post instead.
Instead use ajax call which has success and error callback as shown:
$.ajax({
url : 'submitVoice.php' ,
data: $('#frmVerify').serialize() ,
type: 'POST',
dataType :'JSON',
error: function() {
alert("error");
},
success: function(data) {
alert(data);
}
});
$.post is a shorthand way of using $.ajax for POST requests, so no difference.
$.ajax is generally better to use if you need some advanced configuration.
see reference here.
You can use error callback to know exact error.
$.post('wrong.html', {}, function(data) { })
.fail(function(xhr) { alert('Internal Server Error'); console.log(xhr)});
FIDDLE
I'm using this script :
var test = $.ajax({ url : ("/areas/list"), type : 'GET', dataType : 'json', success : function(e) {
} });
I get this result in var text :
Object {readyState: 1, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function…}
abort: function ( statusText ) {
always: function () {
complete: function () {
done: function () {
error: function () {
fail: function () {
getAllResponseHeaders: function () {
getResponseHeader: function ( key ) {
overrideMimeType: function ( type ) {
pipe: function ( /* fnDone, fnFail, fnProgress */ ) {
progress: function () {
promise: function ( obj ) {
readyState: 4
responseJSON: Object
responseText: "{↵ "kind": "fusiontables#sqlresponse",↵ "columns": [↵ "INSEE_COM",↵ "KML",↵ "NOM_COMM"↵ ]}"
setRequestHeader: function ( name, value ) {
state: function () {
status: 200
statusCode: function ( map ) {
statusText: "OK"
success: function () {
then: function ( /* fnDone, fnFail, fnProgress */ ) {
__proto__: Object
The problem, is in this object, i would like get only the object in response JSON. I tried with test.responseJSON, but it doesnt work...
How can i get only the JSON ?
Thanks for your help !
F.
You're not doing anything with the returned data in the success callback.
This should work:
var test;
$.ajax({
url: "/areas/list",
type: 'GET',
dataType: 'json',
success: function(response) {
// Do what ever with the response here
console.log(response);
// or save it for later.
test = response;
}
});
If you decide to save the response in a variable you won't be able to access it straight away. The ajax request wont't be complete. Best to do your processing of the JSON object in the success callback.
The test variables value will be the value returned by the $.ajax() function call, not the result. $.ajax will not immediately return the value from the call, its asynchronous, that's why a callback (success: function(e) {}) is used. The success callback will be called when the ajax call have successfully fetched whatever it is asked to fetch.
Check what e is in the success callback!
$.ajax({url: ("/areas/list"), type: 'GET', dataType: 'json', success: function(e) {
console.log(e); // e == result from the ajax call.
}});
1. Are you returning JSON data?
In your AJAX, you're sending a request to a link at /areas/list - how are you handling that request in the Rails controller?
For it to return JSON data, it should read something like this:
#app/controllers/areas_controller.rb
def list
respond_to do |format|
format.json { return :json => "hello".to_json }
end
end
Posting your controller's code will be a big help for us all
2. Are you handling the JSON data correctly?
JSON data is different than "normal" javascript data. It has to be parsed when it is returned from the server, using the JSON parse functions:
$.ajax({
url : ("/areas/list"),
type : 'GET',
dataType : 'json',
success : function(data) {
var json_data = JSON.parse(data);
//do what you need here with the new array
}
});
you are trying to fetch value synchronously, which is not a good practice. You should try the following way:
var test;
$.ajax({
url:"/areas/list",
type:"GET",
dataType:"JSONP",
success:function(testdata){
console.log(testdata);
test=testdata;
}
});