I need to detect client side if a requested file (with XMLHttpRequest) had a 301 response. The reason of doing this is because I need to request other files related to the file where user has been redirected and not related to the first one requested.
Any way to detect this response status code using JavaScript or JQuery?
Thanks.
jQuery ajax callback function gives out a lot of info
$.ajax({
url: "test.php",
type: "GET",
data: {},
dataType:"json",
success: function(resp, textStatus, xhr) {
//status of request
console.log(xhr.status);
},
complete: function(xhr, textStatus) {
console.log(xhr.status);
}
});
You can use $.ajax with jquery
It has everything you need here : http://api.jquery.com/jQuery.ajax/
If you look at "statusCode" explaination, you will see you can make something for every code
Related
I'm going to go crazy.
When I i jQuery Ajax function to a request, I get in console this error
OPTIONS [myURL] net::ERR_NAME_NOT_RESOLVED
It is possible to get the error text net::ERR_NAME_NOT_RESOLVED in my JavaScript?
I read all documentation about jQuery Ajax but I can't understand where I can find this message.
Thanks a lot.
This is the simplified Ajax call. The URL is simply a variable of a WebService.
$.ajax({
method: "GET",
url: myURL,
dataType: "json",
})
.done(function(response) {
console.log(response)
})
.fail(function(jqXHR, textStatus, errorThrown) {
console.error("------AJAX error");
});
I'm having a trouble with ajax requests and server responses:
$.ajax({
url: servurl,
dataType: "jsonp",
data: {... },
crossDomain: true,
error: function(){},
success: function(){},
complete: function(){alert('complete')}
});
}
The thing is - sometimes I get succes, when I should get it, but sometimes I can get 500 status, and it is normal and expected.
The same ajax call works for correct requests, but fails for others.
I want to display an error message if I get a 500 server error, but for some reason the ajax does not complete. Thus, neither error: nor complete: work.
Maybe the reason for that is 'jsonp' datatype? Other datatypes do not work though.
Can someone help please?
Or maybe give me an advice on how to detect server status any other way.
jsonp requests do not trigger error callbacks by design, therefore there is no way for you to catch the error with javascript. I suggest instead implementing an error handler on your server that detects a jsonp request and returns jsonp that indicates an error has occured rather than a 500 status code.
Note that error: is deprecated as of 1.8 and is not called for JSONP however I wonder if you might have success using the Promise functionality introduced with 1.5 for deferred http://api.jquery.com/category/deferred-object/ as:
jqXHR.fail(function(jqXHR, textStatus, errorThrown) {});
jqXHR.done(function(data, textStatus, jqXHR) {});
jqXHR.always(function(data|jqXHR, textStatus, jqXHR|errorThrown) { });
Example for your code:
$.ajax({
url: servurl,
dataType: "jsonp",
data: {... },
crossDomain: true
}).done(function(data, textStatus, jqXHR){ //replace success
alert(textStatus);
}).always(function(data|jqXHR, textStatus, jqXHR|errorThrown) { // replace complete
alert(textStatus);
}).fail(function(jqXHR, textStatus, errorThrown) { // replace error
alert(errorThrown);
});
Make sure that you are accessing to your server. Maybe you are requesting in your server for an specific contentType (like application/json) and you are not using that property into your ajax call.
As you requested, to show any message if get a error (400, 404, 500...), you can use my custom function for ajax error responses:
function onErrorFunc(jqXHR, status, errorText) {
alert('Status code: ' + jqXHR.status + '\nStatus text: ' + status +
'\nError thrown: ' + errorText);
}
Usage:
$.ajax({
//some options
error: onErrorFunc
});
Please, show us what error thrown your server.
Thank you all for comments. Jquery .ajax really does not give errors on jsonp requests.
The way to get error messages was to implement the jquery-jsonp plugin:
https://github.com/jaubourg/jquery-jsonp
I try to make a JQuery ajax request to 'http://pastebin.com/raw.php' and using this code:
$.ajax({
url: 'http://pastebin.com/raw.php',
data: "i=VJ29uFnk",
complete: function(jqXHR, textStatus) {
alert('complete');
},
success: function(data) {
alert(data);
},
error: function(xhr, status, error) {
alert('noh!')
}
});
With this I get a status '404' within xhr but the url I can see in firebug looks correct:
http://pastebin.com/raw.php?i=VJ29uFnk
Ideas?
XHR calls are protected under the Same origin policy.
What you can do, however, is call a server side script that bypass this.
You could circumvent the same origin policy by creating a php script that captured the data you want: example.com/getpage.php?url=pastebin.com/raw.php?i=VJ29uFnK.
I'm writing a simple app in HTML and Javascript. I'm trying to retrieve my user_timeline via jQuery's .ajax() method. The problem is that I want to retrieve my timeline in XML but I'm keep failing with this simple task. Here's my code:
$.ajax({
type: 'GET',
dataType: 'xml',
url: 'http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=stepanheller',
success: function(data, textStatus, XMLHttpRequest) {
console.log(data);
},
error: function(req, textStatus, error) {
console.log('error: '+textStatus);
}
});
Weird thing is that when I try exactly the same thing but with JSON instead of XML then the script works.
$.ajax({
type: 'GET',
dataType: 'jsonp',
url: 'http://api.twitter.com/1/statuses/user_timeline.json?screen_name=stepanheller',
success: function(data, textStatus, XMLHttpRequest) {
console.log(data);
},
error: function(req, textStatus, error) {
console.log('error: '+textStatus);
}
});
Can you give me some hints what I'm doing wrong with the request? I know that I'm using old version of API but I won't deal with OAuth right now. Thanks.
It is generally impossible to send a Cross-domain ajax request. It's the general rule.
JsonP is the classic way to work around this limitation, and there is no equivalent for Xml according to my knowledge. Depending on your browser compatibility constraints, you can use XHR2 to achieve this.
Otherwise, the only solution is to set up a server proxy.
Client --Ajax--> Your server --HttpRequest--> Twitter
Following is my code :
function jsonpCallback(response){
//JSON.stringify(response)
alert(response);
}
$.ajax({
url: url,
dataType: 'jsonp',
error: function(xhr, status, error) {
alert(error);
},
success: function(data) {
alert(data);
jsonpCallback(data);
}
});
Here my url variable is the link which contain the following data and as per I know it is in the JSON format:
[{"destination":"United States","destinationId":"46EA10FA8E00","city":"LosAngeles","state":"California","country":"United States"}] etc..
I want to call jsonpCallback function after passing successive data to it. But success argument of $.ajax is not calling the function thats why I am not getting any data into it. But my debugger window showing response there, so why its not coming $.ajax function?
Any help...thanks in advance.
Try to pass type of ajax call GET/POST.
$.ajax({
type: "GET",
url: url,
dataType: 'jsonp',
error: function(xhr, status, error) { alert(error); },
success: function(data) {
alert(data);
jsonpCallback(data);
}
});
function jsonpCallback(response){
//JSON.stringify(response)
alert(response);
}
The URL you are trying to load data from doesn't support JSONP, which is why the callback isn't being called.
If you own the endpoint, make sure you handle the callback GET parameter. In PHP, your output would look like this:
<?php
echo $_GET['callback'].'('.json_encode($x).')';
This will transform the result to look like this:
jsonp2891037589102([{"destination":"United States","destinationId":"46EA10FA8E00","city":"LosAngeles","state":"California","country":"United States"}])
Of course the callback name will change depending on what jQuery generates automatically.
This is required as JSONP works by creating a new <script> tag in the <head> to force the browser to load the data. If the callback GET parameter isn't handled (and the URL returns a JSON response instead of a JSONP response), the data gets loaded yes, but isn't assigned to anything nor transferred (via a callback) to anything. Essentially, the data gets lost.
Without modifying the endpoint, you will not be able to load the data from that URL.
One weird thing I've noticed about $.ajax is that if the content-type doesn't match exactly it's not considered a success. Try playing around with that. If you change success to complete (and fix the arguments) does it alert?
It's not working because your server does not render a JSONP response. It renders a JSON response.
For JSONP to work, the server must call a javascript function sent by the ajax request. The function is generated by jQuery so you don't have to worry about it.
The server has to worry about it, though. By default, this function's name is passed in the callback argument. For example, the URL to the server will be http://some.domain/ajax.php?callback=functionName (notice callback=functionName).
So you need to implement something like the following on the server side (here in PHP):
$callback = $_GET['callback'];
// Process the datas, bla bla bla
// And display the function that will be called
echo $callback, '(', $datas, ');';
The page returned will be executed in javascript, so the function will be called, so jQuery will call the success function.
First check in which event you are calling $.ajax function...
<script type='text/javascript'>
jQuery('#EnrollmentRoleId').change(function(){
alert("ajax is fired");
$.ajax({
type: "GET",
url: url,
dataType: 'jsonp',
error: function(xhr, status, error) { alert(error); },
success: function(data) {
alert(data);
jsonpCallback(data);
}
});
});
function jsonpCallback(response){
//JSON.stringify(response)
alert(response);
}
</script>
second try to replace $ with jQuery.
Try to give no conflict if you thinking any conflict error..
jQuery ajax error callback not firing
function doJsonp()
{
alert("come to ajax");
$.ajax({
url: url,
dataType: "jsonp",
crossDomain: true,
jsonpCallback:'blah',
success: function() { console.log("success"); },
error: function() { console.log("error"); }
});
}
Then check your json data if it is coming it is valid or not..
Thanks