Prodeep Chatterjee
Prodeep Chatterjee

Reputation: 265

How to store value in Global variable which is coming from OnChange to my AJAX script?

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.

HTML

Passing value onChange to ValidUser

<input type="text" name="eMailTxt" id="eMailTxt" onChange="ValidUser(this.value)" />


AJAX##

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

Answers (4)

Mujtaba Haider
Mujtaba Haider

Reputation: 1650

you might need this thing. not mentioning var will make it global

myStr='';
ValidUser = function(str)
{
myStr= str;
}

Upvotes: 1

Manoj Yadav
Manoj Yadav

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

Rohan Kumar
Rohan Kumar

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

daleyjem
daleyjem

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

Related Questions