401 Unauthorized Issue - javascript

I am using the jQuery.get() method
$.get('login.php', function(d, textStatus, jqXHR){
//alert(jqXHR.status)
var status = jqXHR.status;
if((status==200)||(status==202)){
window.location.href = 'dashboard.html';
}else if(status==401){
alert('Error in login details')
}else{
alert('Unknown Error')
}
});
It is working fine. When 200 & 202 , It will rediredt to dashboard page. But Other than 200 & 202, It pass the error in console but doesn't show alert.

You need to add in some event handlers for the fail state, which will handle 4xx and 5xx errors. The success state only handles HTTP codes which indicate a successful request. From http://api.jquery.com/jQuery.get
var jqxhr = $.get( "example.php", function(data, status) {
alert( "success - " + status );
})
.done(function(data, status) {
alert( "second success - " + status );
})
.fail(function(data, status) {
alert( "error - " + status );
})
.always(function(data, status) {
alert( "finished - " + status );
});

This is because the callback function you have defined is only called when a successful request completes. If the response is anything other than a 200, the request is considered to have errored. To do what you require, you could use the $.ajax() method:
$.ajax({
url: 'login.php',
success: function() {
window.location.assign('dashboard.html');
},
error: function(xhr) {
if (xhr.status == 401) {
alert('Error in login details')
} else {
alert('Unknown Error')
}
}
});

Related

Getting "undefined" in AJAX response while there is data available in "Response" tab of chrome dev tools

I'm trying to get response from the following cross domain ajax request, but get undefined in success:
$.ajax({
type: "GET",
url: "https://path_to_app/rest/jjwt",
crossDomain: true,
dataType: 'script',
contentType: 'text/plain;charset=UTF-8',
beforeSend: function(xhr) {
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
xhr.setRequestHeader("Authorization", "Basic " + btoa(username + ":" + password));
},
success: function (response, textStatus, xhr) {
console.log(response);
console.log(textStatus);
},
error: function (jqXHR, exception) {
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
console.log(msg);
}
});
See the response in dev tools below:
When trying to use the exact same url in browser, I can see the expected response (token) after authorization:

jQuery ajax requests repeats when error occurs

I've read through several posts related this this kind of issue, but I'm still not identifying the issue here.
When the following function is called and receives a 200 response, all is well; when it encounters 404 the ajax is repeated; adding a timeout only limits the time frame during which the repeat requests are made. There has to be a simple reason for this, but it is eluding me ...
function myFunction(ID) {
var url = 'http://example.org/' + ID;
var response;
$.ajax(url, {
success: function (responseText) {
if (responseText !== undefined) {
response = responseText;
}
},
error: function (xhr, ajaxOptions, errorMsg) {
if (xhr.status == 404) {
console.log('404: ' + errorMsg);
} else if (xhr.status == 401) {
console.log('401: ' + errorMsg);
}
}
});
return response;
}
You can use the below given approach to get the data for your error without repetition in AJAX.
$.ajax(url, {
success: function (responseText) {
if (responseText !== undefined) {
response = responseText;
}
},
error: function (xhr) {
//the status is in xhr.status;
//the message if any is in xhr.statusText;
}
});
UPDATE
You cannot return the response because you have an async request and response variable will be returned before the actual ajax requests gives a response. So I suggest You either use a callback function on success ore use a synchronous request.
So to get the response you can have a function like so:
function getResponse() {
return $.ajax({
type: "GET",
url: your_url,
async: false
}).responseText;
}
Or the callback approach is:
$.ajax(url, {
success: function (responseText) {
if (responseText !== undefined) {
theCallbackFunction(responseText);
}
},
error: function (xhr) {
//the status is in xhr.status;
//the message if any is in xhr.statusText;
}
});
function theCallbackFunction(data)
{
//do processing with the ajax response
}

jquery Github api

I'm working on a webpage that I need to display the list of repos by using the github api. But keep get 401 error. Not sure where I was wrong.....
Here is what I have so far:
function requestJSON(url, callback) {
$.ajax({
url: url,
dataType: "json",
complete: function(xhr) {
callback.call(null, xhr.responseJSON);
console.log(xhr.responseJSON);
//alert('Load was performed.');
if (xhr.status === 200) {
alert('User\'s name is ' + xhr.responseText);
}
else {
alert('Request failed. Returned status of ' + xhr.status);
}
},
error: function( req, status, err ) { console.log( 'something went wrong', status, err );
},
beforeSend: function(xhr, settings) { xhr.setRequestHeader('Authorization',authCredentials);
xhr.setRequestHeader('Content-Type', 'text/plain');}
});
}
});
beforeSend: function(xhr, settings) { xhr.setRequestHeader('Authorization',authCredentials);
xhr.setRequestHeader('Content-Type', 'text/plain');}
It was my authCredentials issue, miss type.....

