2014-06-25 131 views
0

當我點擊「立即註冊」按鈕時,我想要執行'input.php',其中有代碼將我的數據插入數據庫並顯示成功消息。我不想離開當前頁面。使用Ajax執行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文件沒有執行,沒有數據添加到數據庫。所有必要的數據都在會話變量中。

+0

你使用任何框架? – AkshayP

+0

不錯的主意,但你不能那樣做。看看使用jquery並查找ajax調用。 – RiggsFolly

+0

不可能只有Ajax是一種解決方案,PHP總是先執行然後js – Ashish

回答

2

建議你嘗試類似下面。你不應該試圖在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 Documentation中瞭解關於jQuery.ajax()函數的更多信息。

+0

謝謝,我現在正在使用Ajax來處理它。根據你的例子,我不必使用會話變量。我對麼?另外,正如我從你提供的網址瞭解到的,「.done(函數(msg){」msg表示我的input.php應該返回的字符串,所以我怎麼才能讓我的php將錯誤返回給這個函數? –

+0

是的,只是返回從你的PHP值,它將準備在'msg'變量中使用。 –

+0

OP不應該忘記保護他們的PHP API,並像最常見的那樣檢查「referrer」頭文件:正常情況下使用會話認證令牌 – Reishin

1

要從JavaScript執行Php腳本,您必須使用Ajax。

下面的代碼:

$("#confirm").click(function() { 
    <?php 
    include 'input.php'; 
    ?> 
    alert ("data Added successfully."); 
    }); 

將無法​​正常工作

http://api.jquery.com/jquery.ajax/

-1

試試這個:

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

你可以嘗試添加JQuery的cdn鏈接並嘗試使用它: 。 –

1

您需要使用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);}); 
-1

我不太清楚你在那裏試過什麼。反正這裏是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") 
     } 
}); 
1

您可以通過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 
    } 
    }); 
    }); 

});