使用AJAX从模态表单保存数据

时间:2016-04-14 04:53:32

标签: php 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);
?>

3 个答案:

答案 0 :(得分:1)

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

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

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

答案 1 :(得分: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;  
?>

答案 2 :(得分:0)

echo $json;

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