Show an error when email is not sent

I have the following example form below where beforeSend function shows a message that is sending and once it is sent an other function is called .done(function (data) showing a message that message has been sent. All I want to do is to use another function where the message is not sent, to display the message "error, message is not sent"
var form = $('#main-contact-form');
form.submit(function (event) {
$.ajax({
type: 'POST',
url: '../sendemail.php',
data: {
Name: name,
Subject: $form.find("input[name='subject']").val(),
Email: email,
message: $form.find("textarea[name=message]").val(),
},
beforeSend: function () {
// message is sending...
}
}) //end ajax
.done(function (data) {
// message sent!
});
});//end contact form
You can use fail api to handle errors as shown below.
Also, in the $.ajax({constObj}) you can have apis like success and error to handle the same.
Refer here for more info
//1.
$.ajax({
type: 'POST',
url: '../sendemail.php',
data: {
Name: name,
Subject: $form.find("input[name='subject']").val(),
Email: email,
message: $form.find("textarea[name=message]").val(),
},
beforeSend: function () {
// message is sending...
}
}) //end ajax
.done(function (data) {
// message sent!
})
.fail(function(){
//handle error here
});
//2.
constObj.success(function(data){
});
constObj.error(function(error){
});
Instead of .done use ajax options success and error. Throw error on server when sending email fails.
$.ajax({
success: function () {
// message sent!
},
error: function () {
// message sent failed!
}
});
On server side:
if ($this->sendMessage()) {
echo "ok";
} else {
throw new Exception('Email failed to send.', 500);
}
You can't tell if user actually receives email (I guess there is some complicated ways to figure it out).
You use done(), which is executed after a SUCCESSFUL ajax request (usually returns HTTP 200). If you read http://api.jquery.com/jquery.ajax/, there is fail(), which is executed after a FAILED ajax request.
It also depends the output of sendemail.php. If your PHP returns other than HTTP 200 when error, you can utilize fail() promise method, for example...
$.ajax({
beforeSend: function() {
$('msg').text('Sending email...');
}
}).done(function() {
$('#msg').text('Success!');
}).fail(function() {
$('#msg').text('Failed!');
});
But, if your PHP also returns HTTP 200 when error, you can do something like the following...
PHP:
$response = array(
'status' => null,
'error' => null
);
if ($mailer->send()) {
$response['status'] = true;
} else {
$response['status'] = false;
$response['error'] = 'Unable to send email';
}
jQuery:
$.ajax({
beforeSend: function() {
$('msg').text('Sending email...');
}
}).done(function(data) {
if (data.status === true) {
$('#msg').text('Success!');
} else {
$('#msg').text('Failed: ' + data.error);
}
});

How to handle a 401 unauthorized response with Backbone?

I configure my Backbone router with different views. But on some views, I need to fetch a collection. If the user is not logged in, server returns a 401 http status.
So, I configure jQuery's global ajax settings like that:
$.ajaxSetup({
xhrFields: {
withCredentials: true
},
crossDomain: true,
error: function(jqXHR, textStatus, errorThrown) {
console.log("error ajax");
if (jqXHR.status == 401) {
console.log('error 401');
app.router.navigate('', { trigger: true });
}
}
});
But it never goes in the error callback, even if the response code is 401.
Instead of modifying the ajax options globally, I modified Backbone.sync function to handle authentication.
Backbone.sync = (function(syncFn) {
return function(method, model, options) {
options = options || {};
var beforeSend = options.beforeSend,
error = options.error;
// Add headers
options.beforeSend = function(xhr) {
xhr.setRequestHeader('withCredentials', true);
if (beforeSend) return beforeSend.apply(this, arguments);
};
// handle unauthorized error (401)
options.error = function(xhr, textStatus, errorThrown) {
console.log("error sync");
if (error) error.call(options.context, xhr, textStatus, errorThrown);
if (xhr.status === 401) {
console.log('error 401');
app.router.navigate('', { trigger: true });
}
};
return syncFn.apply(this, arguments);
};
})(Backbone.sync);

Categories

Resources