How can I handle errors in AJAX in jquery - javascript

How can I handle errors in AJAX?
In my code, the else condition containing console.log is not executed even when the departments.json file is not loaded. I checked it by deleting the departments.json file from where it is loaded into the code.
My code is:
$.getJSON("departments.json?" + new Date().getTime(), {}, function(departments, status, xhr) {
if (xhr.status == 200) {
var numericDepts = [];
var nonNumericDepts = [];
for(dept in departments) {
$("#kss-spinner").css({'display':'none'});
if (isNaN(departments[dept].depNo)) {
if (isNaN(parseInt(departments[dept].depNo,10)))
nonNumericDepts[nonNumericDepts.length] = departments[dept];
else
numericDepts[numericDepts.length] = departments[dept];
}
else
numericDepts[numericDepts.length] = departments[dept];
}
numericDepts.sort(cmp_dept);
nonNumericDepts.sort(function(dept1,dept2) {
return dept1.depNo.toLowerCase() - dept2.depNo.toLowerCase();
});
departments.sort(cmp_dept);
var k = 0;
$.each(numericDepts.concat(nonNumericDepts), function() {
if (k % 2 == 0) {
$('<p class="odd" onClick="selectTag(this,\'' + this.id + '\', 1)">' + this.depNo + '</p>').appendTo($(".scroller", $("#br1")));
}
else {
$('<p class="even" onClick="selectTag(this,\'' + this.id + '\', 1)">' + this.depNo + '</p>').appendTo($(".scroller", $("#br1")));
}
k++;
});
$("#kss-spinner").css({'display':'none'});
}
else {
console.log(xhr.status);
console.log(xhr.response);
console.log(xhr.responseText)
console.log(xhr.statusText);
console.log('json not loaded');
}
});

You could just use the generic ajax() function:
$.ajax({
url: url,
dataType: 'json',
data: data,
success: successCallback,
error: errorCallback
});

You will need to use the fail() method in order to accomplish that.
Example:
$.get("test.php")
.done(function(){ alert("$.get succeeded"); })
.fail(function(){ alert("$.get failed!"); });

if you need a generic error handler use
$.ajaxSetup({
error: function(xhr, status, error) {
// your handling code goes here
}
});

