Learn, Share, Build

187
September 25, 2017, at 04:28 AM

I have my ajax call like this and I want to set a variable globally so I can use it letter My code is below Please give suggestions for accessing UserTr variable:-

    var UserTr;
    $.ajax({
            url:'ReAjaxFunction.php',
            data:'fun=3',
            type:'POST',
            cache:false,
            success:function(UserResponse){
              var FetchAppUser= JSON.parse(UserResponse);
              $.each(FetchAppUser.AppUser,function(key,value){
                UserTr ='<tr><td colspan="2">Approval Status</td></tr><tr><td>'+value.Name+'</td><td>'+value.ApprovalStatus+'</td></tr>'
              });
            }
          });
    alert(UserTr);
Answer 1

Your alert at the end is being invoked its just the Ajax call is asynchronous so the alert is running before the Ajax call completes.

At the time of the alert your variable UserTr is un-defined so your alert is empty.

However, if you were to move your alert call to the inside of the Ajax call right after you actually set the UserTr variable then it would be defined and have a value (assuming the JSON parse succeeds and the expected structure is present.

That being said, the way you set UserTr inside of the Ajax call means that on each loop iteration of $.each it is being over-written -- I think you want to use UserTr += to accumulate a series of table rows.

To do that you'd also want to initialize your variable to a string.

So do this:

var UserTr = "";

Then replace UserTr = ... with UserTr += ...

After your iteration then you can do something with the fully populated UserTr

READ ALSO
Learn, Share, Build

Learn, Share, Build

How to get last folder name from URL path 000000

176
Learn, Share, Build

Learn, Share, Build

I need to be able to select a row in a table by clicking it (and using css class for highlight styling)

146
Learn, Share, Build

Learn, Share, Build

I am trying to show progress/spinner when user selects all the check boxes in the Kendo Grid using kendoui

173
Learn, Share, Build

Learn, Share, Build

I am creating dynamic array and this array value is that :-

202