Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Ajax call - Set variable value on success [duplicate]

I have an application that I am writing that modifies data on a cached object in the server. The modifications are performed through an ajax call that basically updates properties of that object. When the user is done working, I have a basic 'Save Changes' button that allows them to Save the data and flush the cached object.

In order to protect the user, I want to warn them if the try to navigate away from the page when modifications have been made to the server object if they have not saved. So, I created a web service method called IsInitialized that will return true or false based on whether or not changes have been saved. If they have not been saved, I want to prompt the user and give them a chance to cancel their navigation request.

Here's my problem - although I have the calls working correctly, I can't seem to get the ajax success call to set the variable value on its callback function. Here's the code I have now.

   ////Catches the users to keep them from navigation off the page w/o saved changes... window.onbeforeunload = CheckSaveStatus; var IsInitialized;  function CheckSaveStatus() {      var temp = $.ajax({         type: "POST",         url: "URL.asmx/CheckIfInstanceIsInitilized",         data: "{}",         contentType: "application/json; charset=utf-8",         dataType: "json",         success: function(result) {             IsInitialized = result.d;         },         error: function(xmlHttpRequest, status, err) {             alert(xmlHttpRequest.statusText + " " + xmlHttpRequest.status + " : " + xmlHttpRequest.responseText);         }      });      if (IsInitialized) {         return "You currently have unprocessed changes for this Simulation.";     } } 

I feel that I might be trying to use the Success callback in an inappropriate manner. How do I set a javascript variable on the Success callback so that I can decide whether or not the user should be prompted w/ the unsaved changes message?

As was just pointed out, I am making an asynchronous call, which means the rest of the code gets called before my method returns. Is there a way to use that ajax call, but still catch the window.onunload event? (without making synchronos ajax)

like image 476
Nathan Avatar asked Apr 02 '09 14:04

Nathan


2 Answers

Since you need this behavior in the unload event, you will have to make a synchronous call instead. However it may freeze the browser window/tab dependent on how long the call will take, but because you're effectively trying to prevent the user from closing the window...

Add async: false to your JSON to make a synchronous call.

like image 180
Pawel Krakowiak Avatar answered Sep 24 '22 00:09

Pawel Krakowiak


An example of jquery page:

var html = $.ajax({   url: "some.php",   async: false  }).responseText; 

Source: http://api.jquery.com/jQuery.ajax/

like image 42
Vale Avatar answered Sep 26 '22 00:09

Vale