How to use a variable of one function into another?

+2 Altaf Husain Neva · February 20, 2015
I am setting a variable using POST() method in jQuery when my document is ready. Now i want to use that variable in another function, how can i do that?



$(document).ready(function(){

$.post('count_products.php',function(data){
var count_products = data;
});
});



Now i want to use that count_products variable in another function which executes on focusout event. I can not access it's value as it has a limited scope upto its own function only. What is the solution?

Post a Reply

Replies

Oldest  Newest  Rating
0 Jay Deshaun · February 25, 2015
No Problem
0 Altaf Husain Neva · February 24, 2015
@Jay Deshaun.. yeah thanks for the help. It resolved my problem.
+1 Jay Deshaun · February 24, 2015
Well, if you want to use the same var in another function then that means you would need it to be global as you would need to create the var outside of any functions making it global usable to any function on the same page of it.

Here's 2 examples:

This one is making it global only for jQuery functions and events

$(document).ready(function(){
var count_products;
$.post('count_products.php',function(data){
count_products = data;
});
$('object').event(function(){
count_products += 1;
});
});


This one is making it global for the whole page:
<script>

var count_products;
$(document).ready(function(){

$.post('count_products.php',function(data){
count_products = data;
});
$('object').event(function(){
count_products += 1;
});
});
function add(num){
count_products += num;
}

</script>
0 william appiah-dankwah · February 23, 2015
i think you have written that wrong
  • 1

Javascript

107,050 followers
About

A scripting language that is added to standard HTML to create interactive effects, apps, games for the browser.

Links
Moderators