2

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?

3 Answers 3

7

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);
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

Just curious, does this work? data: {'data[BlogPost][title]':$("input[name='data[BlogPost][title]']").val()},?
You would probably need to escape the [] characters in the jQuery selector: 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.
0

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.

2 Comments

This would work in some contexts, but I don't actually have the form to grab data from
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...
0

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 :)

4 Comments

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

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.