简体   繁体   中英

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(ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM