2013-05-31 32 views
-1

一個PHP函數,下面是我的html文件的頭部,在腳​​本標籤:如何調用使用JQuery/AJAX

$(document).ready(function(){ 
       $("#Submit").click(function(){ 
        var name = $("#name").val(); 
        $.ajax({ 
         url : "function.php", 
         type : "POST", 
         data : {"firstname":name}, 
         success : function(n){ 
          //more code here       } 
        }); 
       }); 
} 

這是HTML表單:

<div class="myForm"> 
       <input name="name" id="name" value="name" onfocus="if (this.value == 'Name') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Name';}" type="text" /> 
       <input type="button" value="Submit" id="Submit"> 
      </div> 

這裏我的PHP,保存在一個名爲function.php文件:

<?php 
$con=mysqli_connect("test", "", "", "test"); 
// Check connection 
$name = $_POST['firstname']; 
if (mysqli_connect_errno()) 
    { 
    echo "Failed to connect to MySQL: " . mysqli_connect_error(); 
    } 

mysqli_query($con,"INSERT INTO customers (name) VALUES (" + $name + ")"); 

mysqli_close($con); 
?> 

功能需要一個年齡打電話,並沒有什麼保存在我的數據庫。我是JQuery/Ajax的新手。我在這裏有什麼調試選項?可能是什麼問題?

+2

您正在發佈名爲'firstname'的變量並檢索名爲'name'的變量。他們應該匹配。你也可以嘗試'mysqli_query(...)或死(mysqli_error())'來查看任何mysql錯誤。 – showdev

+0

格式化你的數據:'data:{firstname:name},' – tymeJV

+0

@showdev我現在已經做了這個編輯。該函數執行速度快得多,但我的表中仍然沒有數據:( –

回答

2

試試看看這個代碼。我編輯了代碼並添加了PDO,這是連接數據庫的新方法。 這更安全並自動轉義數據。

你的php中有很多語法錯誤。像php中的字符串追加操作符是.而不是+

<?php 
$name = $_POST['firstname']; 
try { 
    // Prepare our connection string and execute it 
    $con = new PDO("mysql:host=".HOST.";dbname=".DBNAME, USER, PASS); 
} catch(PDOException $e) { 
    // Connection error jumps here 
    echo $e->getMessage(); 
} 
// Define our query here 
$query = $con->prepare("INSERT INTO customers (name) VALUES (:name)"); 
// Define our query data here. the name here maps to the :name in the query. 
$data = array("name" => $name); 
try { 
    // Try to execute our query 
    $query->execute($data); 
} catch(PDOException $e) { 
    // Insert error jumps here 
    echo $e->getMessage(); 
} 
?> 

只需放入您的主機,數據庫名稱,用戶並傳入代碼中提到的地方,您就可以輕鬆前往。

要在您的Firefox和HTML頁面上調試php代碼安裝Firebug,請右鍵單擊頁面並選擇Inspect element with firebug以打開Firebug。打開Net面板,在那裏你可以看到要求。看到迴應,你會看到任何可能的錯誤在您的PHP頁面。

祝你好運!