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" : "..."
}
Smajl
  • 7,555
  • 29
  • 108
  • 179

6 Answers6

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.

getty
  • 135
  • 11
  • 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 – Smajl Mar 11 '16 at 10:00
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());
Denis Frezzato
  • 957
  • 6
  • 15
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?

Tech Savant
  • 3,686
  • 1
  • 19
  • 39
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

Community
  • 1
  • 1
Pavan Teja
  • 3,192
  • 1
  • 15
  • 22
  • I tried console.log(json) and it produces url-encoded content: imageUrl=...&tag=... and thus results in Bad Request – Smajl Mar 11 '16 at 09:56
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);
    },

    });
DAre G
  • 177
  • 10
-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,
});
Prasad Khode
  • 6,602
  • 11
  • 44
  • 59