JQuery's getJSON function is an abstraction over the regular .ajax() method - but it excludes the error callback.
Basically, the function you define is only called if the call is successful (that's why it never gets to the else part).
To handle errors, set an error handler before like this:
$.ajaxError(function(event, jqXHR, ajaxSettings, thrownError) { alert("error");});
Whenever an AJAX request completes with an error, the function will be called.
You can also append the .error at the end of your getJSON call:
$.getJSON("example.json", function() {
(...)
}).error(function() { (...) });

The $.getJSON() function is just a special purpose version of the more general .ajax() function.
.ajax() function will give you the extra functionality you desire (such as an error function). You can read more documentation here http://api.jquery.com/jQuery.ajax/
$.ajax({
url: "departments.json?" + new Date().getTime(),
dataType: 'json',
success: function(departments){
var numericDepts = [];
var nonNumericDepts = [];
for(dept in departments)
{
$("#kss-spinner").css({'display':'none'});
if(isNaN(departments[dept].depNo))
{
if(isNaN(parseInt(departments[dept].depNo,10)))
nonNumericDepts[nonNumericDepts.length]=departments[dept];
else
numericDepts[numericDepts.length]=departments[dept];
}
else
numericDepts[numericDepts.length]=departments[dept];
}
numericDepts.sort(cmp_dept);
nonNumericDepts.sort(function(dept1,dept2) {
return dept1.depNo.toLowerCase() - dept2.depNo.toLowerCase();
});
departments.sort(cmp_dept);
var k=0;
$.each(numericDepts.concat(nonNumericDepts),function(){
if(k%2==0){
$('<p class="odd" onClick="selectTag(this,\''+this.id+'\',1)">'+this.depNo+'</p>').appendTo($(".scroller",$("#br1")));
} else {
$('<p class="even" onClick="selectTag(this,\''+this.id+'\',1)">'+this.depNo+'</p>').appendTo($(".scroller",$("#br1")));
}
k++;
});
$("#kss-spinner").css({'display':'none'});
},
error: function(xhr, textStatus, errorThrown) {
console.log(xhr.status);
console.log(xhr.response);
console.log(xhr.responseText)
console.log(xhr.statusText);
console.log('json not loaded');
}
});​

Related

Error part in jQuery is missing

I build following JavaScript part and everything works fine. But I'm not sure if the code is completely right. Because in my script I only use success: function() but I don't use error. Is it a MUST to have error in a jQuery AJAX call?
Currently I'm catching the errors in my php controller function and echo them in the success part.
$(document)
.ready(function() {
var groupName = '';
var groupid = '';
$(".grp")
.click(function() {
$('.text-danger')
.html('');
groupName = $(this)
.data('groupname');
groupid = $(this)
.attr('id');
$('.text')
.html(groupName);
$('#dataModal')
.modal({
show: true
});
});
jQuery(".grpval")
.click(function(e) {
e.preventDefault();
jQuery.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]')
.attr('content')
}
, });
jQuery.ajax({
url: "{{ route('request_group') }}"
, method: 'post'
, data: {
'Gruppe': groupid
}
, success: function(data) {
if (typeof data.successsuccess != 'undefined') {
jQuery('.alert-success')
.show();
jQuery('.alert-success')
.html('<p>' + data.successsuccess + '</p>');
$('#dataModal')
.modal('toggle');
window.scrollTo(500, 0);
} else if (typeof data.successdberror != 'undefined') {
jQuery('.alert-danger')
.show();
jQuery('.alert-danger')
.html('<p>' + data.successdberror + '</p>');
$('#dataModal')
.modal('toggle');
window.scrollTo(500, 0);
} else {
jQuery.each(data.errors, function(key, value) {
jQuery('.alert-danger')
.show();
jQuery('.alert-danger')
.html('<p>' + value + '</p>');
$('#dataModal')
.modal('toggle');
window.scrollTo(500, 0);
});
}
}
});
});
});
EDIT: Here is the function from my Controller:
public function setGroupRequest(Request $request){
$validator = \Validator::make($request->all(), [
'Gruppe' => [new ValidRequest]
]);
$groupid = $request->input('Gruppe');
if ($validator->fails())
{
return response()->json(['errors'=>$validator->errors()->all()]);
}
try{
$groups_request = new GroupRequest();
$groups_request->idgroups = $groupid;
$groups_request->iduser = Auth::id();
$groups_request->request_active = 1;
$groups_request->save();
$db_status = 'success';
}catch(\Exception $e){
$db_status = 'error';
}
if($db_status == 'success'){
return response()->json(['successsuccess'=>'Record is successfully added']);
}else{
return response()->json(['successdberror'=>'DB Error! Values could not be saved.']);
}
}
Error handling is required as you never know different things on the internet might result in failure of request for example,
Network failure.
Lost database connection
Unauthorised access/access denied
Any variable being not defined
There is nothing wrong in your way of writing PHP error in success, but writing it in $ajax error callback function is preferred as it helps in separating error & success logic.
In fact you can add a jquery error callback function as well to your $ajax which will handle all the errors originating from above mentioned internet failures.
You can add error function, which will receive any type of error coming from backend.
jQuery.ajax({
url: "{{ route('request_group') }}",
method: 'data: {
'Gruppe': groupid
},
success: function(data) {
//code here
},
error: function (jqXHR, exception) {
//error handling
}
})
In your PHP file,
if ($query) {
echo "success"; //whatever you want to show on success.
} else {
die(header("HTTP/1.0 404 Not Found")); //Throw an error on failure
}
This way you can catch PHP error as well as any internet Network errors in your jquery ajax.

How to define a variable after process in ajax?

