Israel
Israel

Reputation: 1224

Error ' missing : after property id' when using Jquery ajax function

In the following code, I'm trying to send a key-value pair and I always get the error:
" missing: after property id "

$(".general").change(function () {
  fields = { $(this).attr('id') : "1" };
  $.ajax({
   type: "POST",
   url: "ajax/update_general.php",
   data: { fields: fields },
   dataType: "json",
   });
})

I've figured that what causes the problem is:

$(this).attr('id')

But I have no clue why. I've tried to first assign $(this).attr('id') to a variable, and put the variable in the ajax call, but that didn't help. How can I fix that?
Thank you!

Upvotes: 3

Views: 5356

Answers (3)

Nikolay Yordanov
Nikolay Yordanov

Reputation: 1404

Change this line:

fields = { $(this).attr('id') : "1" };

to this:

fields = $(this).attr('id') || "1";

That's if you intended to have something like a default value.

If you want an object, use this:

fields[$(this).attr('id')] = "1";

Upvotes: 0

Taha Jahangir
Taha Jahangir

Reputation: 4902

When declaring object with {} syntax, ONLY strings (like {'foo':1}) or bare string is allowed ({foo:1})

You should write something like this:

var fields = {};
fields[$(this).attr('id')] = 1;

Upvotes: 0

BoltClock
BoltClock

Reputation: 723568

It's a syntax error. You can't use the return value of a function call as a property name.

You can, however, use that return value in bracket notation after initializing the object:

  fields = {};
  fields[$(this).attr('id')] = '1';

Upvotes: 8

Related Questions