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

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'?

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);
})
}

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);
})
}

Related

Retrieving Variable From A Javascript File

My question is how to share a variable between two different javascript files. I am creating a form that transfers the value to a different page, which alerts that variable. I have 2 html files (index.html and form.html) as well as 2 javascript files (form.js and index.js). So basicly I want to share the variable theNick from form.js to index.js to display it using alert(). If this is not possible, is there another way to do this?
form.html:
<input type="text" id="Nick" placeholder="Nickname">
<a id="btn" onclick="submit()" href="index.html.">Submit</a>
form.js:
function submit(){
var theNick = document.getElementById("Nick").value; //retrieves theNick from your input
???
}
index.html:
<button onclick="callNick()">Click Me to view your Nickname.</button>
index.js:
function callNick(){
???????
alert(theNick); //I want to get access to this variable from form.js
}
By using the var keyword you are doing exactly the opposite. If you want to share something the easiest thing would be to bind the variable to the window object like this: window.theNick = ... and use it like alert(window.theNick).
It is sort of possible.
First of all you need to make certain that your HTML loads both JavaScript files. There isn't really a way for them to import each other, so the HTML must load both scripts.
Secondly, you need to modify your function submit to use a global variable. Global variables are initially defined outside the scope of a function. The function callNick is already looking for a global variable.
However, the submit function is defining its own, local variable because of the keyword var being used inside the function scope. Change it like so:
// Set global variable
var theNick;
function submit(){
// Use global variable
theNick = document.getElementById("Nick").value; //retrieves theNick from your input
???
}
See this article for further information.
http://www.w3schools.com/js/js_scope.asp
You could just declare the variable outside of the function
var theNick; // you could omit this entirely since it will be declared in
// global scope implicitly when you try to assign it in the function
function submit(){
theNick = document.getElementById("Nick").value; //retrieves theNick from your input
}
javascript does not care about which files declarations are made but in which scope.
By placing the variable in global scope you'll be able to access it everywhere.
Global variables are not the best coding strategy but this should help you with the concept
It seems like you need to store the variable in the local storage object of the window object, this way you can set its value on the first page and retrieve it on the second.
page 1
window.localStorage.setItem("yourVariable", "yourValue");
page 2
var myVar = localStorage.getItem("yourVariable");
Only one 'caveat': this is a html5 feature, so it comes with limitations, check this link for more info.
You can pass your variable into the url, using the ?yourVar= GET mark :
form.js
function submit(e){
var theNick = document.getElementById("Nick").value; //retrieves theNick
e.target.href+='?n='+theNick; // set the href of your anchor with your variable
}
form.html
<input type="text" id="Nick" placeholder="Nickname">
<!-- We pass the event object into our function as a parameter -->
<a id="btn" onclick="submit(event)" href="index.html">Submit</a>
index.js
function callNick(){
// get the variable from the current location
var theNick = window.location.href.split('?n=')[1];
alert(theNick);
}
index.html
<button onclick="callNick()">Click Me to view your Nickname.</button>
▶︎ Plunker where "form" has been changed to "index" and "index" to "result".
Note :
To pass multiple variables, you can use the & delimiter, and then use the window.location.search property as done in this CSS-tricks article.
▶︎ Multiple vars plunker

Calling function from a variable

I want to call a function and the function name is stored into a variable, but it is giving error. I am trying to call a function uploadDocumentCallback but its name is stored into a variable
$scope.uploadDocumentCallback(data,status,headers,config); //its working fine if i'm passing callback function name directly.
$scope.callback = "uploadDocumentCallback"; //this is my variable where I store function name
var callbackFunction = $scope.callback;
$scope.callbackFunction(data,status,headers,config); //not working
callbackFunction(data,status,headers,config); //not working
$scope.callback(data,status,headers,config); //not working
Please suggest me that how can I achieve this?
I managed it to work
$scope[$scope.callback](data,status,headers,config);

How to get global variable value to ajax

