Is it possible to pass predefined variables to functions called upon successful jQuery $.get request?
As in the example below the PHP script would return "bar":
var extra = "foo";
$.get(baar.php, function(data, extra){
alert(extra + data);
});
Thus my goal being an alert box proclaiming "foobar" to the world.
Thanks.
Is it possible to pass predefined variables to functions called upon successful jQuery $.get request?
As in the example below the PHP script would return "bar":
var extra = "foo";
$.get(baar.php, function(data, extra){
alert(extra + data);
});
Thus my goal being an alert box proclaiming "foobar" to the world.
Thanks.
Share Improve this question asked May 7, 2013 at 20:09 MatteMatte 2796 silver badges16 bronze badges 2- JavaScript functions are closures. No need to do anything more than just reference the variable. – user1106925 Commented May 7, 2013 at 20:12
-
...that said, another option is to take the
jqxhr
object returned from$.get()
and add properties to it. That object will be available as the 3rd argument to the callback, as well as thethis
value, allowing you to retrieve the property. This helps make your function reusable. – user1106925 Commented May 7, 2013 at 20:15
3 Answers
Reset to default 4You don't need to pass it, extra
will be available inside the callback because of how JavaScript scoping works. So:
var extra = "foo";
$.get('baar.php', function(data){
alert(extra + data);
});
I don,t think it is possible. but you can use external variable inside function
var extra = "foo";
$.get(baar.php, function(data){
alert(extra + data);
});
I know this post is old(er), but I had this same problem and thought I'd post the solution for the next guy. Basically, like bfalvretto says above, jquery's .get() and .post() functions are async, so by the time it got the remote url, the variable's value was different.
My solution was to throw the .get() part of it into it's own separate function to limit the scope of the callback.
This is what I came up with:
$("#SomethingClick").click(function(e) {
e.preventDefault();
$.post("..getURL", { id: 123 }, function(data) {
for (i = 0; i < data.rows.length; i++) {
ExternalFunction(data.rows[i].Value1, data.rows[i].Value2);
}
});
});
...
function ExternalFunction(value1, value2) {
$.get("/Core/ContactViewer/" + contactID, function (data2) {
$("someoutputdiv").html("<div>" + value1 + ": " + value2 + "</div>");
});
}
Hope this helps.