Ferdinand Fatal Ferdinand Fatal - 2 months ago 7
Ajax Question

Ajax Post with [ ] in parameter name [solved]

I need to send an ajax Post to a PHP-Script which expect [] in the Parameter name.

my code:

$("#form").submit(function () {
var salutation = $("input[name='salutation ']:checked").val();
var name = $("#name").val();
var surename= $("#surename").val();
var origin = "true";

var post = jQuery.post(url, {
salutation: salutation,
name: name,
surname: surname,
origin[Newsletterform]: origin
});

post.done(function(data) {
console.log("webservice-done")
});
});


The problem is in the line with origin[Newsletterform]: origin

It tells me that there is a Error in this line.

If I remove the [DATA] part and only use ** origin: origin** it tells me that there is no Error in my Code. But i need to send the Parameter with the [DATA] part.

I can't change something in the PHP-Script because it is not mine and there is no possiblity to change something on that side.

Is there any way to send the parameter name with [DATA]?

It should be like SCRIPT_URL?salutation=salutation&name=name&lastname=lastname&origin[Newsletterform]=true

Any help highly appreciated

Answer

To add a property to an object with that syntax you can wrap it in quotes:

var postData = {
    salutation: salutation,
    name: name,
    surname: surname,
    'origin[Newsletterform]': origin
}

var post = $.post(url, postData);

Or use bracket notation:

var postData = {
    salutation: salutation,
    name: name,
    surname: surname
}
postData['origin[Newsletterform]'] = origin;

var post = $.post(url, postData);