Reputation: 67
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
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.)
Demo: https://jsfiddle.net/8jew8kk7/14/
Upvotes: 1
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
}
})
Upvotes: 1