1

Here is my working code:

jQuery.ajax({
type: 'post',
url: ajaxurl,
dataType: 'json',
data: jQuery('select[name^="option"], :input[name^="option"]),
success: function (mydata) {
    // do something
}
});

I want to add a variable to be passed back along with the select and textbox option values called 'myVar'. But I don't see it in the parameters when I add it:

var myVar = '123';

jQuery.ajax({
type: 'post',
url: ajaxurl,
dataType: 'json',
data: jQuery('select[name^="option"], :input[name^="option"], myvar='+myVar),
success: function (mydata) {
    // do something
}
});

Am I doing something wrong? Do I need to serialize or encodeURIcomponent or something? Nothing seems to affect it. I still get the select and textbox data, but myVar doesn't come at all in the $_POST side.

Thoughts?

2
  • How would that work, it looks like you're trying to pass a jQuery object ? Commented Sep 21, 2013 at 14:36
  • yes, if you pass jQuery form elements, they auto-encode or serialize. It works nice actually. But when trying to pass other non-form elements on the same data line, I'm not sure how they blend Commented Sep 21, 2013 at 14:52

1 Answer 1

2

Have you tried:

 var myVar = '123';
 jQuery.ajax({
    type: 'post',
    url: ajaxurl,
    dataType: 'json',
    data: jQuery.param(jQuery('select[name^="option"]').val()) + jQuery.param(jQuery('input[name^="option"]').val()) + '&myvar=' + myVar,
    success: function (mydata) {
        // do something
    }
  });

I think you can also use traditional: true instead of param

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

1 Comment

well there could be many selects and inputs.. oddly when you pass form inputs like that they seem to self-serialize. If I changed it to your way would it assume only a single input?

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.