Data is being inserted multiple times in table using ajax Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Data is being inserted multiple times in table using ajax without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I am using this AJAX for inserting data in table but problem is data is inserting multiple times.Actually I have created one form with login,if login is correct then data will insert into database.Problem is if we give wrong username or pass multiple time then data is also inserted multiple times.ex if we enter username pass 3 times wrong then data is inserted 3 times after we give correct login.I am new in AJAX.

<script>
$(document).ready(function()
{


$("#simple-post").click(function()
{
    $("#ajaxform").submit(function(e)
    {
        $("#simple-msg").html("<img src='loading.gif'/>");
        var postData ="";
        postData = $(this).serializeArray();
        var formURL = $(this).attr("action");
        alert(postData);
        $.ajax(
        {
            url : formURL,
            type: "POST",
            data : postData,
            success:function(data, textStatus, jqXHR) 
            {

            window.location = "Dealer/PostPropertyAdvanceDetails.php?sdfdsf=sf";


            },
            error: function(jqXHR, textStatus, errorThrown) 
            {
                $("#simple-msg").html('<pre><code class="prettyprint">AJAX Request Failed<br/> textStatus='+textStatus+', errorThrown='+errorThrown+'</code></pre>');
            }
        });
        e.preventDefault(); //STOP default action
    });

    $("#ajaxform").submit(); //SUBMIT FORM
});

});
</script>

Here’s my php code (I think there is no problem with php) :

<?php
ob_start();

session_start(); 

include 'CUserDB.php';





include 'config.php';



$myusername=$_POST['txtusername']; 
$mypassword=$_POST['txtpassword']; 
//$typ= $_POST['type'];


$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
//$typ = stripslashes($typ);    
$myusername = mysql_real_escape_string($myusername);
$mypassword=mysql_real_escape_string($mypassword);


$qry = "SELECT UserName,Type_user FROM login WHERE UserName = '".$myusername."' AND password = '".$mypassword."' ";





$result = mysql_query($qry) or die ("Query failed");

