tut
tut

Reputation: 3

Javascript passing variable from ajax function

I'm a learner and i'm facing a problem. First i made a variable. then with a ajax function i have got a json data. then i parsed it and tried to pass the json data to my variable named var invoice_details. Then with a click event i tried to see the variable but its showing only 0. but my console.log(parsed); command under ajax function showing the json data on my console log. but the console.log(invoice_details); on my action function showing 0. What wrong with me?

//function order started
var invoice_details;
function order(val1){
var order_no=getQueryVariable("order_number");
//AJAX START    
    $.ajax({
        url: "/anamika/function/order.php",
        type: "POST",
        data: {item_code: item_added, paymentdetails: val1, order_no: order_no }, 
        success:function(data, textStatus, jqXHR)
        {
                //console.log(data);
                var parsed = JSON.parse(data);
                var invoice_details = parsed;
                console.log(parsed);

        },//Success finished
        error:function(jqXHR, textStatus, errorThrown)
        {

        } //Error finished
    }) //AJAX FINISHED

}
//function order finished

order('91');

$("#invoice_pay").live("click", function (event) {
            console.log(invoice_details); 

})

Upvotes: 0

Views: 97

Answers (1)

Omri Aharon
Omri Aharon

Reputation: 17064

When you declare var invoice_details = parsed; inside the success callback, you are actually creating a new local variable that lives only on the scope of the success callback, and hence this new local variable is getting your data and not the global one you're then performing the console.log on.

You already defined that variable on the outside, so just remove the var declaration and do:

invoice_details = parsed;

Upvotes: 4

Related Questions