erol_smsr erol_smsr - 1 year ago 89
Ajax Question

Javascript can't access global variable

I have a global variable called

, that holds the price of a selected product. I change the value of this global variable with a function, and then with another function I submit it to a server with an AJAX post request:

var calculated_price;

function calculatePrice() {
calculated_price = $$( '.myInput' ).val();
$$( '.price-holder' ).text( calculated_price );

function submitOrder( calculated_price ) {
if( calculated_price !== null || calculated_price !== '' ) {

$$.post( '', { price: calculated_price},
function( data ) {

alert( 'Data: ' + data );



I'm using Framework7, so the JS framework I use is Dom7, however this is very similar to jQuery and the $$.post function I'm using always worked so far. It just can't seem to access the
calculated_price variable
. I've not redeclared this variable anywhere in my code (nowhere have I put
in front of it except for when it's declared globally). Any idea why this variable gets lost until the last function is executed (submitOrder)? I know the variable exists and has value, because in the
function I put the calculated price inside an HTML element and it does show the price correctly.

Answer Source

You are declaring calculated_price globally, and then you use the same name as function parameter.

var calculated_price;

function submitOrder( calculated_price ) { <---- error is here

Those are 2 different variables. When you call submitOrder, do you send calculated_price as a parameter?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download