Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Curious: is it possible to have dynamic Ajax data variable names?

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!

like image 325
Trevor Filter Avatar asked Aug 20 '09 09:08

Trevor Filter


1 Answers

If I understand you correctly, this is what you're after:

jQuery.fn.updateChanges = function(){

   this.bind('blur',function(){    

      var data = {};
      data[$(this).attr("name")] = $(this).val();

      $.post('/ajax/updateValue.php',
        data,
        function(ret){
           if (ret=='success') alert("all good!");
        }    
   }    
}

Your main issue was attempting to use a dynamic value using the object literal notation, something you cannot do without reverting to really bad practices (like using eval() where eval() doesn't belong ;).

var myObj = { 'n1': 'v1' };

is equivalent to:

var myObj = {}; // {} = new Object();
myObj['n1'] = 'v1';

is equivalent to:

var myObj = {},
    myKey = 'n1',
    myVal = 'v1';

myObj[myKey] = myVal;
like image 65
Lior Cohen Avatar answered Nov 11 '22 16:11

Lior Cohen