2015-12-21 60 views
-1

我有一個用php構建的非常詳細的表單,當我嘗試使用php進行常規GET提交時,它工作得很好,但是我需要使用ajax來執行此操作,因爲我需要進行實時預覽從PHP文件的一些信息,我熟悉PHP,HTML,CSS,但我沒有經驗與AJAXPHP JQUERY AJAX FORM提交回復

所以我的表單是這樣的,它有兩個提交按鈕,我擔心預覽按鈕。基本上我想要頁面提交到php dopdf.php並從中帶回結果。

<form action="dopdf.php" name="formular" id="form" method="GET" enctype="multipart/form-data"> 
<!-- Lots of input --> 
<input type="submit" value="Create PDF" name="print" class="btn btn-primary submit-button" onclick="javascript:document.getElementById('act').value='0'" style="margin-left: 0;" /> 
<input type="submit" value="Preview!" name="preview" class="btn btn-primary submit-button" onclick="javascript:document.getElementById('act').value='0'" style="margin-left: 0;" /> 

這這裏是我使用通過AJAX來填滿完成了jQuery:

<script> 
$('#form').submit(function() { // catch the form's submit event 
$.ajax({ // create an AJAX call... 
    data: $(this).serialize(), // get the form data 
    type: $(this).attr('GET'), // GET or POST 
    url: $(this).attr('dopdf.php'), // the file to call 
    success: function(response) { // on success.. 
    // $('#created').append(response); // update the DIV 
    alert(response); 
    } 
}); 
return false; // cancel original event to prevent form submitting 
}); 
</script> 

,這是這裏的代碼作爲一個測試,我試圖,如果這個工程我會放在if語句數據:

if (isset($_GET['preview'])) { ?> 
    <?php echo = "This is a test"; exit();?> 
<?php } else { 
    // This is for the other submit button. 
} 

,我已經是Ajax的工作原理和我得到的警報的響應,但警報的響應,我得到的是,我從因爲我張貼這張貼在同一頁面的問題從文件形式ent.php所以我得到的document.php回來。

+0

您可以使用按鈕而不是提交按鈕,不僅如此,點擊調用函數而不是'$(「#形式」)。提交(函數(){' –

+0

能否請您包括你得到的錯誤,再加上你可以使用'console.log()'而不是'alert()'在測試的時候更好地查看你的結果。 –

回答

0

我認爲你實際上是在做兩次事情。當你按下按鈕時,它正在運行JavaScript,但也像往常一樣處理提交。

你需要告訴瀏覽器不要做正常提交,你現在用JS做/阿賈克斯此行,添加到您的JavaScript

而且你有一些錯誤的設定參數的AJAX。

使用

<script type="text/javascript"> 
$('#form').submit(function(event) { // catch the form's submit event 
    event.preventDefault(); 

    $.ajax({ // create an AJAX call... 

     data: $(this).serialize(), // get the form data 
     type: $(this).attr('method'), // GET or POST 
     url: $(this).attr('action'), // the file to call 
     success: function(response) { // on success.. 
     // $('#created').append(response); // update the DIV 
     alert(response); 
     } 
    }); 

}); 
</script> 
2

設置網址時出現錯誤。以下內容應該是正確的:

$(this).attr('action') 
+0

嗨,這確實解決了問題,在警告框中返回相同的頁面,但現在一些如何警報框顯示沒有價值,而不是我的回聲陳述。 謝謝你的幫助 –