I'm grabbing user information from the Last.fm website with a JQuery $.get request.
Since some users' accounts are private, I sometimes receive a 403 error stating that authentication is required. This breaks the JS code. The last.fm API doesn't let you see if a user is private or not.
Is there a way to catch this error and continue through the code?
Thanks!
Not sure if it works with cross-domain requests, but you could do something like this:
$.ajax({
type: 'GET',
statusCode: {
403: function() {
alert('a 403 was received');
}
},
success: function() {
alert('everything OK');
}
});
Or possibly set it up in $.ajaxSetup() if it works ?
You would be better using a proxy to get the data from API since $.ajax() error handler won;t return errors for cross domain requests per jQery API docs:
http://api.jquery.com/jQuery.ajax/
EDIT Note in docs for error option:
"Note: This handler is not called for cross-domain script and JSONP requests."
Related
im want to call haveibeenpwned v3 API,
here is my code
<script>
$.ajax({
url:"https://haveibeenpwned.com/api/v3/breachedaccount/brian.c#softnet.co.id",
headers: { 'Content-type': 'x-www-form-urlencoded', 'hibp-api-key': 'my-key'},
async: false,
datatype:'application/json',
success:function(data){
alert("a");
},
error:function(data){
console.log(JSON.stringify(data));
}
});
</script>
but i always get this this error at the console
{"readyState":0,"status":0,"statusText":"NetworkError: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'https://haveibeenpwned.com/api/v3/breachedaccount/brian.c#softnet.co.id'."}
pls help me if you ever use haveibeenpwned.com
i already doing this way with another api, this is my first time with headers
i expect the json output
You likely have some other errors in your console too which are more relevant than the one you posted - including, I expect, a CORS-related error.
According to https://haveibeenpwned.com/API/v3#CORS you may have a problem because
"CORS is only supported for non-authenticated APIs".
...and according to https://haveibeenpwned.com/API/v3#Authorisation
Authorisation is required for all APIs that enable searching HIBP by email address...The key is then passed in a "hibp-api-key" header
Therefore the endpoint you are trying to search is one requiring authentication/authorisation and as such you are not allowed to make a CORS (cross-origin ) AJAX request to it.
In conclusion you will need to connect to this API via your server-side code instead.
Update - 2016-01-30
As advised in the comments I have:
installed XAMPP
put my page on Apache and ran the server
made sure the page and the scripts are executing (simple alert test)
set the xhrFields: withCredentials to false to make CORS request as advised in the only answer and taught here
I still cannot pass the request. This is the console log:
XMLHttpRequest cannot load http://localhost:8080/RimmaNew/rest/appointments.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost' is therefore not allowed access. The response had HTTP status code 400
Here how it looks on the 'user end' if this is of any help:
------------------Initial ticket-----------------------------
I have a java rest application that runs locally and accepts so far one get method and returns a json string:
Another method is POST, which is supposed to convert, validate and save the information from the sent form and return a 200 answer. If anything goes wrong during conversion, validation or persistence - an exception is thrown (e.g. BadRequest or 500).
This is the rest method (I omitted for brevity validating, build methods as well as the converter and converter provider classes):
#POST
#Produces("application/json")
#Consumes("application/x-www-form-urlencoded")
public Response bookAppointment(#FormParam("date") Date appDate,
#FormParam("time") Time appTime, #FormParam("type") String appType,
#FormParam("clientName") String clientName, #FormParam("email") String clientEmail,
#DefaultValue("") #FormParam("message") String clientMsg) {
//externalize the validation of all fields to concentrate on "positive"
//scenario only
validator(appDate, appTime, appType, clientName, clientEmail);
Appointment appointment = build(appDate, appTime, appType,clientName,
clientEmail, clientMsg);
try {
repository.add(appointment);
return Response.ok(appointment).build();
} catch (Exception e) {
throw new InternalServerErrorException("Something happened in the application "
+ "and this apointment could not get saved. Please contact us "
+ "to inform us of this issue.");
}
}
The client is not within the application (I thought may be this will be useful) - it is a simple HTML file on my computer that has this jQuery script:
<script type='text/javascript'>
$(document).ready(function(){
$('form#appointmentForm').submit(function(ev){
ev.preventDefault();
$.ajax({
url: 'localhost:8080/RimmaNew/rest/appointments',
type: 'post',
dataType: 'json',
data: $('form#appointmentForm').serialize(),
contentType: 'application/x-www-form-urlencoded',
beforeSend: function() {
$('#ajaxResponse').html("<img src='245.gif' />");
},
success: function(data) {
$('#ajaxResponse').html("<span style='color:white; background-color: green;' class='glyphicon glyphicon-ok'></span><p>"+JSON.stringify(data)+"</p>")
.fadeIn("slow");
},
error: function(xhr, ajaxOptions, thrownError){
$('#ajaxResponse').html("<span style='color:white; background-color: red;' class='glyphicon glyphicon-exclamation-sign'></span><p>Status: ").append(xhr.status)
.append("</p>").fadeIn("slow");
}
});
});
});
</script>
I want to submit a form in order to access its params with the #FormParam annotated attributes. On every request that I send I do not receive any of the thrown errors and the status is always 0. Do you see where am I erring or what am I missing?
A status code of 0 means that the request didn't happen. In order to have a status code a valid http interaction has to happen, if none did there is no status code.
The main reasons why this would happen are:
The DNS could not be resolved
A connection to the host/port could not be established
CORS Issues, the HTML is not being served by the same host/port than the server. In this case you need to write a CORS policy to allow specific domains to
make ajax request to the server.
The HTML is a local file, this is a special case of the CORS problem where some browser don't allow connections without a host.
All of them should show an error on the javascript console ( the weirdest would be CORS that shows itself as a failed OPTIONS request )
I am working on an app that will submit data to a REST API and have some questions.
How does jQuery know if my post request was successful or not? Is it only looking at the HTTP status?
Is there a convention on what to return from a POST request to a REST API?
JavaScript
$.post( '/API/removeUser', { Eid: id }, function(data) { row.remove(); } );
PHP SLIM Framework
$app->POST('/API/removeUser', function () use ($app) {
// Get the ID from the jQuery post
$Eid = trim(stripslashes(htmlspecialchars($_POST['Eid'])));
echo json_encode(removeFunction($Eid));
});
Your backend should always return the appropriate HTTP status code along with the actual data. 404 for resources that were not found, 403 for unauthorized requests, 200 for successful requests etc. Most AJAX libraries (including jQuery) will rely on those for determining the result of the operation.
If you need more fine-grained error reporting, you could always include a field like "errorCode" in your response that contains an application-level error code that you define yourself and react to accordingly in your frontend code.
I am working on an e-commerce site and I need google sign-on it, so when a user creates his/her shopping list and click on the add to list button. I am able to send my data through the $.ajax() method, so what I exactly want is when the response from ajax method come it should redirect me to Login page if the user is not logged in, else it should save my object.
In the target endpoint of that .ajax() call, check your authentication, and if the user is not logged in, set the response header to - 401 Unauthorized.
Then in the .ajax() do this:
$.ajax(function() {
//.. your other ajax stuff..//
error: function(jqXHR, textStatus, errorThrown) {
// only redirect if user unauthorized - 'errorThrown' has text part of HTTP status header
if(errorThrown == "Unauthorized") {
window.location.href = "myloginpage.html";
}
}
});
The response header being set to 401 will trigger .ajax()'s error function, instead of the success function.
Edit:
Changed the error function to only redirect on Unauthorized
Also note, that if this is a cross-domain jsonp call, it won't work, as jsonp requests fail silently and don't trigger the error function
check in your response callback function and write your programming logic that you want
$.ajax({
'url':location,
'type':type,
'success':function(response){
/*write here your logic*/
},
'error':function(){
/*you code for error handling*/
}
});
to redirect window by javascript use
window.location.href = 'your location';
You can redirect to login page using window.location = 'yourlocation' in either success or error function of the response (depending upon what response you are gettig from server. If you are bringing the response code in header 401 error function will be executed other wise success).
but i think what you would like to have is take user back to the same page after login from which he started.
If you are interrested in this, you can use spring security for this. Its very easy to integrate if you are using spring already.
If you are not using spring you might look for some alternative for the same. Following links may help you
Spring Security Ajax login
http://java.dzone.com/articles/implementing-ajax
In jquery there is .post() method found to do this. In action page you can do whatever you want.
So I have a bit of a problem. When I ask MooTools to send a request it comes back as failed every time. I can't seem to diagnose the problem either because if I try to get the returned header info the console just gives me "Refused to get unsafe header 'Status'" Message. The only thing I can think of is that the server isn't letting me access outside resources but maybe I just coded it wrong.
Here's the request code:
var finfo = current.textFontData();
var url = 'http://antiradiant.com/clients/TMW/rbwizard/mailer.php?s='+current.size+'&b='+current.box+'&l='+current.lidWood+'&c='+current.cartID+'&f='+finfo.font+'&l1='+finfo.line1+'&l2='+finfo.line2;
console.log(url);
var req = new Request({
url: url,
onSuccess: function() {
console.log('success');
//atc2.send();
},
onFailure: function() {
console.log('failure');
console.log(this.getHeader('Status'));
//atc2.send();
},
onException: function(headerName, value) {
console.log('exception');
console.log(headerName+': '+value);
}
});
req.send();
This code is derived from the resource rb_wizard.js (lines 81-103) on http://tylermorriswoodworking.myshopify.com/pages/recipe-box-wizard?b=maple&l=cherry&s=3x5&c=42042892
Mootools has a class called Request.JSONP that will help with your cross domain problem. Its sub class of the Request class, so your methods should work the same. I believe you need to call .post() or .get() at the end instead of send, but thats about all that should chnge. I'm not sure what version you're running on but here is the link tot he docs Mootools Request.JSONP
The error message "Refused to get unsafe header 'Status'" is spat out by WebKit based browsers (Safari, Chrome, etc) when you violate the cross-domain security model.
Therefore, it seems likely that the code you pasted is located on a domain other than antiradiant.com, and therefore is not allowed (by the browser) to request sites on antiradiant.com.
What I ended up doing was just using an iframe. All I really had to do was send data to another site and not receive any so it worked out.