My JavaScript application is having a strange result.
I have some functions that are called which in turn execute an AJAX request, the result of that request is supposed to be set to a variable and then passed on to the next function.
The problem is that the AJAX request is made and then the code keeps moving forward without waiting for the response of the AJAX to set the variables first!
Below is the flow of things...
After DOM has loaded and is ready....
projectTaskModal.task.openTaskModalFromUrlHash(hashTaskId);
function is calledInside of
openTaskModalFromUrlHash(hashTaskId)
var taskJsonData = projectTaskModal.task.loadTaskAjaxRequest(taskId);
is ranI then print the value of
var taskJsonData
which isundefined
var taskJsonData
is set from teh result ofloadTaskAjaxRequest(taskId)
now inside of
loadTaskAjaxRequest(taskId)
this AJAX call is made...// Request Task Record using AJAX Request to Server $.ajax({ type: 'GET', contentType: 'application/json; charset=utf-8', dataType: 'json', url: projectTaskModal.cache.getTaskRecordUrlEndpoint, data: { action: 'load-task-record', task_id: projectTaskModal.cache.taskId }, success: function(data) { // Parse JSON data var var taskRecordJson = data; var task_record = taskRecordJson.task_record; // Return Task Record Object console.log('task_record var loaded from AJAX SUUCCESS...',task_record); projectTaskModal.cache.taskData = task_record; console.log('projectTaskModal.cache.taskData', projectTaskModal.cache.taskData); return task_record; } });
You can see my AJAX request returns a varible
task_record
So
task_record
is supposed to be returned to thevar taskJsonData
in step 3 above, however it isundefined
!Back to my AJAX request, where I print the content of the return to console, it prints the correct data out.
So it seems that for some reason, my code at the top make the AJAX call but then continues on with the execution without waiting for the AJAX response! So it seems the data is set, it is just set after it is needed!
Now I am using a library called MockAjax
to intercept my AJAX cals and return Mock data, i've never had this issue though so I am ot sure why it is processing without waiting for my AJAX result to be returned first!
I will make a dmeo if needed, right now my app is about 2,000 lines so I was hoping this is something I could describe first without getting into a demo too much but will if I have to!
THanks for any insight or help