J.K
J.K

Reputation: 67

failed to get status code from returned jqXHR of $.post call

I am using jQuery to post and insert a row of record to the end of table body by registering submit event listener. Here is fiddle: https://jsfiddle.net/8jew8kk7/4/

$("form").submit(function(event) {
  event.preventDefault()

  jx = $.post('data.asp', 'action=add&' + $(this).serialize())
  console.log("jx=" + jx.status)
  if (jx.status == 404) {
    alert("404 not found")
    return false
  }
  tdstring = "<tr><td>" + $("input[name='pkeyEmployeeID']").val() + "</td><td>" + $("input[name='strFirstName']").val() + "</td><td>" + $("input[name='strLastName']").val() + "</td><td>" + $("input[name='dtmBirthDate']").val() + "</td><td>" + $("input[name='strHomePhone']").val() + "</td>"
  delstring = '<td><button type="button" name="action" value="del" onclick="del(this)" fid="' + $("input[name='pkeyEmployeeID']").val() + '">add</button></td></tr>'
  $(this).find('tbody').append($(tdstring + delstring).hide().fadeIn('normal'))
})

But jx.status always undefined while running. When execute x=$.post('data.asp').status in Chrome console I can get the code exactly server returns. Is there any flaws with this snippet?

Upvotes: 1

Views: 126

Answers (2)

Quy Truong
Quy Truong

Reputation: 413

jQuery.post ( or $.post) method return a promise object. So if you want to get data from jqXHR, you have to get it from then(), always() or fail() method of promise.

jx = $.post('data.asp', 'action=add&' + $(this).serialize())
jx.always(function(data, textStatus, jqXHR){
    if(jqXHR.status == 200)
    //your code here
})

The jqXHR objects returned by $.ajax() as of jQuery 1.5 implement the Promise interface, giving them all the properties, methods, and behavior of a Promise (see Deferred object for more information). These methods take one or more function arguments that are called when the $.ajax() request terminates. This allows you to assign multiple callbacks on a single request, and even to assign callbacks after the request may have completed. (If the request is already complete, the callback is fired immediately.)

http://api.jquery.com/jQuery.ajax/#jqXHR

Demo: https://jsfiddle.net/8jew8kk7/14/

Upvotes: 1

Shubham Khatri
Shubham Khatri

Reputation: 281922

Since you code runs asynchronously console.log("jx= " + jx.status) runs before the ajax request completes and thus there is no such thing as statusfor jx object and thus it returns undefined. In order to use it , run it inside the .always() function. Also you need to use selector like this $("input[name='pkeyEmployeeID']") instead of $("input[name='pkeyEmployeeID'")

jx.always(function(){
    alert( jx.status)
    if (jx.status == 404) {
      alert("404 not found")
      return false
    }

  })

JSFIDDLE

Upvotes: 1

Related Questions