2

I am passing this function different field names on each call. I would like it to post the interpolated string value of the variable field as the name of the posted var. Eg one post might have

data: { 'shoppingCartContents' : cartrow, 'number' : number, 'foo' : value }

but every post just has

data: { 'shoppingCartContents' : cartrow, 'number' : number, 'field' : value }

even though field is not in quotes.

function update_personalization(cartrow, number, field, value) {
  $.ajax({
    type: 'POST',
    url: 'updatePersonalization.php',
    data: { 'shoppingCartContents' : cartrow, 'number' : number, field : value }
  });
}

What am I doing wrong?

1 Answer 1

5

You'll have to build the object differently:

   data: (function() {
     var rv = {shoppingCartContents: cartrow, number: number};
     rv[field] = value;
     return rv;
   })()

What that does is build up the object you want to pass as "data" in a little anonymous function. The function initializes a simple object with the static field names, then adds the dynamically-named field in a separate statement.

That's not really an "array", for what it's worth.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Pointy. Much obliged!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.