Upasana Sengupta
Upasana Sengupta

Reputation: 77

post from html form to api json jquery

I have to post data from an html form to an api. I have the following code:

<form name="newAppform">
<input type="text" name="appname" placeholder="App Name" id="appname"><br>
<input type="radio" name="platform" value="iOS"> iOS 
<input type="radio" name="platform" value="Android"> Android<br>
<input type="submit" value="submit" name="submit" id="submit"></form>

and the jQuery is:

var a = 1; //var x = $('#appname').val(); 
$('#submit').click(function(){
//alert($('#appname').val());       
$.ajax({
    type: 'POST',
    url: 'https://service.../.../createApp',
    contentType: "application/json",
    data: JSON.stringify({"account_id" : a, "app_name" : $('#appname').val(), "app_platform" : $("[name='platform']").val()}),
    success: function() {
        alert("Complete!");
    },
    error: function(e) {
        console.log(e);
        alert("Something went wrong.");
        }
    }); 
});

I am using a valid for posting url, which I have replaced with ellipsis here. I am getting the alert 'Something went wrong.'. The error that is getting logged on the console is

{readyState: 0, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}.

What is wrong? Please note that the same posting is working with the same code and I am getting the success message if I am not taking it from form input. Conversely, the form input reading is working separately apart from posting. If I uncomment 'alert' it is being able to display the value I put in the input text field. Please also note that if I uncomment and use the variable x as the value for the key "appname", it is still not working. Same error. But if I hardcode x outside as var x = 'abc', I get success.

Upvotes: 0

Views: 229

Answers (1)

r3dst0rm
r3dst0rm

Reputation: 1926

Just a little hint: Instead of taking all your input fields manually (which can get very nasty). You could make use of the serializeArray function.

function serializeForm(_formId){
    var oJson = {};
    var oFrm = $(_formId).serializeArray();
    for (var i = 0; i < oFrm.length; i++) {
        var entry = oFrm[i];
        oJson[entry.name] = entry.value;
    }

    return oJson;
}

This will generate you a proper JSON without much effort (in case you are about to POST more data using a form).

And to POST against the API with a given URL you could use:

var oJson = serializeForm(#idOfForm);
$.ajax({
        type: "POST",
        url: 'YOUR_URL',
        data: oJson,
        success: function (data) {
          // success
        },
        error: function (jqXHR, textStatus, errorThrown) {
            // Display error message
            console.error(errorThrown);
        },
        dataType: "json"
    });

Keep in mind, always set your error function to somewhat more helpful than you did. The code above logs the errorThrown parameter to the error console

EDIT:

I checked your URL and sent some test requests. If the AJAX call tells us something went wrong the server sends a HTTP 500 Internal Server Error which tells us, that we are sending some wrong data. I took the URL you provided at the beginning and filled in some dummy data.

I came up with the conclusion, that you are sending some wrong stuff:

  • Your original code is correct. Just remove the contentType attribute hence the server expects you to send the contentType application/x-www-form-urlencoded; charset=UTF-8 which is jQuery ajax standard

  • My approach is also working (as provided in the code above - but thats not the point) - it just lacks of correct input names try to replace the HTML to following:

    <form id="test" name="newAppform"> <input type="text" name="account_id" placeholder="Account Id" id="accId"><br> <input type="text" name="app_name" placeholder="App Name" id="appname"><br> <input type="radio" name="app_platform" value="iOS"> iOS <input type="radio" name="app_platform" value="Android"> Android<br> <input type="submit" value="submit" name="submit" id="submit"> </form>

What's different?

platform got renamed to app_platform I also introduced an account_id input just for testing purposes (make sure you provide the correct account_id if sending the request otherwise you will also receive an internal server error.

appname got renamed to app_name

Upvotes: 1

Related Questions