views:

516

answers:

4

I am trying to post an ajax call as if it were the following form element:

<input type="text" name="data[BlogPost][title]" />

But I'm not having any luck here is my source:

    $.ajax({
        url: "/add/",
        type: "POST",
        data: ( /* what do I do here */),
        success: function(msg){
            alert(msg);
        }
    });

I've tried nested objects but that only generates a server response like: array 'data' => string '[object Object]' (length=15)

Which does nobody any good!

Any thoughts?

+1  A: 

Have you tried serialize()?

$.ajax({
    url: "/add/",
    type: "POST",
    data: $('#myForm').serialize(),
    success: function(msg){
        alert(msg);
    }
});

I'm not 100% sure it works on multidimensional arrays but it's worth a shot.

Tatu Ulmanen
This would work in some contexts, but I don't actually have the form to grab data from
SeanDowney
A: 

My guess, [..] square brackets are not valid characters for names of input elements?

Correct me if I'm wrong.

Update: Oops, ok so I'm wrong. Will leave this here anyway as a 'learning' info. For others like me :)

o.k.w
It is actually how both Rails and PHP handle arrays and multidimensional arrays.
Doug Neiner
They are valid, used to denote arrays.
Tatu Ulmanen
An thanks for retracting the down-vote, whoever it might be:)
o.k.w
LOL... it was me. I wanted my rep point back, and since you updated the answer I took it back :)
Doug Neiner
+3  A: 

Just put the field name in quotes, also notice I am using an object literal for the data parameter {} vs the parens you had in your question:

$.ajax({
    url: "/add/",
    type: "POST",
    data: { 'data[BlogPost][title]':'My New Title'} ,
    success: function(msg){
        alert(msg);
    }
});
Doug Neiner
Just curious, does this work? `data: {'data[BlogPost][title]':$("input[name='data[BlogPost][title]']").val()`},?
o.k.w
You would probably need to escape the `[]` characters in the jQuery selector: http://docs.jquery.com/Selectors The list at the very bottom shows what needs to be escaped. That has more to do with jQuery and CSS selectors than it does with valid W3C names.
Doug Neiner
@Doug: thanks for the useful insight!
o.k.w
A: 

SERIALIZE? Are you kidding me? REALLY? a freakin word that have saved me the already spent HOURS on arrays, .each, and other crap I tried and to come to find out that it's just ONE WORD called SERIALIZE?

or more of the term $('#myForm').serialize()

WOW. I'm using ASP.NET 4.0 Beta 2 w/ MVC 2 Preview 2 framework, DataAnnotations, Client-side Jquery Validations, jQuery AJAX, a "Notify" jQuery plugin, and a few others all just for resetting a password for a page. I love MVC 2...

Ray Linder