I use an ajax process to modify user's state on an index.php file.
It works but I would like to color my div function of the user's state
My code:
function recupstatut() {
$.post('recup.php', function(data) {
$('.cont2').html(data);
var content = document.querySelector('#cont2');
var status2 = content.innerHTML;
if (status2 == "En-ligne") {
content.style.backgroundColor = "#4CAF50";
} else {
content.style.backgroundColor = "#f44336";
}
});
}
setInterval(recupstatut, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="cont2" id="cont2">
</div>
The condition always applies the else state:
content.style.backgroundColor = "#f44336";
I think the problem comes from var status2 =
How can I fix this?
HTML
<div class="cont2" id="cont2"></div>
SCRIPT
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script>
function recupstatut() {
$.post('recup.php', function(data) {
console.log(data);
var status2 = data.trim();
console.log(status2);
$('.cont2').html(status2);
if (status2 == "En-ligne") {
content.style.backgroundColor = "#4CAF50";
} else {
content.style.backgroundColor = "#f44336";
}
});
}
setInterval(recupstatut, 1000);
</script>
what went wrong is that you imported jquery file after calling the function
so make the import in top of calling your function
your mistake was that you made the import after calling the function, that is why you got undefined error.
As you say you echo string in your page then you can check this one directly from the data as per below code.
Script:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script>
$(function(){
function recupstatut() {
$.post('recup.php', function(data) {
$('#cont2').html(data); // If the data return from the php page as a string then you can compare it directly.
if (data == "En-ligne") {
$('#cont2').css("backgroundColor","#4CAF50");
} else {
$('#cont2').css("backgroundColor","#f44336");
}
});
}
setInterval(recupstatut, 1000);
});
</script>
HTML:
<div class="cont2" id="cont2"></div>
function recupstatut(){
$.post('recup.php',function(data){
console.log(data);
$('.cont2').html(data);
var status2 = data;
if (status2 == "En-ligne") {
$('#cont2').css("backgroundColor","#4CAF50");
} else {
$('#cont2').css("backgroundColor","#f44336");
}
});
}
setInterval(recupstatut,1000);
nothing appear in my div now with the console.log...
THere many ways to accomplish this. You can use the $.post() function by sending the $.post as a variable. Example:
// Fire off the request to /form.php
request = $.post({
url: "recup.php",
});
// Callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
// Log a message to the console
console.log("Hooray, it worked!");
});
// Callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
// Log the error to the console
console.error(
"The following error occurred: "+
textStatus, errorThrown
);
});
// Callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
// Reenable the inputs
$inputs.prop("disabled", false);
});
Or (i recommended) use the $.ajax({}) function as this way:
// Fire off the request to /form.php
$.ajax({
url: "recup.php",
type: "post",
data: { //specify data to be sent },
beforeSend:function(){
/* before sending the data to the other page
may be a loader to show waiting animation
*/
},
success:function(status){
/* this will check the response received from the previous page
and the determine the below conditions
*/
if (status == "En-ligne") {
content.style.backgroundColor = "#4CAF50";
} else {
content.style.backgroundColor = "#f44336";
}
}
});

jQuery AJAX post returns 403 error

I have the following script for AJAX to do login, but with some passwords that contain characters like "!##" it will return 403 error and will not submit to the PHP.
$(document).ready(function () { // When the document is ready
$('#login').click(function (e) { // We attach the event onchange to the select element
e.preventDefault();
var form_info = "";
$('#login_form *').filter(':input').each(function(){
if(this.value !== ""){
form_info += this.name;
form_info += "=";
form_info += encodeURIComponent(this.value);
form_info += "&";
}
});
form_info += "function_name=login";
var form = $('#login_form').serialize() + "&function_name=login";
$.ajax({
url: "function_ajax.php", // path to you php file
type: "post", // We want a POST request
dataType: 'html',
data: form_info,
statusCode:
{
404: function () {
alert('Could not contact server.');
},
500: function () {
alert('A server-side error has occurred.');
}
},
error: function ()
{
alert('A problem has occurred.');
},
beforeSend: function ()
{
alert(form_info);
alert(form);
},
complete: function ()
{
},
success: function (data) { // The function to execute if the request is a -success-,
if(data === "1"){
if (document.referrer !== "") {
window.location.href = document.referrer;
}
else{
window.location.href = "some_domain"
}
}
else if (data === "2")
{
alert("invalid");
}
else {
alert("empty");
}
}
});
});
});
You will find that I'm trying both ways to encode each element and the serialize just to check if I'm getting the same result, and I'm getting the same result, but still, it's getting this error.
If I try to encode the whole serialize, then I will not get the error but in PHP, the $_POST array will have the first key as the data I'm sending with no value.
encodeURIComponent($('#login_form').serialize()) + "function_name=login"
then the $_POST will be like
array(
[email=email#gmail.com&password=pass123!##&function_name=login]=>
)
which will not be useful for me.

jQuery AJAX function call

I have a problem with jQuery calling an AJAX function, basically everytime a user changes a select box, I want it to call the getSubCategories function, but for some reason, nothing is happening. Any ideas?
If I load the page and add console.log inside the getSubCategories function it logs it, should that even be happening?
function getSubCategories() {
var id = $("#category").prop('selectedIndex');
var selectedCategory = $("#category").val();
//should change this into a response from AJAX and grab the slug from there, this is fine for now.
var slugOfCategory = convertToSlug(selectedCategory);
id++;
console.log('here');
$.ajax({
method: 'GET', // Type of response and matches what we said in the route
url: '/product/get_subcategories', // This is the url we gave in the route
data: {
'id': id
}, // a JSON object to send back
success: function(response) { // What to do if we succeed
$("#sub_category option").remove(); //Remove all the subcategory options
$.each(response, function() {
$("#sub_category").append('<option value="' + this.body + '">' + this.body + '</option>'); //add the sub categories to the options
});
$("#category_slug").attr('value', slugOfCategory);
},
error: function(jqXHR, textStatus, errorThrown) { // What to do if we fail
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
}
function getCategories() {
var id = $("#type").prop('selectedIndex');
var selectedType = $("#type").val();
//should change this into a response from AJAX and grab the slug from there, this is fine for now.
var slugOfType = convertToSlug(selectedType);
console.log(slugOfType);
//add one to the ID because indexes dont start at 0 as the id on the model
id++;
$.ajax({
method: 'GET', // Type of response and matches what we said in the route
url: '/product/get_categories', // This is the url we gave in the route
data: {
'id': id
}, // a JSON object to send back
success: function(response) { // What to do if we succeed
$("#category option").remove(); //Remove all the subcategory options
$.each(response, function() {
$("#category").append('<option value="' + this.name + '">' + this.name + '</option>'); //add the sub categories to the options
});
$("#type_slug").attr('value', slugOfType);
},
error: function(jqXHR, textStatus, errorThrown) { // What to do if we fail
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
}
function convertToSlug(Text) {
return Text
.toLowerCase()
.replace(/ /g, '_')
.replace(/[^\w-]+/g, '');
}
$(document).ready(function() {
var firstCatgegory = $("#category").val();
var slugOfFirstCategory = convertToSlug(firstCatgegory);
$("#category_slug").attr('value', slugOfFirstCategory);
var firstType = $("#type").val();
var slugOfFirstType = convertToSlug(firstType);
$("#type_slug").attr('value', slugOfFirstType);
$("#type").change(getCategories());
$("#category").change(getSubCategories());
});
Thanks for any help. (Sorry the code is a little messy, i've just been trying to get it to work so far)
This is due to the fact that the ajax call you are trying to make is asynchronous. When you call getSubCategories() it returns undefined which is why your code is not working.
To make this work you need to put your code within the success callback function instead.
<script>
function getSubCategories()
{
var id= $("#category").prop('selectedIndex');
$.ajax({
method: 'GET',
url: '/product/get_subcategories',
data: {'id' : id},
success: function(response){
// DO SOMETHING HERE
},
error: function(jqXHR, textStatus, errorThrown) { }
});
}
$( document ).ready(function() {
// This is also wrong. Currently you're passing
// whatever is returned from getSubCategories
// (which is undefined) as the callback function
// that the "change" event will call. This instead
// should be the reference to the function. Which
// in this case is getSubCategories
$("#category").change(getSubCategories);
});
Please put getCategories() and getSubCategories() Methods inside Change function like this.Sorry for not code formatting.
<script>
$(document).ready(function(){
$("#category").change(function(){
getSubCategories();
});
$("#type").change(function(){
getCategories();
});
});
</script>

How could I trigger func when another has been completed?

I am using JQuery to collect latest tweets using Twitter API, but I am having some issues when calling two functions.
$(document).ready(function(){
JQTWEET.loadTweets();
});
This, is working ok, but then I want to call this function:
showHideTweets: function() {
alert("hola");
var ojeto = $(JQTWEET.appendTo).find(".item").first();
$(JQTWEET.appendTo).find(".item").first().css("display", "block");
},
Both functions are inside: jqtweet.js ...
loadTweets: function() {
var request;
// different JSON request {hash|user}
if (JQTWEET.search) {
request = {
q: JQTWEET.search,
count: JQTWEET.numTweets,
api: 'search_tweets'
}
} else {
request = {
q: JQTWEET.user,
count: JQTWEET.numTweets,
api: 'statuses_userTimeline'
}
}
$.ajax({
url: 'tweets.php',
type: 'POST',
dataType: 'json',
data: request,
success: function(data, textStatus, xhr) {
if (data.httpstatus == 200) {
if (JQTWEET.search) data = data.statuses;
var text, name, img;
try {
// append tweets into page
for (var i = 0; i < JQTWEET.numTweets; i++) {
img = '';
url = 'http://twitter.com/' + data[i].user.screen_name + '/status/' + data[i].id_str;
try {
if (data[i].entities['media']) {
img = '<img src="' + data[i].entities['media'][0].media_url + '" />';
}
} catch (e) {
//no media
}
var textoMostrar = JQTWEET.template.replace('{TEXT}', JQTWEET.ify.clean(data[i].text) ).replace('{USER}', data[i].user.screen_name).replace('{IMG}', img).replace('{URL}', url );
/*.replace('{AGO}', JQTWEET.timeAgo(data[i].created_at) ) */
//alert(JQTWEET.timeAgo(data[i].created_at));
$(JQTWEET.appendTo).append( JQTWEET.template.replace('{TEXT}', JQTWEET.ify.clean(data[i].text) )
.replace('{USER}', data[i].user.screen_name)
.replace('{NAME}', data[i].user.name)
.replace('{IMG}', img)
.replace('{PROFIMG}', data[i].user.profile_image_url)
/*.replace('{AGO}', JQTWEET.timeAgo(data[i].created_at) )*/
.replace('{URL}', url )
);
if ( (JQTWEET.numTweets - 1) == i) {
$(JQTWEET.appendTo).find(".item").last().addClass("last");
}
}
} catch (e) {
//item is less than item count
}
if (JQTWEET.useGridalicious) {
//run grid-a-licious
$(JQTWEET.appendTo).gridalicious({
gutter: 13,
width: 200,
animate: true
});
}
} else alert('no data returned');
}
});
callback();
},
showHideTweets: function() {
alert("hola");
var ojeto = $(JQTWEET.appendTo).find(".item").first();
$(JQTWEET.appendTo).find(".item").first().css("display", "block");
},
The problem is that if a call functions like this:
$(document).ready(function(){
JQTWEET.loadTweets();
JQTWEET.showHideTweets();
});
Second function executes before tweets has been loaded, so it have nothing to search in, because I can see the alert("hola") working, but Ojeto is 0.
I was trying to create some kind of callback inside loadTweets(); but I could not.
The callback isn't a bad idea.
change loadTweets to look like this:
loadTweets: function(callback) {
And call it here:
$.ajax({
...
success: function(data, textStatus, xhr) {
...
if (callback) callback();
}
});
And then in your DOM ready callback:
$(document).ready(function(){
JQTWEET.loadTweets(JQTWEET.showHideTweets);
});
Your other option (which I actually prefer, in general) is to use a deferred object:
loadTweets: function(callback) {
var def = $.Deferred();
...
$.ajax({
...
success: function(data, textStatus, xhr) {
...
def.resolve();
}
});
return def.promise();
}
...
$(document).ready(function(){
JQTWEET.loadTweets().done(JQTWEET.showHideTweets);
});
Try jQuery methods chaining:
$(document).ready(function(){
JQTWEET.loadTweets().showHideTweets();
});

Categories

Resources