2016-05-04 9 views
1

私のウェブサイトにニュースレターの購読機能を組みたいと思っています。私はすべての入力をホストフォルダのtxtファイルに保存したいと思っています。しかし、私は人々がそれを提出した後にページを切り替えたくない。 「ありがとうございます」と言っているポップアップメッセージを表示するだけで完璧です。 PHPで別のページにメッセージを表示する方法を知っていますが、ポップアップボックスでメッセージを表示する方法はわかりません。ここに私のHTMLとPHPコードです。助けてください、ありがとうございます。フォーム入力をtxtに保存する、ポップアップ結果、ページ変更なし

<html> 
<head> 
    <title></title> 
</head> 
<body> 
    <form> 
     <form action="myprocessingscript.php" method="post"> 
     <input name="field1" type="text" /> 
     <input name="field2" type="text" /> 
     <input type="submit" name="submit" value="Save Data"> 
    </form> 
    <a href='data.txt'>Text file</a> 
</body> 

PHPの関数は

<?php 
if(isset($_POST['field1']) && isset($_POST['field2'])) { 
    $data = $_POST['field1'] . '-' . $_POST['field2'] . "\n"; 
    $ret = file_put_contents('/tmp/mydata.txt', $data, FILE_APPEND | LOCK_EX); 
    if($ret === false) { 
     die('There was an error writing this file'); 
    } 
    else { 
     echo "$ret bytes written to file"; 
    } 
} 
else { 
    die('no post data to process'); 
} 
+1

使用AJAXで見てみましょうHTMLファイル。要求のため –

+2

私は実際にフラットファイル上のデータベースを示唆しています。あなたが成長するにつれ、非常に感謝しています。 –

+0

Htmlフォームは、送信時に位置を変更するためにそのように動作するように意図されていますが、JSを使用するのを防ぐことができますが、パラメータを送信するにはajaxを使用する必要があります。 –

答えて

1

あなたのページにjQueryのを含めたら、次のようなものが動作するはずです:

// process the form 
$('form').submit(function(event) { 

    // get the form data 
    // there are many ways to get this data using jQuery (you can use the class or id also) 
    var formData = { 
     'field1'    : $('input[name=field1]').val(), 
     'field2'    : $('input[name=field2]').val() 
    }; 

    // process the form 
    $.ajax({ 
     type  : 'POST', // define the type of HTTP verb we want to use (POST for our form) 
     url   : 'myprocessingscript.php', // the url where we want to POST 
     data  : formData, // our data object 
     dataType : 'json', // what type of data do we expect back from the server 
        encode   : true 
    }) 
     // using the done promise callback 
     .done(function(data) { 

      // log data to the console so we can see 
      console.log(data); 
      // data is the output from your php, check it and display alert appropriately 

      // here we will handle errors and validation messages 
     }); 

    // stop the form from submitting the normal way and refreshing the page 
    event.preventDefault(); 



}); 

source article

関連する問題