I wanted to pass a simple key/value string to an Ajax request, but you cannot simply use the variable as the key in the data:

var $fieldname  = 'company_name';
var $value      = 'Tate-Davies Inc.';
var $promise = $.ajax({
    'url'       : '/some/action',
    'dataType'  : 'json',
    'data'      : {
                  $fieldname : $value
                  }
    )};

The above just will not work, and the $_GET will contain:

'fieldname'    => 'Tate-Davies Inc.'

What I actually want is:

'company_name' => 'Tate-Davies Inc.'

So, in order to fix this:

var $data      = JSON.parse('{"' + $fieldname + '":"' + $value + '"}');

And pass that instead:

var $promise = $.ajax({
    'url'       : '/some/action',
    'dataType'  : 'json',
    'data'      : $data 
    )};

By admin

One thought on “Passing variable as key in jQuery ajax”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.