pepepapa82
pepepapa82

Reputation: 167

Posting incorrect json payload with Ajax/jquery

I'm trying to do something simple but I'm clearly missing something. I want to post data from a form into a web-service using json. Simple right?

I have my HTML

    <div id="addDiv">
    <form id="addItemForm">
        <fieldset>
            <label for="title">Title</label> 
            <input id="title" class="txt" type="text" name="title"/></BR>

            <label for="url">URL</label> 
            <input id="url" class="txt" type="text" name="url"/></BR>

            <label for="author">Author</label> 
            <input id="author" class="txt" type="text" name="author"/>

        </fieldset>
    </form>
</div>

Then in my js file I do:

              JSONdata = JSON.stringify($('#addItemForm').serialize());
          console.log("Form transformed to: " + JSONdata);

payload output(JSONdata):

Form transformed to: "title=tgtg&url=5rfrf&author=yhyhyyh"

My Ajax code just in case:

    $.ajax({
    type: "POST",
    url: serviceUrl,
    dataType: 'json',
    data: JSONdata,
    contentType : 'application/json',
            ............

So the problem I see is that the json string is not a valid one like [{ "title": "tgtg", "url": "5rfrf" .... },{...}]

Therefore, my service fails.
I've tried with a REST tester and the service has no problems, the problem is when i try to post via jquery.

I've also tried with serializeArray() but I get a different payload also incorrect:

[{"name":"title","value":"tgtg"},{"name":"url","value":"5rfrf"},...]

In other words, I can't find a way to create a proper json string to send via post.

thanks in advanced!

Upvotes: 0

Views: 2296

Answers (1)

Bergi
Bergi

Reputation: 665364

You don't want to use serialize, but the serializeArray method. If you need it in an object, you then still can make the name-value pairs properties of an object:

var res = {},
    arr = $('#addItemForm').serializeArray();
for (var i=0; i<arr.length; i++)
    res[arr[i].name] = arr[i].value;

Upvotes: 1

Related Questions