2016-01-18 42 views
0

當我通過http POST請求發送表單值時,我想要做的是返回「addTemplate.php」的echo值。但是,當我發送請求時,絕對沒有任何反應。認爲我的ajax有問題嗎?

我該怎麼辦?

這裏是我的JS

$(document).ready(function() { 
    $("#sendTemplate").on("submit", function(event) { 
     var template = $("#template").val(); 
     event.preventDefault(); 
     $.ajax({method: "POST", url: "addTemplate.php", data: template, success: function(result) { 
      alert(result); 
     }); 
    }); 
}); 

這裏是我的html

<!DOCTYPE html> 
<html> 
    <head> 
     <title>Admin</title> 
     <link type="text/css" rel="stylesheet" href="stylesheet.css"> 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> 
     <script src="adminscript.js"></script> 
    </head> 
    <body> 
     <h1>Admin/Developer page</h1> 
     <form id="sendTemplate"> 
      <p>Enter a new template for the server: (Enter #word to enter a placeholder for words)</p><input type="text" name="template" id="template"> 
      <input type="submit" name="submit"> 
     </form> 
     <div id='success'></div> 
     <br><br><br><br> 
     <form action="turing.html"> 
      <button type="submit">Home</button> 
     </form> 
    </body> 
</html> 

這裏是我的PHP

$template = $_POST["template"]; 
if(strlen($template) <= 100 && strpos($template, "#word")) { 
    file_put_contents("templates.txt", "\r\n" . $template, FILE_APPEND); 
    header("Location: http://community.dur.ac.uk/h.j.g.baum/admin.html"); 
    echo "True"; 
} 
else { 
    echo "False"; 
} 

這有什麼錯我的代碼(最有可能在JavaScript),以及如何我可以改善它嗎?

感謝

+1

在您的ajax中發送的數據需要是ob ject或序列化的字符串。我建議使用'$(this).serialize()' – CodeGodie

+0

現在有很多選項OP – devpro

回答

0

我想你錯過了在阿賈克斯成功函數右大

$(document).ready(function() { 
    $("#sendTemplate").on("submit", function(event) { 
     var template = $("#template").val(); 
     event.preventDefault(); 
     $.ajax({method: "POST", url: "addTemplate.php", data: template, success: function(result) { 
      alert(result); 
     }}); 
    }); 
}); 
0

ID做到這一點:

$(document).ready(function() { 
      $("#sendTemplate").on("submit", function() { 
       $.ajax({ 
        method: "POST", 
        url: "addTemplate.php", 
        data: $(this).serialize(), 
        success: function (result) { 
         alert(result); 
        }); 
       return false; 
      }); 
     }); 
1

更換AJAX數據:

data: template, 

With:

data: "template="+template, 

問題:

您正在使用$ _ POST [ '模板']用於獲取值和阿賈克斯的數據並沒有規定。

0

只要改變你的JS來

$(document).ready(function() { 
$("#sendTemplate").on("submit", function(event) { 
    var template = $("#sendTemplate").serialize(); 

    $.ajax({method: "POST", url: "test.php", data: template, success: function(result) { 
     alert(result); 
    }}); 
    event.preventDefault(); 
}); 

而且

<form id="sendTemplate"> 

<form id="sendTemplate" method="POST"> 

這是爲了獲取表單數據,並把它傳遞給你的PHP腳本

正道