使用ajax在表中多次插入数据

时间:2013-11-21 09:01:22

标签: php jquery mysql sql ajax

我正在使用这个AJAX在表中插入数据,但问题是数据插入多次。实际上我创建了一个带登录的表单,如果登录正确则数据将插入到数据库中。问题是如果我们提供错误的用户名或传递多次,然后数据也被多次插入。如果我们输入用户名传递3次错误,那么在我们给出正确的登录后数据被插入3次。我是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>

这是我的PHP代码(我认为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>';  */

    }

?>

1 个答案:

答案 0 :(得分:2)

将您的代码更改为:

<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>