jQuery POST form that is viewed with Ajax

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



jQuery POST form that is viewed with Ajax



Ok, this is my first time logged in, but have a question which I can`t find. Maybe I used the wrong search terms or it is my broken English.
But hopefully, somebody can point me in the right direction.



My situation. I have a list of users. When I click on one of them a second screen opens using javascript/AJAX. Some CSS styling does the split screen thing.



In the second screen, I show a form with some info or not. So far so good.
What I want is that when you change some info and you press the submit/save button, data gets saved in the database without a page refresh. But I can't get it right. When I press the button the ajax split-screen disappears. But the page that I linked on the jquery does nothing.



Some code is in Dutch so ask if you need translation.



My code is as follows:
Page users.php


<script>
function jsAjaxVieuwUser(str)

if (str == "")
document.getElementById("mainRight").innerHTML = "";
return;
else
if (window.XMLHttpRequest)
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
else
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");

xmlhttp.onreadystatechange = function()
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
document.getElementById("mainRight").innerHTML = xmlhttp.responseText;

;
xmlhttp.open("GET", "ajaxBeheer.php?VieuwUser=" + str, true);
xmlhttp.send();

document.getElementById("mainRight").style = "display: inline-block;"; // Don`t show the start table
document.getElementById("closeUser").style = "display: block;"; // Don`t show the start table


</script>

<div class="main">
<div class="mainInfo">
<h3>Gebruikers</h3>
</div>

<div class="mainContent">

<div class="mainLeft" id="mainLeft">
<div class="actionBar">
<div><a href="newuser.php"><button class="button button2">Nieuwe gebruiker</button></a></div>
<div id="closeUser"><a href="#" onClick="closeUserVieuw()"><button class="button button2"> << </button></a></div>
</div>

<div class="list" id="userList">
<ul>
<li class="listheader"><div class="listFirstColum">Naam gebruiker</div> <div class="listSecondColum">Laatste login</div></li>
<?php
if(!isset($_GET['limit']))
// START, AANTAL
$limit = '0 , 10';

$result = $db->select("SELECT ID, user_name, user_last_login FROM users ORDER BY ID ASC LIMIT ".$limit." ",array(''),array(''));

while ($row = $result->fetch_assoc())
echo '<a href="#" onClick="jsAjaxVieuwUser('.$row['ID'].')"><li> <div class="listFirstColum">'.$row['user_name'].'</div> <div class="listSecondColum">'.$row['user_last_login'].'</div> </li></a>';


?>
</ul>
</div>
</div>

<div class="mainRight" id="mainRight">
<h1>HALLO</h1>
</div>

</div>




</div>



Page ajaxBeheer.php


