2016-04-14 17 views
0

我希望能夠將我在模態表單中輸入的數據保存到文件中,並在提交後將數據返回到警報。使用AJAX保存模態表單中的數據

這是我目前的AJAX。

$("#submit").click(function(){ 

     $.ajax({ 
      type: "POST", 
      url: "save.php", 
      data: $('#form1').serialize(), 
      success: function(r){ 
       alert (r); 
      return false; 
      }, 
      dataType: "html" 
     }); 

     $('.modal').modal('show'); 
    }); 

如果你需要看save.php,那就是:

<?php 
    // check if a form was submitted 
    if(!empty($_POST)){ 
     // convert form data to json format 
     $data = array(
      "name" => $_POST['name1'], 
      "branch_address" => $_POST['bAddress1'], 
      "officer_in_charge" => $_POST['officer1'], 
      "contact_number" => $_POST['contactN1'] 
     ); //processes the fields on the form 

     $json = json_encode($data); 
     $file = 'entries.json'; 
     // write to file 
     file_put_contents($file, $json, FILE_APPEND); 
?> 
+0

添加preventDeault()來防止默認提交。 –

+0

在提醒中,你想看到姓名,分行地址等。對嗎? – larsAnders

+0

@larsAnders是,並將它們保存到一個名爲entries.json的文件中,該文件位於save.php –

回答

1

你只需要從PHP文件呼應JSON數據,像這樣:

$json = json_encode($data); 
    $file = 'entries.json'; 
    // write to file 
    file_put_contents($file, $json, FILE_APPEND); 
    echo $json; 

這是如何通過ajax返回數據 - 你只需回聲它出來,那麼在這種情況下它應該被腳本捕獲爲變量r

+0

是否不需要像「模式」窗體中的值那樣在「data:{}」中放置任何內容? –

+1

不,您正在迴應JSON格式的數據,該數據已被JavaScript接收到。 – larsAnders

0

使用echo $json;行後file_put_contents($file, $json, FILE_APPEND);

1

文件save.php

<?php 
    // check if a form was submitted 
    if(!empty($_POST)){ 
     // convert form data to json format 
     $data = array(
      "name" => $_POST['name1'], 
      "branch_address" => $_POST['bAddress1'], 
      "officer_in_charge" => $_POST['officer1'], 
      "contact_number" => $_POST['contactN1'] 
     ); //processes the fields on the form 

     $json = json_encode($data); 
     $file = 'entries.json'; 
     // write to file 
     file_put_contents($file, $json, FILE_APPEND); 
     echo $json; 
?> 
+0

是否不需要像「模式」表單中的值那樣將「data:{}」中的任何內容都放入? –