Some background:
On a recent project, I tried to write a streamlined jQuery plugin that would handle some Ajax calls made when various inputs were updated. I wrote the JavaScript function as a plugin so that I could just call it on various inputs, like so:
$("#email").updateChanges();
Then, from within the plugin, I collected the input's id, value, etc.
The problem:
Something that I really wanted to do, but couldn't find a solution for, was to dynamically generate the name of the data variable being passed through ajax.
To be more clear, given this function:
jQuery.fn.updateChanges = function(){
this.bind('blur',function(){
var inputName = $(this).attr("name");
var inputValue = $(this).val();
$.post('/ajax/updateValue.php',
{ email: inputValue }, function(ret){
if (ret=='success') alert("all good!");
}
}
}
...how do I present the data for the Ajax call as { password: inputValue }
instead of { email: inputValue }
when the inputName variable is "password" instead of "email"? This is a very specific example, but basically I'm just looking for a way to read the name of the data variable from a separate dynamic variable.
I tried window[inputName]
with no luck, and I'm pretty much convinced this is impossible. However, if someone has an idea, I'd be very impressed.
Incidentally, we ended up going with { type: inputName, value: inputValue }
instead, but it required a little bit more legwork on the PHP side (don't ask me, I'm just the front-end guy :).
Thanks in advance!