I have noticed that I'm having problems when I'm using AJAX in jQuery inside a .each() loop. Only the first record in my database are being updated when the script executes.
Here's my script:
function save(){
var _userTypeId;
var _userTypeName;
var _isDeleted;
var request;
$("tr.recUserType").each(function(){
$this = $(this);
_userTypeId = $this.find("#userTypeId").html();
_userTypeName = $this.find("#userTypeName").val();
_isDeleted = $this.find("#isDeleted").val();
request = $.ajax({
url: "save.php",
type: "POST",
data: {userTypeId: _userTypeId, userTypeName: _userTypeName, isDeleted: _isDeleted}
});
});
request.done(function(){
document.location.reload();
});
request.fail(function(){
alert("Request Failed!");
});
}
And the contents of save.php:
<?php
include_once "globals.php";
dbConnect();
$isExisting = mysql_query("SELECT COUNT(userTypeId) AS userCount FROM userType WHERE userTypeId='".$_POST['userTypeId']."';");
$result = mysql_fetch_array($isExisting);
//original: if(!$result['userCount'] = 0) <-- This was a logical error
if($result['userCount'] != 0)
mysql_query("UPDATE userType SET userTypeName='".$_POST['userTypeName']."', isDeleted='".$_POST['isDeleted']."' WHERE userTypeId='".$_POST['userTypeId']."';");
else
mysql_query("INSERT INTO userType VALUES('', '".$_POST['userTypeName']."', '".$_POST['isDeleted']."');");
echo mysql_error();
dbClose();
?>
I have read that I have the option to use synchronous instead of asynchronous, but I have also read it is not a good practice.
So how do I actually get this done asynchronously and fix the problem?
userTypeId-_userTypeId = $this.find("#userTypeId").html();for each loop so you are only going to update 1 row.POST userTypeName=Lolinjection&isDeleted=1&userTypeId=' OR 1 = 1; --and explain to you how SQL injection is bad. Use a library that actually helps protect against this, or at the very least sanitize your inputs.<tr>with the id ofuserTypeId(stackoverflow.com/a/7017308/689579), I would not recommend it. Using the same id multiple times in a document, even if in different<tr>tags, is invalid html. w3.org/TR/html401/struct/global.html#h-7.5.2 / w3.org/TR/html5/dom.html#the-id-attributeThe id attribute assigns a **unique** identifier to an element/The id attribute specifies its element's unique identifier (ID). These would be better as classes.