使用AJAX保存模态表单中的数据


Save data from modal form using 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);
?>

您只需要从PHP文件中回显json数据,如下所示:

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

这就是通过ajax返回数据的方式——您只需将其回显出来,然后在这种情况下,它应该被脚本捕获为变量r

文件保存.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;  
?>

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