In the script below, I’m trying to parse through a select list and for each option, call a php that returns a value (psuedo true/false) based on the options “value” attribute.
However, when I’m inside the $.get [to evaluate the return value and execute script against the current option in the each(),] I can’t figure out how to reference the current option element in order to modify it.
$('#my_Select').click(
function(){
$('#my_Select option').each(
function(){
$.get(
'<?php echo getStyle.php',{option: $(this).val()},
function(response){
alert($(this).val()); //Returns empty alert. Should return value of current option
//$(this).attr("disabled","disabled");
//if (response.Success){$(this).attr("disabled","disabled");}
});
});
});
Here’s the php script for reference…
<?php
//getStyle.php
$myOption = $_REQUEST['option'];
$file = "styles/".$myOption."/style.css";
//echo json_encode(file_exists($file));
if (!file_exists($file))
{
$Response = array('Success' => true);
}
else
{
$Response = array('Success' => false);
}
echo json_encode($Response);
?>
thiswithin thegetsuccess callback won’t refer to the element anymore (any time there’s a new function,thiswithin the function may be different fromthisoutside of it, and probably will be; more here).You can solve it like this, using the closure you already have:
Or you can use
ajaxinstead ofget(getis just a wrapper anyway) and use thecontextparameter to tell jQuery what to use forthiswhen calling your callbacks:Edit: Below, @Hakre asked, referring to the first example above:
The answer is no, but it’s a very good question. The reason lies at the heart of how JavaScript resolves free symbols (e.g., stand-alone “variable” names) and how closures work.
When a function is called, the JavaScript interpreter creates something called an “execution context” for that specific function call. That execution context has something we’ll call the “variable object” that holds the variables and such related to this specific call to the function (technically they’re held on the [deep breath] binding object of the variable context of the execution context — gotta love spec-speak).
Functions created within that function call keep a reference to the variable object for the execution context in which they were created; this is how closures work. The interpreter resolves a free symbol by looking on the variable object for this function call to see if there’s a matching variable (I’m simplifying here). If there isn’t, it looks at the variable object for the containing execution context, and then to the one outside that, etc., etc., until it gets to the global context. (This is how global variables work; they’re a natural consequence of closures.) This chain of variable objects is called the scope chain.
So in the above, there are multiple
optionvariables, each intrinsically tied to thegetcallback defined in the same call. So that callback sees the correctoptionvariable, regardless of timing.