F
F
fapchat2021-11-21 18:45:43
AJAX
fapchat, 2021-11-21 18:45:43

Why does the confirm($txt) function return the old (past) text of the file?

Hello! Here is such a problem:
Here is the code in order to return the result of the js conferr using the php function

<?php
function confirm($txt)
{
?>
<script>
let txt = "<?php echo $txt; ?>";
var confirm = confirm(txt);
$.ajax({
url: 'script.php',
type: 'POST',
data: "confirm=" + encodeURIComponent(confirm)
})
</script>
<?php
return filter_var(file_get_contents('text.txt'), FILTER_VALIDATE_BOOLEAN);
}


Here is the script.php file

<?php
if (isset($_POST['confirm'])) {
$file = 'text.txt';
file_put_contents($file, $_POST['confirm']);
}


The text.txt file is updated after each page reload with a decision in confirm (that is, after choosing between ok and cancel), but the confirm($txt) function
returns the old (past) text of the file, that is, the one that was before overwriting the file with using file_put_contents. What to do?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
ThunderCat, 2021-11-21
@ThunderCat

...
var confirm = confirm(txt);// здесь получаем тру или фалс, ок...
...
data: "confirm=" + encodeURIComponent(confirm) //здесь его енкодим и отправляем на сервер зачем-то...
...
return filter_var(file_get_contents('text.txt'), FILTER_VALIDATE_BOOLEAN);//читаем файл, получаем из него значение...

When executing the function, you display Javascript in the browser, and immediately request the contents of the file. Since the output to the browser and the execution of the js function in the browser occur with a serious delay, naturally you will get the "old" value, and the new one will most likely contain some kind of nonsense like a 'true'/'false' string, judging by the code.

S
SagePtr, 2021-11-21
@SagePtr

phpfaq.ru/newbie/na_tanke
Read several times until you understand the meaning

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question