1

I am a beginner in JQuery and I am trying to do a very simple thing: get a html form, convert it to JSON, send it to my API and display the result.

I read multiple SO post about serializing forms and arrays into JSON but I am unable to get it work(I either get 400 - Bad Request response because my JSON is not in a correct format or 415 status for some reason).

This is the Html form:

<form id="imageUploadForm">
        <fieldset>
        <legend>Upload new image</legend>
        <p>
                <label for="imageUrl">Image URL:</label>
                <input id="imageUrl" type="text" name="imageUrl" />
        </p>
        <p>
                <label for="tag">Tag:</label>
                <input id="tag" type="text" name="tag" />
        </p>
        <p>
                <input id="uploadButton" type="button" value="Submit" />
        </p>
        </fieldset>
</form>

<div id="uploadResponse"></div>

And script handling the request:

$(document).ready(function() {

  //Stops the submit request
  $("#imageUploadForm").submit(function(e) {
    e.preventDefault();
  });

  //checks for the button click event
  $("#uploadButton").click(function(e) {

        //get the form data and then serialize that
        var json = JSON.parse(JSON.stringify(jQuery('#imageUploadForm').serializeArray()));

        $.ajax({
        type: "POST",
        url: "<url>",
        data: json,
        crossDomain: true,
        dataType: "text/plain",

        //if received a response from the server
        success: function(response) {
                $("#uploadResponse").append(response);
        },

        });
  });

});

Could someone point me to the right direction? The goal is to send the following JSON to the api:

{
   "imageUrl" : "...",
   "tag" : "..."
}
3
  • just try var json=$('#imageUploadForm').serialize() Commented Mar 11, 2016 at 9:40
  • Maybe this will help contentType: "application/json; charset=utf-8" Commented Mar 11, 2016 at 9:42
  • Try to use solution from this answer - stackoverflow.com/a/1186309/6014444 Commented Mar 11, 2016 at 9:48

6 Answers 6

2

Can you check following code and fiddle link,

$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
    if (o[this.name] !== undefined) {
        if (!o[this.name].push) {
            o[this.name] = [o[this.name]];
        }
        o[this.name].push(this.value || '');
    } else {
        o[this.name] = this.value || '';
    }
});
return o;
};

$(function() {
$("#imageUploadForm").submit(function(e) {
e.preventDefault();
});
$('#uploadButton').click(function() {
var jsonText = JSON.stringify($('form').serializeObject());
    $('#result').text(JSON.stringify($('form').serializeObject()));
     $.ajax({
    type: "POST",
    url: "<url>",
    data: jsonText,
    crossDomain: true,
    dataType: "text/plain",

    //if received a response from the server
    success: function(response) {
            $("#uploadResponse").append(response);
    },

    });
});
});


http://jsfiddle.net/sxGtM/7142/

Hope it may help you.

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

1 Comment

This is the only approach that worked so far. Although I imagined that such a simple thing as sending a serialized form as JSON should not require so much boiler plate code
0

You don't have to parse the stringified JSON, otherwise you send a JS object. You have to send a string rappresenting a JSON.

var json = JSON.stringify(jQuery('#imageUploadForm').serializeArray());

Comments

0

Try changing the content type to contentType: "application/json; charset=utf-8", and if your api is returning json set dataType: "json".

What is your console reporting, if anything?

Comments

0

just use var json=$('#imageUploadForm').serialize()

according to your form in question you dont need serializeArray and change content type contentType:"application/json; charset=utf-8",

check this SO link

1 Comment

I tried console.log(json) and it produces url-encoded content: imageUrl=...&tag=... and thus results in Bad Request
0
    var imagedataUrl = $("#imageUrl").val();
    var tagdataUrl = $("#tag").val();

    $.ajax({
    type: "POST",
    url: "<url>",
     dataType: "json",
    data: { imageUrl: imagedataUrl  , tag: tagdataUrl },
    contentType: "application/json; charset=utf-8;",
    crossDomain: true,


    //if received a response from the server
    success: function(response) {
            $("#uploadResponse").append(response);
    },

    });

3 Comments

Your code produces the following payload: imageUrl=...&tag=... It somehow does not interpret those data as JSON
Use data:JSON.stringify(object)
Could you provided a working example, please? This only results in 415
-1

You should mention your content type which is sent to server

varContentType="application/json; charset=utf-8";

$.ajax({
    type: varType, //GET or POST or PUT or DELETE verb
    url: varUrl, // Location of the service 
    data: varData, //Data sent to server
    contentType: varContentType, // content type sent to server
    dataType: varDataType, //Expected data format from server
    processData: false,
    crossDomain: true,
});

Comments

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.