Reputation: 558
I'm using the following $.post
syntax to retrieve json data from a database and I pass that to a function that appends them to a certain(!) div.
$.post("request.php", { var1:'var1', var2:var2, .. }, myownfunction, "json" );
Can I, from this line here above, pass a variable directly to my function? Due to some glitch, I've created a bug in my script.
I have a lot of divs with the class 'x', and when a user selects one, its class is set to 'selected'. The function in the above post request only targets that: $('div#selected')
, however, if by the time the response comes through the user selects another div, the data from the server gets appended to the wrong div.
I'd like to pass the id of the selected div to my function, so that there could be no confusion in what goes where. Is there a way to do that?
Right now, Im thinking of passing the id to the request.php and return it back as part of the json, but that would so not be elegant.
Upvotes: 0
Views: 117
Reputation: 123739
I'd like to pass the id of the selected div to my function, so that there could be no confusion in what goes where. Is there a way to do that?
Yes, You can use $.Proxy to pass in the context of the clicked div. And access the id of the id using this.id
inside the function.
$.post("request.php",
{ var1:'var1', var2:var2, .. },
$.proxy(myownfunction, elem), "json" );
Inside your function
function myownfunction( response )
{
....
this.id // here will be the id of the element passed if it is the clicked div then you will get it here
....
}
Upvotes: 2
Reputation: 339985
If you use $.ajax
instead of $.post
you can use its context
setting to explicitly set the callback's this
value as required:
$.ajax('request.php', {
type: 'POST',
data: { ... },
context: mydiv
}).done(myownfunction);
function myownfunction(data) {
var id = this.id; // extracting the element here
...
}
Upvotes: 1
Reputation: 33153
If you wrap the function call to an anonymous function you can pass whatever parameters you need.
$.post(
"request.php",
{ var1:'var1', var2:var2, .. },
function( data, textStatus, jqXHR ) {
myownfunction( data, textStatus, jqXHR, myVariable );
},
"json"
);
Upvotes: 1