0

For some reason, my form won't post, any ideas as to why(I already know that everything else on my server is operational)? Code below:

PHP

    <?php
if(isset($_POST['field1']) && isset($_POST['field2'])) {
$data = $_POST['field1'] . '-' . $_POST['field2'] . "<br>";
$ret = file_put_contents('user.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
    die('There was an error writing this file');
}
}
?>

https://pastebin.com/hHeMD4Mq


HTML/AJAX JS


<form id ="form">
<p>Name:</p>
<input name="field1" type="text" id ="name" />
<h3>&nbsp;</h3>
<p>Message:</p>
<textarea name="field2" type="text" id ="message"></textarea><br/>
<button onclick="pos();">reply</button>
</form>
</td>
</table>
</div>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
function pos(){
var values=$("form").serialize();
$.post('form.php', values, function(response) {
    console.log("Response: "+response);
});}
</script>

https://pastebin.com/eAVE8EGS


demo on my site:

jakesandbox.com/dnd/

(any info not provided above will be provided upon request in the comments)

Jake t
  • 141
  • 2
  • 13
  • are there errors in the console? and are you sure that `values` pertain to the serialized values of your form? – Wreigh Oct 18 '18 at 01:16

3 Answers3

1

The problem is your button is actually submitting the form (Which is essentially reloading the page, as it's submitting to itself). You need to do one of 2 things:

  1. Change your button to a type="button" to prevent it from submitting (A button inside of a form element automatically becomes a submit button):
<button type="button" onclick="pos();">reply</button>
  1. Prevent the click action from taking place (Thus preventing the submit):
<button type="button" onclick="pos(event);">reply</button>
<script type="text/javascript">
function pos(e){
e.preventDefault();
var values=$("form").serialize();
$.post('form.php', values, function(response) {
    console.log("Response: "+response);
});}
</script>

-OR-

<button type="button" onclick="pos(); return false;">reply</button>
Blue
  • 22,608
  • 7
  • 62
  • 92
0

It turns out your form is actually sent normally with GET request (you can probably see the page reload). It occurs when a button inside a form has no specified type (default being submit).

A button of type "submit" inside a form submits the form while a button of type "button" doesn't.

Just add the attribute type="button" to your button and your problem should be solved.

<button type="button" onclick="pos();">reply</button>
Stefmachine
  • 382
  • 4
  • 11
0

On your php end to debug if the data actually came

<?php
header('Content-Type: application/json');
echo json_encode($_POST);

Then on your js

$.post('form.php', values, function(response) {
   console.log(response); // return json
});}
rocky
  • 81
  • 8