Jeya Kumar
Jeya Kumar

Reputation: 1102

Ajax-POST succeeds only Async is false

I am trying POST ajax call to my back end. It is working fine if I set async: false, but if I remove that it is failing and return undefined in error section

 $.ajax({
        type: "POST",
        enctype: 'multipart/form-data',
        url: "http://localhost:8000/student/queue/create",
        data: data,
        processData: false,
        contentType: false,
        cache: false,
        timeout: 600000,
        success: function (data) {
            console.log("SUCCESS : ", data);

        },
        error: function (e) {
            console.log("ERROR : ", e.responseText);
            alert("ERROR : "+  e.responseText);

        }
    });

Calling my ajax function from button onclick

<button type="submit" id="submit-createqueue" class="btn feedback glass" onclick="sendformDataToBackend()">Submit</button>

I tried Ajax Call returns undefined when async is true but that also not working

function Call(data) {

    return $.ajax({
        url: "http://localhost:8000/student/queue/create",
        type: "POST",
        enctype: 'multipart/form-data',
        data: data,
        processData: false,
        contentType: false,
        cache: false,
        timeout: 600000,

        error: function (e) {
        console.log("ERROR : ", e.responseText);
        alert("ERROR : "+  e.responseText);
        }

    });
}

Call(data).then(function(data) {
    console.log(data);
    alert("test")
});

Upvotes: 2

Views: 734

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337666

You need to stop the form submission that's also happening when you click the submit button. It works with async: false because it blocks processing while the request is in process - which is exactly why you shouldn't use it.

I'd also strongly suggest you stop using on* event attributes. Use unobtrusive event handlers instead.

As you're using jQuery, you can achieve both of those using this code:

$('#yourFormElement').on('submit', function(e) {
  e.preventDefault();

  var data = // your logic to get form data here...

  $.ajax({
    type: "POST",
    enctype: 'multipart/form-data',
    url: "http://localhost:8000/student/queue/create",
    data: data,
    processData: false,
    contentType: false,
    cache: false,
    timeout: 600000,
    success: function (data) {
      console.log("SUCCESS : ", data);
    },
    error: function (e) {
      console.log("ERROR : ", e.responseText);
      alert("ERROR : " +  e.responseText);
    }
  });
});

Upvotes: 2

user5403939
user5403939

Reputation:

Please try with input type button replaced with submit button

Upvotes: 0

Related Questions