i am trying to get the global variable value inside ajax,jquery function.
here i am using this code..
code:
<script type="text/javascript">
var id;
function refreshRecord(id)
{
alert(id);
}
$(document).ready(function(){
$("#refresh").click(function(){
var fileId=id;
alert("id is"+fileId);
$.ajax({
type:"post",
url:"checkStatusAndNumRecs",
data: {fileId:fileId},
success:function(data){$("#div1").html(data);},
error:function(data){$("#div1").html("It was a failure !!!");}
});
});
});
</script>
Onclick one submit button i am calling the javascript function
<input type="radio" name="submit" value="submit" onclick="refreshRecord(this.value)">
Here what i want to get is, i have declared the global variable id in script tag,
when i click on radio button the onclick event calls the javascript function refreshRecord(id) with one parameter 'id'
now that id value will be set to some value. now i want to get that variable value inside jquery function and i want to assign it to
var fileId = id;
but when i did the above code and click button.
in alert it is showing the first value correctly(i.e the alert from javascript is coming correctly) but the alert from the ajax,jquery is coming is as undefined or [Object Object]
How can i resolve this??
You need to assign the value passed to the function to the global variable id. Currently you are not assigning it. The parameter id of the function is just local to the function , it is not the same global one and the global variable id is still undefined.
Just modify as below,
var id;
function refreshRecord(value)
{
id = value;
alert(id);
}
You should put the value from the field inside the global variable:
var id;
function refreshRecord(inputValue)
{
id = inputValue;
alert(id);
}
Because if you do this:
function refreshRecord(id)
{
alert(id);
}
the id global variable won't be accessible inside the refreshRecord function because of a name conflict inside the function scope. Please read about scope to understand:
http://robertnyman.com/2008/10/09/explaining-javascript-scope-and-closures/
The argument we pass inside a function acts as a local variable to that function. So in your function you are actually creating a local variable and setting the value.
Try this instead -
var id;
function refreshRecord() {
id = $("input:radio").val();
}
Give an id to have better selector for radio button.

Can't access a global variable

I'm trying to access a global variable in testGlob1, however I'm not able to do so:
var displayVar;
function globVariable(){
displayVar="2";
}
function testGlob1(){
alert(displayVar);
}
You aren't showing how your variable is being assigned a value. Is globVariable() being called on load of the document? Im sure this would work:
var displayVar=2;
function testGlob1(){
alert(displayVar);
}

Undefined function called within another function

I have a simple script which calls a function that is set in the function that the call is made...
But i get an "undefined function" error.
My script is:
function messages_document(messages){
messages = JSON.parse(messages);
function del_msg(id){
result = call_file('del.php',id);
if(result){
messages[id].length = 0;
}
}
var output = [];
output.push('<p align="center"><b><u>My Messages</u></b></p> <br/><br/>');
for(var id in messages){
output.push('Delete Message');
}
document.getElementById('main').innerHTML = (output.join(''));
}
I'm curious if i have misunderstood how scope works because i get:
del_msg is not defined
Any ideas why this is ?
You have a problem with the scope in that "del_msg" is defined: You need that function to be in the global scope, but you're creating it inside a function "messages_document" (that has its own scope).
Function statements are defined in the current scope, not globally. In this case, that means that del_msg exists only within the scope of messages_document. However, you invoke it via an onclick attribute: these attributes are evaluated globally. Since del_msg doesn't exist globally, it doesn't work.
You have two options. One is to make del_msg global, by defining it outside any other functions. However, this pollutes the global namespace, generally a bad thing. Better would be to apply it to your a element within the scope. This is going to require building the elements via DOM methods, rather than by HTML
var para = document.createElement('p'),
id,
link;
para.innerHTML = '<b><u>My Messages</u></b></p> <br/><br/>';
para.align = 'center';
for(id in messages){
link = document.createElement('a');
link.href = '';
link.onclick = del_msg;
link.innerHTML = "Delete message";
para.appendChild(link );
}
document.getElementById('main').appendChild(para);
Try declaring it like
var del_msg = function(id)...
Sorry confused. you are using the function on the window scope do declare it out of the other function.
The function is called with the onclick global scope.
What you have to understand here is that you are creating html code, but the onclick will be called when user click and not when you vreate the html.

Categories