2014-01-14 39 views
0

我有一個php/Ajax/Jquery腳本,它將表單字段插入到MySQL中,並在您點擊提交時無需刷新即可更新頁面。我希望腳本提交四個表單字段,而不是一個。如何修改PHP/jquery/Ajax腳本有多個表單字段posst

我已經更新了數據庫表add_delete_record與另外3個領域:平衡,ACCOUNT_NUMBER,加上內容字段已經在那裏了。

下面可能是矯枉過正的代碼,因爲我只需要修改幾行,但我想這會回答所有問題。

這是PHP & html頁面:

<div class="content_wrapper"> 
<ul id="responds"> 
<?php 
//include db configuration file 
include_once("config.php"); 

//MySQL query 
$Result = mysql_query("SELECT id,content FROM add_delete_record"); 

//get all records from add_delete_record table 
while($row = mysql_fetch_array($Result)) 
{ 
echo '<li id="item_'.$row["id"].'">'; 
echo '<div class="del_wrapper"><a href="#" class="del_button" id="del-'.$row["id"].'">'; 
echo '<img src="images/icon_del.gif" border="0" />'; 
echo '</a></div>'; 
echo $row["content"].'</li>'; 
} 

//close db connection 
mysql_close($connecDB); 
?> 
</ul> 
<div class="form_style"> 
<textarea name="content_txt" id="contentText" cols="45" rows="5"></textarea> 
<button id="FormSubmit">Add record</button> 
</div> 
</div> 

這是它張貼到PHP:

<?php 
//include db configuration file 
include_once("config.php"); 

//check $_POST["content_txt"] is not empty 
if(isset($_POST["content_txt"]) && strlen($_POST["content_txt"])>0) 
{ 

    //sanitize post value, PHP filter FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH 
    $contentToSave = filter_var($_POST["content_txt"],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH); 

    // Insert sanitize string in record 
    if(mysql_query("INSERT INTO add_delete_record(content) VALUES('".$contentToSave."')")) 
    { 
     //Record is successfully inserted, respond to ajax request 
     $my_id = mysql_insert_id(); //Get ID of last inserted record from MySQL 
     echo '<li id="item_'.$my_id.'">'; 
     echo '<div class="del_wrapper"><a href="#" class="del_button" id="del-'.$my_id.'">'; 
     echo '<img src="images/icon_del.gif" border="0" />'; 
     echo '</a></div>'; 
     echo $contentToSave.'</li>'; 
     mysql_close($connecDB); 

    }else{ 
     //output error 

     //header('HTTP/1.1 500 '.mysql_error()); 
     header('HTTP/1.1 500 Looks like mysql error, could not insert record!'); 
     exit(); 
    } 

} 
elseif(isset($_POST["recordToDelete"]) && strlen($_POST["recordToDelete"])>0 && is_numeric($_POST["recordToDelete"])) 
{//do we have a delete request? $_POST["recordToDelete"] 

    //sanitize post value, PHP filter FILTER_SANITIZE_NUMBER_INT removes all characters except digits, plus and minus sign. 
    $idToDelete = filter_var($_POST["recordToDelete"],FILTER_SANITIZE_NUMBER_INT); 

    //try deleting record using the record ID we received from POST 
    if(!mysql_query("DELETE FROM add_delete_record WHERE id=".$idToDelete)) 
    { 
     //If mysql delete record was unsuccessful, output error 
     header('HTTP/1.1 500 Could not delete record!'); 
     exit(); 
    } 
    mysql_close($connecDB); 

}else{ 

    //Output error 
    header('HTTP/1.1 500 Error occurred, Could not process request!'); 
    exit(); 
} 
?> 

這是JQuery的

$(document).ready(function() { 
    //##### Add record when Add Record Button is clicked ######### 
    $("#FormSubmit").click(function (e) { 

     e.preventDefault(); 

     if($("#contentText").val()==="") //simple validation 
     { 
      alert("Please enter some text!"); 
      return false; 
     } 

     var myData = "content_txt="+ $("#contentText").val(); //post variables 

     jQuery.ajax({ 
      type: "POST", // HTTP method POST or GET 
      url: "response.php", //Where to make Ajax calls 
      dataType:"text", // Data type, HTML, json etc. 
      data:myData, //post variables 
      success:function(response){ 
      $("#responds").append(response); 
      $("#contentText").val(''); //empty text field after successful submission 
      }, 
      error:function (xhr, ajaxOptions, thrownError){ 
       alert(thrownError); //throw any errors 
      } 
     }); 
    }); 

    //##### Delete record when delete Button is clicked ######### 
    $("body").on("click", "#responds .del_button", function(e) { 
     e.preventDefault(); 
     var clickedID = this.id.split("-"); //Split string (Split works as PHP explode) 
     var DbNumberID = clickedID[1]; //and get number from array 
     var myData = 'recordToDelete='+ DbNumberID; //build a post data structure 

     jQuery.ajax({ 
      type: "POST", // HTTP method POST or GET 
      url: "response.php", //Where to make Ajax calls 
      dataType:"text", // Data type, HTML, json etc. 
      data:myData, //post variables 
      success:function(response){ 
      //on success, hide element user wants to delete. 
      $('#item_'+DbNumberID).fadeOut("slow"); 
      }, 
      error:function (xhr, ajaxOptions, thrownError){ 
       //On error, we alert user 
       alert(thrownError); 
      } 
     }); 
    }); 
}); 

這不是我的腳本所以我認爲我也應該給一個鏈接來信任它的作者: http://www.sanwebe.com/2012/04/ajax-add-delete-sql-records-jquery-php

回答

1

我不是PHP的專家,但這應該讓你通過:

首先改變主網頁上的表格區域:

<div class="form_style"> 
    <textarea name="content_txt" id="contentText" cols="45" rows="5"></textarea><br/> 
    <input type="text" id="balance" /><br/> 
    <input type="text" id="acctNum" /><br/> 
    <input type="text" id="monthly" /><br/> 
    <button id="FormSubmit">Add record</button> 
</div> 

那麼你myData的是這樣的:

var myData = { 
    content_txt: $("#contentText").val(), 
    balance: $("#balance").val(), 
    acctNum: $("#acctNum").val(), 
    monthly: $("#monthly").val() 
}; 

後來在Ajax響應:

$("#contentText").val(''); //empty text field after successful submission 
$("#balance").val(''); 
$("#acctNum").val(''); 
$("#monthly").val(''); 

終於PHP:

//sanitize post value, PHP filter FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH 
$content = filter_var($_POST['content_txt'],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH); 
$balance = filter_var($_POST['balance'],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH); 
$account = filter_var($_POST['acctNum'],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH); 
$monthly = filter_var($_POST['monthly'],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH); 


$qry= "INSERT INTO add_delete_record(content,balance,account,monthly) VALUES('".$content."','".$balance."','".$account."','".$monthly."')"; 


// Insert sanitize string in record 
if(mysql_query("INSERT INTO add_delete_record(content,balance,account,monthly) VALUES('".$content."','".$balance."','".$account."','".$monthly."')")) 
{ 
    //Record is successfully inserted, respond to ajax request 
    $my_id = mysql_insert_id(); //Get ID of last inserted record from MySQL 
    echo '<li id="item_'.$my_id.'">'; 
    echo '<div class="del_wrapper"><a href="#" class="del_button" id="del-'.$my_id.'">'; 
    echo '<img src="images/icon_del.gif" border="0" />'; 
    echo '</a></div>'; 
    echo $content.'</li>'; 
    mysql_close($connecDB); 

}else{ 
    //output error 

    //header('HTTP/1.1 500 '.mysql_error()); 
    header('HTTP/1.1 500 Looks like mysql error, could not insert record!'); 
    exit(); 
} 
+0

感謝您的回答!我會照顧我所承諾的。我也會刪除以前的評論。 –

+0

我注意到你將變量'$ contenttosave'的名稱改爲'$ content',這很好,我只是好奇你設置'$ balance $ account $ monthly'的其他變量是否也是這樣假設在echo語句中?如果我假設添加這行代碼的3行if(isset($ _ POST [「content_txt」])&& strlen($ _ POST [「content_txt」])> 0)'3表單字段,你沒有名字? –

+0

這將取決於您對這兩個問題的要求。第一個問題:是的,如果你想要顯示的刪除網格包含新的值。第二個問題:是的,如果你想要3個新領域需要一個價值。如果你沒有問題,他們是空的,你不需要做驗證。 – erikrunia

0

事情是這樣的:

var myData = "content_txt="+ $("#contentText").val()+"&other_value"+ $("#foo").val(); //post variables 

在php文件:

$other_value = $_POST['other_value']; 

UPDATE: 

balance, account_number and monthly 

JS: 

var myData = "content_txt="+ $("#contentText").val()+"&balance"+ $("#balance").val(); 
myData = myData + "&account_number="+$('#acnum').val()+"&monthly="+$('#month').val(); 


PHP: 

$content = filter_var($_POST['content_txt'],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH); 
$balance = filter_var($_POST['balance'],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH); 
$account = filter_var($_POST['account_num'],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH); 
$monthly = filter_var($_POST['monthly'],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH); 


$qry= "INSERT INTO add_delete_record(content,balance,account,monthly) VALUES('".$content."','".$balance."','".$account."','".$monthly."')"; 

if(mysql_query($qry)){ 
+0

你需要一個'&'在那裏 – cmorrissey

+0

哎呀,對不起,我錯 – Hackerman

+0

謝謝,不想我也需要修改PHP喜歡的東西' INSERT INTO add_delete_record('content','balance','account_number','monthly') –

0
var myData = { 
    content_txt: $("#contentText").val(), 
    other_var: $("#anotherField").val() 
}; 
jQuery.ajax({ 
    type: "POST", // HTTP method POST or GET 
    url: "response.php", //Where to make Ajax calls 
    dataType:"text", // Data type, HTML, json etc. 
    data:myData, //post variables 
    success:function(response){ 
     $("#responds").append(response); 
     $("#contentText").val(''); //empty text field after successful submission 
    }, 
    error:function (xhr, ajaxOptions, thrownError){ 
     alert(thrownError); //throw any errors 
    } 
}); 

這是送幾個字段(注意MYDATA的對象)一個簡單的方法。在PHP中,你可以檢索和保存這樣的新變量:

//check $_POST["content_txt"] is not empty 
if(isset($_POST["content_txt"]) && strlen($_POST["content_txt"])>0 && !empty($_POST["other_var"])) // !empty() checks that the variable is set and not empty 
{ 

    //sanitize post value, PHP filter FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH 
    $contentToSave = filter_var($_POST["content_txt"],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH); 
    $otherVarToSave = filter_var($_POST["other_var"],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH); 

    // Insert sanitize string in record 
    if(mysql_query("INSERT INTO add_delete_record(content, other) VALUES('".$contentToSave."', '".$otherVarToSave."')")) 
    { 
+0

難道我也不得不用表單域和表域數據更新php文件嗎? –

+0

用PHP示例更新了我的答案。 – positivew

+0

我只是看着它,你注意到了這一點:'注意myData對象'。我將它與我所擁有的進行了比較,除第一個變量不同外,它沒有任何區別。但是我看到你有'other_var:$(「#anotherField」)。val()'的額外變量示例我是否缺少與此不同的任何東西? –