$UserData = mysql_fetch_array($result);




    if($UserData['UserName'] != '')

        {
            session_start(); 

             $_SESSION['UserId'] = $myusername;

        $typ = $UserData['Type_user'];



    if   ( $typ == "Dealer" || $typ == "Individual" || $typ == "Builder")
    { 




         //save details

$PostPropertyFor=$_POST['rdoSalesAndRent'];



$PropertyType=$_POST['propertyType'];
$TransactionType = "";
if (isset($_POST['rdoNewPropResale']))
 {

     $TransactionType =$_POST['rdoNewPropResale'];
 }

$City=$_POST['cmbCity'];
$Location=$_POST['cmbLocation'];

$NameofProject=$_POST['txtNameOfProject'];

$SelectProject=$_POST['rdoProjAndSociety'];
$BedRoom=$_POST['Bedrooms'];
$BathRoom=$_POST['bathrooms'];
$Furnished=$_POST['furnished'];

if (isset($_POST['txtCoveredArea']))
 {
$CoveredArea=$_POST['txtCoveredArea'];
$CoveredAreaSize=$_POST['coveredAreasize'];
$FinalCoveredArea = $CoveredArea.".".$CoveredAreaSize;
$FinalCoveredArea = trim($FinalCoveredArea);
 };



if (isset($_POST['txtPlotNland']))
 {
$PlotArea=$_POST['txtPlotNland'];
$PlotAreaSize=$_POST['plotareaSize'];
$FinalPlotArea = $PlotArea.".". $PlotAreaSize;
$FinalPlotArea = trim($FinalPlotArea);
 };


$FinalCarpetArea = "";
if (isset($_POST['txtCarpet']))
 {
$CarpetArea=$_POST['txtCarpet'];
$CarpetAreaSize=$_POST['carpetareaSize'];
$FinalCarpetArea = $CarpetArea.".".$CarpetAreaSize;
$FinalCarpetArea = trim($FinalCarpetArea);
 };

$TotalPrice=$_POST['txtTotalPrice'];

$FinalPerUnitPrice = "";
if (isset($_POST['txtPerUnit']))
 {
  $PerUnitPrice=$_POST['txtPerUnit'];
$PerUnitSize=$_POST['perunitsize'];
$FinalPerUnitPrice = $PerUnitPrice .".". $PerUnitSize;
$FinalPerUnitPrice = trim($FinalPerUnitPrice);
 };

$DisplayPriceToUser ="";
 if (isset($_POST['rdoYesorNo']))
 {

    $DisplayPriceToUser=$_POST['rdoYesorNo']; 
    $DisplayPriceToUser=trim($DisplayPriceToUser);
 }

$FloorNo=$_POST['floorNumber'];
$TotalFloors=$_POST['txtTotalFloors'];
$Description=$_POST['txtCompDesc'];

$PossessionStatus ="";
 if (isset($_POST['rdoUnderConstrucionNready']))
 {
     $PossessionStatus=$_POST['rdoUnderConstrucionNready'];
 }

if(isset($_POST['txtMonthlyRent']))
 {
$MonthlyRent=$_POST['txtMonthlyRent'];
$MonthlyRent=trim($MonthlyRent);
 }

$AvailableFrom = "";
if(isset($_POST['rdoAvailableFor']))
 {
  $AvailableFrom=$_POST['rdoAvailableFor'];
 $AvailableFrom=trim($AvailableFrom);

 }



$PostPropertyFor=trim($PostPropertyFor);
$PropertyType=trim($PropertyType);
$TransactionType =trim($TransactionType);
$City=trim($City);
$Location=trim($Location);
$NameofProject=trim($NameofProject);
$SelectProject=trim($SelectProject);
$BedRoom=trim($BedRoom);
$BathRoom=trim($BathRoom);
$Furnished=trim($Furnished);




$TotalPrice=trim($TotalPrice);



$FloorNo=trim($FloorNo);
$TotalFloors=trim($TotalFloors);
$Description=trim($Description);
$PossessionStatus=trim($PossessionStatus);



$Username = $_SESSION['UserId'];


   $str ="Call sp_SaveDealerPostProperty('".$PostPropertyFor."','".$PropertyType."','".$TransactionType."','".$City."','".$Location."','".$NameofProject."','".$SelectProject."','".$BedRoom."','".$BathRoom."','".$Furnished."','".$FinalCoveredArea."','".$FinalPlotArea."','".$FinalCarpetArea."','".$TotalPrice."','".$FinalPerUnitPrice."','".$DisplayPriceToUser."','".$FloorNo."','".$TotalFloors."','".$Description."','".$PossessionStatus."','".$MonthlyRent."','".$AvailableFrom."','".$Username."')";

           if(!mysql_query($str))
{ 
 die('Error:'.mysql_error()); 
 } 
  else 
 { 

     $query="SELECT MAX(property_Id) as id FROM dealerpostproperty WHERE UserName ='".$Username."'"; 
$result = mysql_query($query) or die(); 
$row = mysql_fetch_object($result);
$LastId = $row->id; 



             $_SESSION['LastId'] = $LastId;



//make directory for property with property id if not exist

$uploaded_files_location = "propertyImages/".$_SESSION['LastId']."/";
echo $uploaded_files_location;
  if (file_exists($uploaded_files_location))
   {
} 
else 
{
    mkdir($uploaded_files_location);
}

  }






}   
    }

   else 

    { 
    header('HTTP/1.0 403 Forbidden');
echo " wrong username or password";
/*          echo '<script>';
echo 'alert("Wrong Username or Password!");';
echo 'location.href="index.php"';
echo '</script>';  */

    }

?>

Answer

Change you code to:

<script>
$(document).ready(function()
{
$("#ajaxform").submit(function(e)
{
    $("#simple-msg").html("<img src='loading.gif'/>");
    var postData ="";
    postData = $(this).serializeArray();
    var formURL = $(this).attr("action");
    alert(postData);
    $.ajax(
    {
        url : formURL,
        type: "POST",
        data : postData,
        success:function(data, textStatus, jqXHR) 
        {

        window.location = "Dealer/PostPropertyAdvanceDetails.php?sdfdsf=sf";


        },
        error: function(jqXHR, textStatus, errorThrown) 
        {
            $("#simple-msg").html('<pre><code class="prettyprint">AJAX Request Failed<br/> textStatus='+textStatus+', errorThrown='+errorThrown+'</code></pre>');
        }
    });
    e.preventDefault(); //STOP default action
});

$("#simple-post").click(function()
{
    $("#ajaxform").submit(); //SUBMIT FORM
});

});
</script>
We are here to answer your question about Data is being inserted multiple times in table using ajax - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji