I have this form and the user can choose things from a list. For the selected items the attribute in the database changes (Insert/Update statements). When the user clicks on the button the functions all work fine.
Now i want to redirect the user to another page after script. At the moment, the user can’t see a difference after a click on the button, even though the script works fine.
This is the relevant part of the script:
<div id="refresh-section">
<form id="chk-input" role="form" method="post">
<?php
$vertragFS = $vertrag->getVertragFS($et);
?>
</form>
</div>
<button id="button" class="btn btn-primary" type="submit" form="refresh section" name="status">Flurstücke an Vertrag koppeln</button>
<script>
var form = document.getElementById('chk-input');
document.getElementById('button').addEventListener('click', function(e) {
var fskz = [];
form.querySelectorAll('input').forEach(function(input) {
if (input.type === 'checkbox' && input.checked) {
fskz.push(input.value);
}
})
string_json = JSON.stringify(fskz);
//console.log(fskz);
$.ajax({
method: "post",
data: {
fskz: JSON.stringify(fskz),
}
})
})
<?php
$fskz = json_decode($_POST['fskz'], true);
$vid = $_GET['vid'];
foreach ($fskz as $fkz) {
$vertrag->insertVertragID($fkz, $vid);
$vertrag->updateFlstStatusSN2($fkz);
}
?>
</script>
I already tried the ‘standard things’. A header won’t work due to the outputs. I also tried to run the script without the echo and console log statements, but it doesn’t work.
A JS relocation reacts instantly, so the user cannot interact. Ob_start() and Ob_flush() haven’t worked yet, I tried in combination with header at different lines in the script. Doesn’t work.
I also tried to add a condition to the foreach statement, that user should get redirected after the last insert/update statement is executed. This doesn’t work.
Can you give me advise what i need to look for or what i have to change in general? Thanks 🙂
Edit: I know i can add an extra button to relocate, but i want to combine it in the one existing button.
2
Answers
Add ajax succes function, and then your php code should run after it. Then finally in the end you can redirect using js.
Using AJAX probably doesn’t make much sense if you want to redirect afterwards. While it’s possible to do that, it misses the point of using AJAX, which is to avoid any need for postbacks / redirects etc.
You can achieve all this easily with a standard postback and sensible code structure.
If you put the code which processes the form and performs the redirect first in your script (within a check to see if the request is a POST, which is lacking in your code now) you can
That is a very standard structure to use in a web application.
So something like this: