0

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.

5
  • 1
    You dont need to stringify the data property Commented Aug 16, 2017 at 8:30
  • 1
    “The error that is getting logged on the console is” ... not actually an “error”, but the jqXHR object itself. Commented Aug 16, 2017 at 8:31
  • Also check in your response, the server will be returning somekind of an error. Commented Aug 16, 2017 at 8:31
  • Your error handler logic isn't very helpful - could you check the network tab of the console to see what the response from the request is. Commented Aug 16, 2017 at 8:31
  • @ CBroe , I know. I felt so too. I felt that was the syntax to log errors so that is what I used. Commented Aug 16, 2017 at 8:45

1 Answer 1

1

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

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

4 Comments

when I was fiddling with the code I had used var obj = $('form').serializeJSON(); and $.ajax({ data: JSON.stringify(obj), ... But that hadn't worked. Now, I'll try this, thank you.
Changing the error codeblock to what you suggested is not consoling anything somehow.
Tried this solution. Still the same alert message Something went wrong. And nothing is being consoled now.
Please try to set a breakpoint to the console.error statement. Then check which values each parameters have.

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.