John Hora
John Hora

Reputation: 17

Global variable in javascript result is always undefine

I had trouble with my global variable hope you can help me.

<li>
 <a href="<?php echo site_url("adminController/questionAdd/".$row->subjectid); ?>" id="<?php echo $row->subjectid; ?>" class="subject">Add Question</a>
</li>

Now from that line I passed my id in this line by click() in javascript

$(document).ready(function () {
        var correctAnswer;
        var subId;

        $( ".subject" ).click(function() {
            subId = ($(this).attr('id')); //passed the id variable into the global variable
            alert(subId) // when I alert this it returns the value
        });

now I used the global variable in this line the same $(document).ready(function ()

$('#form-user').submit(function(e){
                e.preventDefault();

                var me = $(this);
                var correct = correctAnswer;
                var passedSubId = subId; // passed the global variable to this local variable 
                console.log(correct); // this is okey
                console.log(subId); // this is undefined
});

result

i
undefined

Upvotes: 0

Views: 69

Answers (2)

scx
scx

Reputation: 2789

Your code will never work as you think it will.

What you are doing there I think is you click on your link, which then moves you from page A to page B, and you want to use that variable that you set on page A on page B, sorry but this will never work, when you refresh your page your entire script is run again and it does not know what have you done on the previous page. You would have to either take that id from the url ( its there ) or store it for example in local storage, try this:

$(document).ready(function () {
    var correctAnswer;
    var subId;

    $( ".subject" ).click(function() {
        subId = ($(this).attr('id')); //passed the id variable into the global variable
        alert(subId) // when I alert this it returns the value
        localStorage.setItem('subId', subId);
        console.log('id stored');
    });

    $('#form-user').submit(function(e){
            e.preventDefault();

            var me = $(this);
            var correct = correctAnswer;
            var passedSubId = subId; // passed the global variable to this local variable 
            console.log(correct); // this is okey
            console.log(subId); // this is undefined

            storedSubId = localStorage.getItem('subId');
            alert(storedSubId); 
            console.log('stored id');
    });
});

Anyway getting it from url is definitely the way you want to go

Upvotes: 0

Pritam Banerjee
Pritam Banerjee

Reputation: 18923

You can use window to declare a global variable though it is highly recommended not to use.

You can declare a global variable like this:

window.yourVariable = "something";

Upvotes: 1

Related Questions