Reputation: 265
I am trying to store this.value user wrote in eMailTxt box in a Global Variable and then let AJAX do the checking of User exists or not.
Passing value onChange to ValidUser
<input type="text" name="eMailTxt" id="eMailTxt" onChange="ValidUser(this.value)" />
Checks if value exists in database through php
function ValidUser(str)
{
//Want to declare a global variable here
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
if (xmlhttp.responseText=="false")
{
$("#eMailTxt").css({'background-color':'#fed3da','color':'red'});
$("#eMailTxt").val("[User Does Not Exist]"); //Changes text if user does not exist
//Want to store str in global variable so that in $("#eMailTxt").focus function I can store back what was written earlier
}
else
{
$("#eMailTxt").css({'background-color':'#d3fef3'});
}
}
}
xmlhttp.open("GET","loginVerify.php?q="+str,true);
xmlhttp.send();
}
Upvotes: 1
Views: 1161
Reputation: 1650
you might need this thing. not mentioning var will make it global
myStr='';
ValidUser = function(str)
{
myStr= str;
}
Upvotes: 1
Reputation: 6612
Try this:
var eMailTxtVal = '';
function ValidUser(str)
{
eMailTxtVal = str;
$.get("loginVerify.php?q=" + str, function(data) {
if (data == "false") {
$("#eMailTxt").css({'background-color': '#fed3da', 'color': 'red'});
$("#eMailTxt").val("[User Does Not Exist]"); //Changes text if user does not exist
}
else {
$("#eMailTxt").css({'background-color': '#d3fef3'});
}
});
}
$("#eMailTxt").focus(function() {
$(this).val(eMailTxtVal);
});
Upvotes: 1
Reputation: 40639
Add this before your function
like,
var myStr=''
function ValidUser(str)
{
myStr=str; //Add this for assigning previous value in myStr variable
....
Also , if you are using ajax
then use $.ajax function
for this,
var myStr='';
function ValidUser(str)
{
myStr=str;
$.ajax({
url:'loginVerify.php',
type:'GET',
data:{q:str},
success:function(response){
$("#eMailTxt").css({'background-color':'#fed3da','color':'red'});
$("#eMailTxt").val("[User Does Not Exist]");
}
});
}
Upvotes: 1
Reputation: 2674
Just declare the variable "above" the scope of any of your functions. Set it before you change it and then recall it when you need it.
Upvotes: 0