Reputation: 55
I'd like to share my variable called str with setInterval function. Its needed to build whole url passing to php script. It works fine with ajax function and GET parameter is passing to php script, but I've got some trouble with setInterval function. I dont know to share the same str variable between these two functions. I enclose my code below:
$(function () {
$(document).ready(function () {
var ultimox;
var ultimoy;
$('#list li a').on('click',function() {
var str = $(this).data('driver');
$.ajax({
url: "live-data.php" + str,
type: 'get',
success: function(DatosRecuperados) {
$.each(DatosRecuperados, function(i,o){
//some body of function
});
setx(DatosRecuperados[(DatosRecuperados.length)-1].x);
sety(DatosRecuperados[(DatosRecuperados.length)-1].y);
$('#container').highcharts({
//this part draws chart
}});
});
});
setInterval(function () {
$.get( "live-data.php?Consultar=1" + str , function( UltimosDatos ) {
//this part draws updated chart
}
});}, 1000);
function getx(){return ultimox;}
function gety(){return ultimoy;}
function setx(x){ultimox=x;}
function sety(y){ultimoy=y;}
});
Upvotes: 1
Views: 896
Reputation: 118
In JavaScript, scope refers to the current context of your code. Scopes can be globally or locally defined. Understanding JavaScript scope is key to writing good javascript. You’ll need to understand where variables/functions are accessible.
Javascript scope can be thought of as function scoped. You should take the setInterval()
function and move it inside $(document).ready(function() { ... });
. Since var str;
is declared in that function $(document).ready(function() { ... });
the function setInterval
can now read str
.
I would recommend not polluting the global namespace unless you need to. By this I mean not having the var str;
outside of $(document).ready(function() { ... });
. Keep the variable where you need it.
Upvotes: 2
Reputation: 1118
You can have a global variable in JQuery, try the following example.
<script>
var str = "";
$(document).ready(function() {
//do something with 'str'
//e.g. str = 'Some value';
});
function setInterval()
{
//do something with 'str'
//e.g. str = 'Some other value';
}
</script>
Upvotes: 1