I'm currently facing an issue with executing ajax requests using jQuery. The sequential order in which I am attempting this is as follows:
- Click the button
- Make an ajax post request
- Invoke a function that resides outside the current scope upon completion of the ajax call.
It seems like the problem lies within the on-click callback and the possibility that the 'load' function is out of scope. Strangely, I don't even see the console.log message either, although the ajax call is visible.
Any suggestions or ideas? Could I be approaching this the wrong way?
Below is a sample prototype code akin to what I am attempting to achieve:
$(document).ready(function(){
$('#button').on('click',function(evt){
var data = {};
ajax('index.html', data).done(function(){
console.log('Fire Please'); // This message fails to appear after the ajax call!!!
load(); // This function does not execute after the ajax call!!!
});
});
function load(){
// Perform another ajax call and update the DOM
}
function ajax(url, data){
return $.ajax({
url: url,
type: 'post',
dataType: 'json',
data: data
});
}
});
And Here's the Actual Code I'm trying to use
$(document).ready(function(){
// Attach onclick event to the Add Unit Button
addUnitButt.on('click', function(evt){
var data = {
id: id,
dept_no: dept_no.val(),
dept: dept.val()
};
evt.preventDefault();
dept.val('');
dept_no.val('');
$(this).prop('disabled', true);
ajax('index.html', data).done(function(){
load();
});
});
function load(){
var data = {
id: 575
};
// Display loading animation
showLoading();
// Reset the table DOM
$("#listTable").find("tr:gt(0)").remove();
// Initial retrieval of list data
ajax('index.html', data)
.done(function(units){
var data = toJSONObject(units);
for(var x = 0; x < data.length; x++){
if((x & 1) == 0){
addRow(data[x], data.length, 'odd');
}else{
addRow(data[x], data.length, 'even');
}
}
// Hide loading animation
hideLoading();
});
}
// Function to make ajax calls for data retrieval
function ajax(url, data){
return $.ajax({
type: 'POST',
data: data,
dataType: 'json',
url: url
});
}
});
Thank you in advance!