简体   繁体   中英

How to update MySQL table data in PHP without page refresh?

I am trying to update MySQL table field using JQuery, but the code I wrote is not working with JQuery and if I run this code without JQuery it works.

assignlead.php

<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'root';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
  die('Could not connect: ' . mysql_error());
}
$count=$_POST["id"];
$usersCount = count($count);
for($i=0;$i<$usersCount;$i++) {
  $eid=$_POST["eid"][$i];
  $id=$_POST["id"][$i];

  $sql = "UPDATE clientreg
          SET eid='" .$eid. "'
          WHERE id='" .$id. "'";

  mysql_select_db('helixcrm');
  $retval = mysql_query( $sql, $conn );
}
if(! $retval )
{
  die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully\n";
mysql_close($conn);
?>
<?php
$rowCount = count($_POST["users"]);
for($i=0;$i<$rowCount;$i++) {
$result = mysql_query("SELECT * FROM clientreg WHERE Id='" . $_POST["users"][$i] . "'");
$row[$i]= mysql_fetch_array($result);
$id=$row[$i]['id'];
?>
<input type="hidden" name="id[]" class="txtField" value="<?php echo $row[$i]['id']; ?>"></td>
<?php
$rowCoun = count($_POST["eid"]);
for($j=0;$j<$rowCoun;$j++) {
  $result = mysql_query("SELECT * FROM login WHERE eid='" . $_POST["eid"][$j] . "'");
  $row[$j]= mysql_fetch_array($result);
  $eid=$row[$j]['eid'];
?>
<input type="hidden" name="eid[]" class="txtField" value="<?php echo $row[$j]['eid']; ?>">
<?php
}
}
?>

my JQuery

<script>
$(document).ready(function(){
    $('#myForm').submit(function(){
        $.ajax({
            url : 'assignlead.php',
            data : $(this).serialize(),
            type : 'POST',
            success : function(data){
                console.log(data);
                $("#success").show().fadeOut(5000);
            },
            error:function(data){
                $("#error").show().fadeOut(5000);
            }
        });
        // !important for ajax form submit
        return false;
    });
});
</script>

I do not know where I am wrong. Please help me to short out my problem.

$(this) is not referring to the form. do it like that

$('#myForm').submit(function(){
    var self = $(this);
    $.ajax({
        url : 'assignlead.php',
        data : self.serialize(), // using this here will refer to Ajax jQuery object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM