Rabia Rana Khan
Rabia Rana Khan

Reputation: 202

How to save value from JQuery $.post to a Javascript Global Variable

I am using Javascript and JQuery.

I have the following Variable var RoleID=""; and I have placed it outside of all functions.

I have a function

role_submit(){
var role=$('#emp_role').val();
var url="submitrole.php";
$.post(url, {role2: role} ,function(data){
var RoleID=data;
alert(RoleID);
})
}

This function gets the value of an <input type="text" id="emp_role"> and submits to a url='submitrole.php' using JQuery $.post and gets back an ID from url='submitrole.php' in return which is saved in RoleID and afterwards RoleID is alerted. This all is executed using <button onclick="role_submit();" type="submit">Submit</button> and works fine meaning that the ID which should come from url='submitrole.php' comes accurately and is also alerted accurately.

The issue arises when I use following function to look at the global variable var RoleID

function alert_roleID(){alert(RoleID);}

I call to this function using

<button onclick="alert_roleID();" type="submit" >Role ID</button>

This time the alert pops up showing nothing rather than the ID I got back from url='submitrole.php'. How can I get the global variable RoleID to have the value of from url='submitrole.php'?

Upvotes: 0

Views: 132

Answers (2)

I wrestled a bear once.
I wrestled a bear once.

Reputation: 23379

There are two ways.

Set the variable to the window explicitly. Window is the global scope.

function role_submit(){
  var role=$('#emp_role').val();
  var url="submitrole.php";
  $.post(url, {role2: role} ,function(data){
    window.RoleID=data;
    alert(RoleID);
  })
}

Or define the variable in the global scope. If you do it this way, make sure you don't use var when you redefine it. If you use var it makes a new variable only visible in that scope (function).

var RoleID;
function role_submit(){
  var role=$('#emp_role').val();
  var url="submitrole.php";
  $.post(url, {role2: role} ,function(data){
    RoleID=data;
    alert(RoleID);
  })
}

Upvotes: 1

Aruna
Aruna

Reputation: 12022

Once you declared the variable outside, you should not use 'var' once again inside the function since this will recreate the local scoped variable instead of a global scoped variable and inaccessible outside the function. So you can remove the 'var' as below,

var RoleID = '';

role_submit(){
var role=$('#emp_role').val();
var url="submitrole.php";
$.post(url, {role2: role} ,function(data){
   RoleID=data;
alert(RoleID);
})
}

Upvotes: 0

Related Questions