if(isset($_GET['VieuwUser'])){

$disabled = 'disabled';
$idUser = $_GET['VieuwUser'];

$result = $db->select(" SELECT users.ID,
users.user_name,
users.user_email,
userinfo.userid,
userinfo.user_firstname,
userinfo.user_lastname,
userinfo.user_birthday,
userinfo.user_adress,
userinfo.user_adressnr

FROM users INNER JOIN userinfo
ON userinfo.userid = users.ID
WHERE users.ID=? ", array($idUser),array('%i'));

while ($row = $result->fetch_assoc())
//Gebruikers gegevens
$username = $row['user_name'];
$user_email = $row['user_email'];

//Personal data
$user_firstname = $row['user_firstname'];
$user_lastname = $row['user_lastname'];
$user_birthday = $row['user_birthday'];
$user_adress = $row['user_adress'];
$user_adressnr = $row['user_adressnr'];



// make the date readable, but if its empty make it 0000
if ($user_birthday == '0000-00-00' || empty($user_birthday))
$user_birthday = ' ';
else
$date = DateTime::createFromFormat('Y-m-d', $user_birthday);
$user_birthday = $date->format('d-m-Y');


?>
<div class="contentHolder" style="width: 100%;">
<div class="header">
<h3 style="width: 100%; text-align: center;">Gegevens medewerker: <?= $username ?></h3>
</div>

<div class="prLeftColomn colomn">
<form name="gebruiker" id="formId" method="POST">
<p><div class="omschrijving">Voornaam</div><div class="waarde"><input type="text" name="firstname" value="<?= $user_firstname ?>" /></div></p>
<p><div class="omschrijving">Achternaam</div><div class="waarde"><input type="text" name="firstname" value="<?= $user_lastname ?>" /></div></p>
<p><div class="omschrijving">Email</div><div class="waarde"><input type="text" name="firstname" value="<?= $user_email ?>" /></div></p>
<p><div class="omschrijving">Geboorte datum</div><div class="waarde"><input type="text" name="firstname" value="<?= $user_birthday ?>" /></div></p>
<p><div class="omschrijving">Telefoon</div><div class="waarde"><input type="text" name="firstname" value="" /></div></p>

<p><div class="omschrijving">Adres + huisnummer</div><div class="waarde">&nbsp;<?= $user_adress.'&nbsp;'.$user_adressnr ?></div></p>
<p><div class="omschrijving">Postcode</div><div class="waarde">&nbsp;</div></p>
<p><div class="omschrijving">Plaats</div><div class="waarde">&nbsp;</div></p>
<p><div><input class="button" type="submit" name="updateGebruiker" value="UPDATE" onclick="save()"/></div></p>
</form>
</div>

<style type="javascript">
function save()
var query = $('#formId').serialize();
var url = 'updateUser.php';
$.post(url, query, function (response)
alert (response);
);


</style>



page updateUser.php


<?php

$table = 'userinfo';
$data = array('user_firstname' => 'test');
$format = array('%s');
$where = array('id' => '3');
$where_format = array('%i');
$updateCalc = $db->update($table, $data, $format, $where, $where_format);
?>





Did you check my solution? comment me if it doesn't work for you.
– zhilevan
Aug 12 at 10:04




2 Answers
2



The reason of refreshing the page is because you're using a form with submit button, to prevent it just prevent the form to submit



if you have Jquery use the following


//option A
$("form#formId").submit(function(e)
e.preventDefault();
);



and Pure js solution is


document.getElementById('formId').addEventListener('submit', function(e)
e.preventDefault();
);





I have tryed it and yea the page doesnt refresh anymore. But the page execute doesnt work. I did go back to the basics and minimalize everything and still it doen`t work. If i opened the updateUser.php it worked, so that script is correct.
– MrDutchstyler
Aug 12 at 18:26



t refresh anymore. But the page execute doesn





@MrDutchstyler thank you for feedback,
– zhilevan
Aug 13 at 3:55



Ok have it finally worked. Had the jquery in the ajaxBeheer.php script. Now i have it in the page where the ajax is executed. And that worked for me.
The Jquery link



Is located in the header.



I have now a second screen where the information is updated without a refresh page. :D
It`s without security so thats need too update for everyone that wants too use it! The question was for the second screen no refresh page.



Hopefully i can help some other people with it, becease it was a pain for me too find information.



The whole code:
Page users.php:


<?php
require_once (__DIR__.'/safeuser.php');
require_once (__DIR__.'/include/topheader.php');
require_once (__DIR__.'/include/config.inc.php');
require_once (__DIR__.'/classes/class-db.php');

?>


<script>
function jsAjaxVieuwUser(str)

if (str == "")
document.getElementById("mainRight").innerHTML = "";

return;
else
if (window.XMLHttpRequest)
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
else
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");

xmlhttp.onreadystatechange = function()
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
document.getElementById("mainRight").innerHTML = xmlhttp.responseText;

;
xmlhttp.open("GET", "ajaxBeheer.php?VieuwUser=" + str, true);
xmlhttp.send();

document.getElementById("mainRight").style = "display: inline-block;"; // Don`t show the start table
document.getElementById("closeUser").style = "display: block;"; // Don`t show the start table




function save()
// Get the form.
var form = $('#formId');

// Get the messages div. Too show the messages on screen
var formMessages = $('#form-messages');

// TODO: The rest of the code will go here...
// Set up an event listener for the contact form.
$(form).submit(function(event)
// Stop the browser from submitting the form.
event.preventDefault();

// TODO
// Serialize the form data.
var formData = $(form).serialize();

// Submit the form using AJAX.
$.ajax(
type: 'POST',
url: $(form).attr('action'),
data: formData
)

.done(function(response)
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');

// Set the message text.
$(formMessages).text(response);

alert (response);
)

.fail(function(data)
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');

// Set the message text.
if (data.responseText !== '')
$(formMessages).text(data.responseText);
else
$(formMessages).text('Oops! An error occured and your message could not be sent.');

);
);


function closeUserVieuw()
var x = document.getElementById("mainRight");
if (x.style.display === "none")
x.style.display = "block";
else
x.style.display = "none";
document.getElementById("closeUser").style = "display: none;"; // Don`t show the start table



</script>


<style type="text/css">


</style>


<div class="main">
<div class="mainInfo">
<h3>Gebruikers</h3>
</div>

<div class="mainContent">

<div class="mainLeft" id="mainLeft">
<div class="actionBar">
<div><a href="newuser.php"><button class="button button2">Nieuwe gebruiker</button></a></div>
<div id="closeUser"><a href="#" onClick="closeUserVieuw()"><button class="button button2"> << </button></a></div>
</div>

<div class="list" id="userList">
<ul>
<li class="listheader"><div class="listFirstColum">Naam gebruiker</div> <div class="listSecondColum">Laatste login</div></li>
<?php
if(!isset($_GET['limit']))
// START, AANTAL
$limit = '0 , 10';

$result = $db->select("SELECT ID, user_name, user_last_login FROM users ORDER BY ID ASC LIMIT ".$limit." ",array(''),array(''));

while ($row = $result->fetch_assoc())
echo '<a href="#" onClick="jsAjaxVieuwUser('.$row['ID'].')"><li> <div class="listFirstColum">'.$row['user_name'].'</div> <div class="listSecondColum">'.$row['user_last_login'].'</div> </li></a>';


?>
</ul>
</div>
</div>

<div class="mainRight" id="mainRight">
<h1>HALLO</h1>
</div>

</div>




</div>




<!-- FOOTER -->
</div>


</body>
</html>



ajaxBeheer.php:


<?php
// name: ajaxBeheer.php

require_once (__DIR__.'/classes/class-users.php');
require_once (__DIR__.'/include/config.inc.php');

if(isset($_GET['q']))
$zoek = $_GET['q'];
$param = "$zoek%"; // Zoek alleen op voorletter
$getGebruiker = $db->select("SELECT * FROM users WHERE naam LIKE ?",array($param),array('s'));

?>

<div id="tableUsers">
<div class="headRow" style="" id="tableUsers">
<div class="cell" style="width: 70%">Gebruiker</div>
<div class="cell" style="width: 30%; border-left: 2px solid #fff; border-right: 2px solid #fff;">Status</div>
</div>

<?php
while ($myrow = $getGebruiker->fetch_assoc())

if($myrow['active'] == '1')
$gebrActive = 'Aktief';
else
$gebrActive = 'gedeaktiveerd';


echo '<a style="display:block" href="?ID='.$myrow['id'].'">
<div class="row">
<div class="cell" style="width: 70%">'.$myrow['naam'].'</div>
<div class="cell" style="width: 30%; border-left: 1px solid #fff; border-right: 1px solid #fff;">'.$gebrActive.'</div>
</div></a>';


echo '</div>';



if(isset($_GET['VieuwUser'])) empty($user_birthday))
$user_birthday = ' ';
else
$date = DateTime::createFromFormat('Y-m-d', $user_birthday);
$user_birthday = $date->format('d-m-Y');


?>


<div class="contentHolder" style="width: 100%;">
<div class="header">
<h3 style="width: 100%; text-align: center;">Gegevens medewerker: <?= $username ?></h3>
</div>


<div class="prLeftColomn colomn">
<form name="gebruiker" id="formId" action="updateUser.php">
<p><div class="omschrijving">Voornaam</div><div class="waarde"><input type="text" name="firstname" value="<?= $user_firstname ?>" /></div></p>
<p><div class="omschrijving">Achternaam</div><div class="waarde"><input type="text" name="lastname" value="<?= $user_lastname ?>" /></div></p>
<p><div class="omschrijving">Email</div><div class="waarde"><input type="text" name="useremail" value="<?= $user_email ?>" /></div></p>
<p><div class="omschrijving">Geboorte datum</div><div class="waarde"><input type="text" name="userbirthday" value="<?= $user_birthday ?>" /></div></p>
<p><div class="omschrijving">Telefoon</div><div class="waarde"><input type="text" name="usertel" value="" /></div></p>

<p><div class="omschrijving">Adres + huisnummer</div><div class="waarde">&nbsp;<?= $user_adress.'&nbsp;'.$user_adressnr ?></div></p>
<p><div class="omschrijving">Postcode</div><div class="waarde">&nbsp;</div></p>
<p><div class="omschrijving">Plaats</div><div class="waarde">&nbsp;</div></p>
<p><div><input class="button" type="submit" name="updateGebruiker" value="UPDATE" onclick="save()"/></div></p>
</form>
</div>



<div class="header" style="margin-top: 5%">
<h3 style="width: 90%; text-align: center;">Uren overzicht</h3>
</div>

<div id="tableUserUren">
<div class="prLeftColomn colomn">

<label>Uren deze week</label>
<input type="text" value="" style="background: white;" <?= $disabled ?> />
<label>Uren deze maand</label>
<input type="text" value="" style="background: white;" <?= $disabled ?> />
<label>Uren vorige maand</label>
<input type="text" value="" style="background: white;" <?= $disabled ?> />
<label>Uren Vrij genomen</label>
<input type="text" value="" style="background: white;" <?= $disabled ?> />
<label></label>
<input type="text" value="" style="background: white;" <?= $disabled ?> />
</div>

<div class="prRightColomn colomn">

</div>
</div>

</div>

<?php


?>



updateUser.php


<?php
require_once (__DIR__.'/include/config.inc.php');
require_once (__DIR__.'/classes/class-db.php');


$username = $_POST['firstname'];


// Ready too add the username
$table = 'users';
$data = array('user_name' => $username);
$format = array('%s');
$newJob = $db->insert($table, $data, $format);

if($newJob != $db::SQLSUCCESFULL) // Variable is 00000
echo 'Er is helaas iets fout gegaan met het toevoegen van de regel. Code:'.$newJob;
header('location: '.$_SERVER['REMOTE_HOST'].'newuser.php?err=DATABASE&code='.$newJob);
exit();

else
echo 'succes!'.$username;


?>






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard