index.php:
<script>
$(document).ready(function(){
$("form").submit(function(){
var str = $(this).serialize();
$.ajax({
type: "POST",
url:"do.php",
data: $("form").serialize(),
});
return false;
});
});
</script>
<form action='do.php' method='post' id='toDo' name='toDo'>
<input type='hidden' name='okok' value='one.txt'>
<button type='submit' class='theButton'></button>
</form>
<form action='do.php' method='post' id='toDo' name='toDo'>
<input type='hidden' name='okok' value='two.txt'>
<button type='submit' class='theButton'></button>
</form>
On the code above, there are 2 different forms - each with the same name. Each form has an input hidden
tag with its own unique value relating to a specific file in the directory.
If the user clicks the submit button in any of the forms, the value of the input hidden
tag that was in the form that the user clicked the submit button in will be sent to the file do.php.
As the values of the input hidden
tags are names of a text file, once it is sent to do.php (which can be seen below), the contents of the file will be retrieved (the contents are all numbers). The value that is retrieved from the text file (which is a number) will increase by 1. The new value that increased by 1 will rewrite the old value and be stored in the text file.
do.php:
<?php
$filename = $_REQUEST[okok];
$content = file_get_contents($filename);
preg_match("#\d+#", $content, $before_editing);
$number_before = $before_editing[0];
file_put_contents($filename, ++$number_before);
$content = file_get_contents($filename);
preg_match("#\d+#", $content, $after_editing);
$number_after = $after_editing[0];
?>
The code works perfectly without the AJAX script that I have included. With the AJAX script, only the value of the bottom form will be sent to do.php - so if I click submit on the first form, instead of sending the value one.txt, it'll send the value two.txt.
How would I fix the AJAX so that it works correctly?