Writing fail case for ajax call in getJSON - javascript

I have following code of ajax call and I would like to write custom error on failed ajax call.In following piece of code block, where I can write the same:
$.getJSON("/ProductMatrix/CaptureCategoryTypeList/" + $("#categoryFilter > option:selected").attr("value"),
function (data) {
var items = "<option> Default </option>";
$.each(data,
function (i, captureCategoryType) {
items += "<option value=' " + captureCategoryType.Value + "'>" + captureCategoryType.Text + "</option>";
});
$("#categoryTypeFilter").html(items);
SherlockAdmin.Shared.closeProcessingWheel();
});

It's as simple as
// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.getJSON( "example.json", function() {
console.log( "success" );
})
.done(function() {
console.log( "second success" );
})
.fail(function() {
console.log( "error" );
})
.always(function() {
console.log( "complete" );
});
// Perform other work here ...
// Set another completion function for the request above
jqxhr.complete(function() {
console.log( "second complete" );
});
Code from http://api.jquery.com/jquery.getjson/

Related

Ajax call in loop: Ajax requests getting cancelled except last

I have one ajax call in a loop as shown below.
reloadSetupAndRecurringAvailable = function( objDiscountRow ) {
var intProductId = objDiscountRow.find('.product-id').val();
var strUrl = '/?module=contract_setup_products-new&action=get_setup_and_recurring_available';
$.ajax( {
url: strUrl,
data: { 'product_id': intProductId },
success: function( response ) {
fltSetupAvailable = parseFloat( response.data.fltSetupAvailable );
fltRecurringAvailable = parseFloat( response.data.fltRecurringAvailable );
objDiscountRow.find('.setup-available').text( fltSetupAvailable + '%' );
objDiscountRow.find('.recurring-available').text( fltRecurringAvailable + '%' );
}
} );
reloadDiscountProducts = function() {
$('.discount-row').each( function() {
reloadSetupAndRecurringAvailable( $(this) );
} );
}
reloadDiscountProducts();
When the code executes, in the network tab the last ajax call shows successful and all the previous calls show in canceled status.
As per my findings it is due to asynchronization. The ajax request can take any time. How can I fix the code so that all the requests will be in completed status?

get value from $(document).ready

I am pulling temperature reading from my temp.php and displaying it on my index.php with the code below.
My problem is I cannot use the information for anything else
I would appreciate any suggestions.
<div id = "temperature"></div> // displays as expected
$(document).ready(function(){
setInterval(function(){
$("#temperature").load('temp.php')
}, 1000);
});
temp1 = document.getElementById('temperature').value; // this doesn't work
if (temp1 == 72) {do something}; //cannot get the value of "temperature"
You should get the response in the callback like the following
<script>
$( "#success" ).load( "/not-here.php", function( response, status, xhr ) {
if ( status == "error" ) {
var msg = "Sorry but there was an error: ";
$( "#error" ).html( msg + xhr.status + " " + xhr.statusText );
}
});
</script>

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>

My $(document).ajaxComplete() doesn't work

I'm messing with jQuery an AJAX for few days and I've come to a dead end. I'm trying to load some content with AJAX -this part works just fine - and after that I want to execute other script. However, my content loaded with first script doesn't show up till the second script is finished. Code looks like this:
$.ajax({
url : folder,
success: function (data) {
$(data).find("a").attr("href", function (i, val) {
if( val.match(/\.(jpe?g|png|gif)$/) ) {
var $codeText = "<li class='ui-state-default'><a href='#' data-featherlight='" + folder + val + "'><img src='" + thumbFolder + val + "' data-src='"+ thumbFolder + val + "'/></a></li>";
$("ul[id=sortable]").append($codeText);
$("li").featherlight(folder + val);
};
});
}
})
$(window).ajaxComplete(function(){
console.log("Haba");
var x = 0;
while( x < 50000 )
{
console.log("Haba nr "+x);
x++;
}
The whole code is triggered, but images are showing up on website after all the console messages. Does anyone have any suggestion what to do to show up pictures first? I've also tried with done(). and ajaxStop(), still no effect.
you have to use the .done() function of ajax to get the asynchrone result :
var jqxhr = $.ajax( "example.php" )
.done(function(data) {
alert( "success : " + data );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "complete" );
});
Why not just move the code you want to run after the pictures are loaded into the success function of the ajax call and do that after the code to load pictures?
$.ajax({
url : folder,
success: function (data) {
//Code to load pictures
console.log("Haba");
var x = 0;
while( x < 50000 ) {
console.log("Haba nr "+x);
x++;
}
});
I think the reason it's not behaving the way you want it to is because the ajax call is complete after it gets a response back. That response triggers the ajax complete function that runs before your logic in the success function of the ajax call. Also, the way you have it written, the ajax complete logic will fire even if your ajax call fails. Which I don't think you want.
try to use setTimeout()
function ajaxDone(){
console.log("Haba");
var x = 0;
while( x < 50000 )
{
console.log("Haba nr "+x);
x++;
}
}
$(window).ajaxComplete(function(){
window.setTimeout(ajaxDone,1);
});

Adding options to select field using javascript from a json file

var json = $.getJSON("../category.json", function() {
alert(2);
})
.done(function() {
console.log( "second success" );
var var1 = document.getElementsByClassName('category');
var1.innerHTML = "<option value='" + key + "'>" + val + "</option>";
alert(var1);
})
.fail(function() {
alert( "error" );
});
I want to values from json file as options to my select field. But my code always shows alert error. Please tell me what is wrong with it ?
You're not setting your key and value parameters. In fact it doesn't look like you're getting your JSON results at all.
Change your done method to
.done(function( data ) { /* do stuff */ }
Now your JSON results will be stored in data.
Then you may need to loop through the results. See the example here
try this
var json = $.getJSON("../category.json", function(data) {
alert(2);
})
.done(function(data) {
console.log( "second success" );
var var1 = document.getElementsByClassName('category');
$.each( data, function( key, val ) {
var1.innerHTML += "<option value='" + key + "'>" + val + "</option>";
alert(var1);
});
alert(var1);
})
.fail(function() {
alert( "error" );
});
Your JSON is not valid: You cannot use a number as a JSON key
[
{
"NAME":"chair",
"0":"chair" <-- error
},
{
"NAME":"bed",
"0":"bed" <-- error
},
{
"NAME":"table",
"0":"tabl‌​e" <-- error
},
{
"NAME":"almira",
"0":"almira" <-- error
}
]
Try running your JSON through an online JSON parser and the error will come up.
Alternatively, change your error handler to include more information
.fail(function (jqXhr, status, error) {
alert(status + ':' + error + ':' + jqXhr.responseText) }
});

Categories

Resources