[英]Execute php file with Ajax
當我單擊“立即注冊”按鈕時,我想執行“input.php”,其中我有將數據插入數據庫並顯示成功消息的代碼。 我不想離開當前頁面。
<input type="button" id="confirm" value="Register Now" class="button">
<script type="text/javascript">
$(document).ready(function() {
$("#confirm").click(function() {
<?php
include 'input.php';
?>
alert ("data Added successfully.");
});
});
</script>
我的代碼給了我“數據添加成功”的消息,但 PHP 文件沒有執行,也沒有數據添加到數據庫中。 所有必要的數據都在會話變量中。
建議您嘗試以下操作。 您不應該嘗試在 jQuery 腳本中執行 PHP。 執行 AJAX 調用並傳遞數據並在 PHP 中處理它,而不是依賴於會話變量。 例如:
<script type="text/javascript">
$(document).ready(function () {
$("#confirm").click(function () {
$.ajax({
type: "POST",
url: "index.php",
data: {
firstname: "Bob",
lastname: "Jones"
}
})
.done(function (msg) {
alert("Data Saved: " + msg);
});
});
});
</script>
其中名字,姓氏將是您的正常會話數據。
您可以在jQuery API 文檔 中了解有關 jQuery.ajax() 函數的更多信息。
要從 javascript 執行 Php 腳本,您必須使用 Ajax。
以下代碼:
$("#confirm").click(function() {
<?php
include 'input.php';
?>
alert ("data Added successfully.");
});
不管用
您需要使用 AJAX。 Ajax 是從頁面內部從 javascript 調用 php 文件的概念。 然后,您將在變量中獲取 php 頁面輸出,您可以選擇是否顯示它。 這種技術的一個例子是顯示更多 Facebook 的帖子。 這可以使用 jQuery 輕松完成。
$.post( PHP_FILE, { field1: 'value', field2: 'value'}).done(function( data )
{alert("this function will be run when the request is over and the variable data
will have the output : " + data);});
你可以通過ajax post方法做到這一點..
$.ready(function(){
$("#confirm").click(function() {
$.ajax({
type: "POST",
url: "give url to the input.php file ",
data:,
success:function(data)
{
alert('data');// data is the return value from input.php
}
});
});
});
嘗試這個:
<input type="button" id="confirm" value="Register Now" class="button">
<script type="text/javascript">
$(document).ready(function() {
$("#confirm").click(function() {
$.get('input.php').
success(function(){
alert ("data Added successfully.");
});
});
});
</script>
我不太確定你在那里嘗試過什么。 無論如何,這里有一段 js 應該為你做(我很確定在新的 jQuery 版本中有一個更好的方法來做到這一點):
$.ajax({
url: "input.php",
success:
function(data)
{
// here, for example, you load the data received from input.php into
// an html element with id #content and show an alert message
$("#content").html(data);
alert("Success")
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.