I have a form with a submit button and a close button. If a user enters something and hits the submit button, an answer will be posted and saved inside the database. If a user clicks the close button, inside the database an entry will be updated with the current timestamp.
Everything is working fine but now I would like to make those changes if someone clicks the close button with AJAX so that I do not have to reload the page.
The code for my submit button is:
<input type='submit' id='setclosed' value='Close Ticket' name='setclosed' class='btn btn-warning' />
Now if someone clicks the submit button, the followin code will be activated inside my current file (so no external file for php processing):
if (isset ($_POST['setclosed'])) { // Setze Status auf Closed
$updatecontent_success=array('stamp_closed'=>$localtime);
updateContractTicket($show_details,$updatecontent_success);
}
What do I have to do so that the database entry will be updated, but the page does not reload?
Here is a quick AJAX example to get you going. You should separate you PHP and Javascript/HTML code. I'll write out the two files.
In your HTML file you'll have the html code and the javascript that will make the request, and then alert the user that the request went through. Make sure that your form doesn't submit anything.
-HTML
<button type='button' id='setclosed' name='setclosed' class='btn btn-warning'>Close Ticket</button>
-Javascript
$('#setclosed').click(function() {
$.post('ajax.php',
{ cmd: 'setclosed' },
function(data) {
alert('AJAX request was made');
}, 'json'
);
});
The ajax sends a POST variable read by the PHP as $_POST["cmd"]
. This will let your php execute the necessary code for that command, echo back a status, and then exit the php file.
-PHP
if ($_POST["cmd"]=='setclosed') {
$updatecontent_success=array('stamp_closed'=>$localtime);
$updateContractTicket($show_details,$updatecontent_success);
echo json_encode(array('Status' => 'Ok'));
exit(0);
}
Let me know if anything is unclear.