简体   繁体   中英

Updating global variable after ajax function call with jQuery

Not sure why the following doesn't work. I hope somebody can shed some light.

I have a global parameter reresenting a certain id of an item in a database. Now in order to check if the db should be updated or a new entry should be made for the item, I check before making the ajax call if the variable is set. If the variable is set, I know I have to update the db, if its not set I know I have to insert into the db. Then on the server side I return a newly generated id in case of an insert or else just the old id in case of an update. I use the jQuery form and validate plugins by the way (hence the function call ajaxSubmit()). However, the assignment in the success function of submitHandler doesn't seem to work (I have checked that data.poiId returns a suspected result).

$(document).ready(function() {

    // Function which examines window.location.href and extracts a numerical id if there is one specified in the query
    var id = getParameter('poiId')

   ...

   },
   submitHandler : function(form) {
       var str = 'submitPOI.php';
       if (id.length > 0) str += '?poiId=' + id;

       $(form).ajaxSubmit({
           url : str,
           type : 'POST',
           dataType : 'json',
           success : function(data) {
               id = data.poiId     // Update POI id with response from server
           } 
       });
   }

   ...
});

Seems to me that your id variable is not global as it is declared in the $(document).ready() function. Move it outside the function and check if it works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM