In my code I send $id to Java Script section and it returns the same value inside <p id="retid"></p> and I can't get the value as integer inside $text variable.
`while ($row = $result->fetch_assoc())
{
$id = $row["id"];
$regname = $row["reg-name"];
echo '<button class="btnicon btndel" type="button" name="answer" onclick="showDiv('.$id.')"><i class="fa fa-trash"></i> '.$regname.'</button>';
}
} else {
//header("Location: login.php?Msg=wrongPass"); }
}
?>
</div>
<div id="DelMessageDiv" style="display:none;" class="answer_list" >
<form action="_modify.php" method="get">
<div id="alerts">
<?php
$text = '<p id="retid"></p>';
echo $text.'-+-'.strip_tags($text,'<p>').'
Are you sure for delete?
<input name="id" type="hidden" value="'.strip_tags($text).'" />
<button class="btnicon btndel" type="submit" name="operation" value="0+regDelete">Yes Delete</button>
';
?>
</div>
</form>
</div>
</div>
<?php include '_footer.php'; ?>
<script src="js/extention/choices.js"></script>
<script>
const choices = new Choices('[data-trigger]',
{
searchEnabled: false
});
function showDiv(x) {
document.getElementById('DelMessageDiv').style.display = "block";
document.getElementById('retid').innerHTML = x;
}
</script>`
Thanks for all helps.
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><button class="button button2">Nieuwe gebruiker</button></div>
<div id="closeUser"><button class="button button2"> << </button></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 '<li> <div class="listFirstColum">'.$row['user_name'].'</div> <div class="listSecondColum">'.$row['user_last_login'].'</div> </li>';
}
?>
</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"> <?= $user_adress.' '.$user_adressnr ?></div></p>
<p><div class="omschrijving">Postcode</div><div class="waarde"> </div></p>
<p><div class="omschrijving">Plaats</div><div class="waarde"> </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);
?>
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();
});
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><button class="button button2">Nieuwe gebruiker</button></div>
<div id="closeUser"><button class="button button2"> << </button></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 '<li> <div class="listFirstColum">'.$row['user_name'].'</div> <div class="listSecondColum">'.$row['user_last_login'].'</div> </li>';
}
?>
</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'])){
$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" 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"> <?= $user_adress.' '.$user_adressnr ?></div></p>
<p><div class="omschrijving">Postcode</div><div class="waarde"> </div></p>
<p><div class="omschrijving">Plaats</div><div class="waarde"> </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;
}
?>
I've build a function in javascript to show me a second submit but only after the first submit was clicked.
Edited - this is ex.php:
<form method="post" action = "ex.php">
<input type="submit" id="button" name="search" value="Search"
onclick="myFunction();" >
<br>
<input type="submit" name="search_close" id="submit" style="display:
none;" value="Find close results">
</form>
<?php
if(isset($_POST['search']))
{
echo "first search";
}
else if(isset($_POST['search_close']))
{
echo "second search";
}
else {
echo "nothing";
}
?>
<script type="text/javascript">
inputSubmit = document.getElementById("submit");
function myFunction(){
inputSubmit.style.display = "block"; };
</script>
Updated:
I've edited in order to conclude the main problem.
So what I want is this:
a) The user has pressed the first submit button "search" then it will echo on the page "first search" and then show the second submit button "search_close" .
b)Then, if the user has pressed the second submit button it will show "second search".
When first Refreshing:
======
search (button)
======
if clicking the "search" button:
======
search (button)
======
first search (text)
==================
Find close results (button)
==================
if clicking the "find close results:
======
search (button)
======
first search (text)
==================
Find close results (button)
==================
second search (text)
This code doesn't do what I want. Why?
Updated - why the button find close results disappers after one second?
<?php
session_start();
$db=mysqli_connect("localhost","root","","travelersdb");
if(#$_SESSION["username"]){
?>
<?php
// function to connect and execute the query
function filterTable($query)
{
$connect=mysqli_connect("localhost","root","","travelersdb");
$filter_Result = mysqli_query($connect, $query) or die(mysqli_error($connect));
return $filter_Result;
}
$submit_value = 0;
if(isset($_POST['search']))
{
$Destination = $_POST['Destination'];
$TypeOfTravel = $_POST['TypeOfTravel'];
$Age= $_POST['Age'];
$email = $_POST['email'];
$topic_name = $_POST['topic_name'];
$StartingPoint = $_POST['StartingPoint'];
// search in all table columns
$query = "SELECT * FROM `topics`
left join `users` on users.username = topics.topic_creator
WHERE 1=1 ";
if(!empty($Destination)) {
$query.="AND destination='$Destination'";
}
if(!empty($TypeOfTravel)) {
$query.=" AND typeTravel='$TypeOfTravel'";
}
if(!empty($Age)) {
$query.="AND age='$Age'";
}
if(!empty($email)) {
$query.=" AND email='$email'";
}
if(!empty($topic_name)) {
$query.=" AND topic_name='$topic_name'";
}
if(!empty($StartingPoint)) {
$query.=" AND StartingPoint='$StartingPoint'";
}
$search_result = filterTable($query);
$submit_value = 1;
}
///Make The search more wider, only for the fields that were in the post
else if(isset($_POST['search_close']))
{
$Destination = $_POST['Destination'];
$TypeOfTravel = $_POST['TypeOfTravel'];
$topic_name = $_POST['topic_name'];
$StartingPoint = $_POST['StartingPoint'];
// search in all table columns
$query = "SELECT * FROM `topics`
left join `users` on users.username = topics.topic_creator
WHERE 1=1 ";
if(!empty($Destination)) {
$query.="AND destination='$Destination'";
}
if(!empty($TypeOfTravel)) {
$query.=" AND typeTravel='$TypeOfTravel'";
}
if(!empty($topic_name)) {
$query.=" AND topic_name='$topic_name'";
}
if(!empty($StartingPoint)) {
$query.=" AND StartingPoint='$StartingPoint'";
}
$search_result = filterTable($query);
$submit_value = 2;
}
else {
$query = "SELECT * FROM `topics`";
$search_result = filterTable($query);
}
?>
<html>
<head>
<?php header('Content-Type: text/html; charset=utf-8'); ?>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Home Page</title>
<style>
.hidden {
display: none;
}
</style>
<script type="text/javascript">
function showHide()
{
var checkbox = document.getElementById("chk");
var hiddeninputs = document.getElementsByClassName("hidden");
for (var i=0; i != hiddeninputs.length; i++) {
if(checkbox.checked){
hiddeninputs[i].style.display = "block";
} else {
hiddeninputs[i].style.display = "none";
}
}
}
<?php
if($submit_value == 1 || $submit_value == 2){ ?>
myFunction();
inputSubmit = document.getElementById("submit");
function myFunction(){
document.getElementById('submit').style.display = "block";
};
<?php } ?>
</script>
<body>
</body>
</head>
<?php include("header.php");?>
<center>
</br>
<button>Post</button>
</br>
<br/>
<h4>Simple Serach</h4>
<form action="" method="post">
<input type="text" name="Destination" placeholder="Destination" value=
"<?php if(isset($_POST['Destination']))
{echo htmlentities($_POST['Destination']);}?>" ></br>
<input type="text" name="TypeOfTravel" placeholder="Type Of Travel"
value=
"<?php if(isset($_POST['TypeOfTravel']))
{echo htmlentities($_POST['TypeOfTravel']);}?>"
></br>
<input type="text" name="Age" placeholder="Age" value="<?php if(isset($_POST['TypeOfTravel']))
{echo htmlentities($_POST['Age']);}?>">
</br>
</br>
<!-- Advanced Search-->
<input type="checkbox" name="chkbox" id="chk" onclick="showHide()" />
<label for="chk"><b>Advanced search</b></label>
</br>
<input type ="text" name="email" placeholder="Email" class="hidden" value="<?php if(isset($_POST['TypeOfTravel']))
{echo htmlentities($_POST['email']);}?>">
<input type ="text" name="topic_name" placeholder="topic name" class="hidden"value="<?php if(isset($_POST['TypeOfTravel']))
{echo htmlentities($_POST['topic_name']);}?>">
<input type="text" name="StartingPoint" placeholder="Starting Point" class="hidden"value="<?php if(isset($_POST['TypeOfTravel']))
{echo htmlentities($_POST['StartingPoint']);}?>">
</br><br/>
<input type="submit" id="button" name="search" value="Search"
onclick="myFunction();" >
<br><br>
<input type="submit" name="search_close" id="submit" style="display:
none;" value="Find close results">
</form>
<br/>
<?php echo '<table border="1px">';?>
<td width="400px;" style="text-align:center;">
Name
</td>
<td width="400px;" style="text-align:center;">
Destination
</td>
<td width="400px;" style="text-align:center;">
Type Of Travel:
</td>
<td width="80px;" style="text-align: center;">
First Name
</td>
<td width="80px;" style="text-align: center;">
Age
</td>
<td width="400px;" style="text-align:center;">
profile picture
</td>
<td width="80px;" style="text-align: center;">
Creator
</td>
<td width="80px;" style="text-align: center;">
Date
</td>
</tr>
</center>
<?php
$sql = "Select * from `topics`";
$check = mysqli_query($db,$sql);
$rows = mysqli_num_rows($search_result);
if($rows != 0){
while ($row = mysqli_fetch_assoc($search_result)){
$id = $row['topic_id'];
echo "<tr>";
//echo "<td>".$row['topic_id']."</td>";
echo "<td style='text-align:center;'><a href='topic.php?id=$id'>".$row['topic_name']."</a></td>";
echo "<td>".$row['Destination']."</td>";
echo "<td>".$row['typeTravel']."</td>";
$sql_u = "Select * from users where username='".$row['topic_creator']."'";
$check_u = mysqli_query($db,$sql_u);
while ($row_u = mysqli_fetch_assoc($check_u))
{
$user_id = $row_u['id'];
$profile_pic = $row_u['profile_pic'];
$firstname = $row_u['firstname'];
$age = $row_u['age'];
echo "<td>".$firstname."</td>";
echo "<td>".$age."</td>";
echo "<td><img src='".$profile_pic."' width='10%' height='10%' alt='me'></td>";
echo "<td><a href='profile.php?id=$user_id'>".$row['topic_creator']."</a></td>";
}
$get_date = $row['date'];
echo "<td>".$row['date']."</td>";
echo "</tr>";
}
}else {
echo "No topics found";
}
echo "</table>";
if (#$_GET['action']=="logout")
{
session_destroy();
header('location:login.php');
}
}else
{
echo "You must be logged in.";
echo "<a href ='login.php'>Click here to login</a>";
}
?>
</br>
</br>
<body>
</body>
</html>
you need to set type button cause when you set type submit then form automatically submit so show second not show but it work.
<form method="post" action = "">
<input type="submit" id="button" name="search" value="Search" >
<br>
<input type="submit" name="search_close" id="submit" style="display:
none;" value="Find close results">
</form>
<?php
$submit_value = 0;
if(isset($_POST['search']))
{
echo "first search";
$submit_value = 1;
}
else if(isset($_POST['search_close']))
{
echo "first search";
echo '<br>';
echo "second search";
$submit_value = 2;
}
else {
echo "nothing";
}
?>
<script type="text/javascript">
<?php
if($submit_value == 1 || $submit_value == 2){ ?>
document.getElementById('submit').style.display = "block";
<?php } ?>
</script>
check this code
I have cleaned up your code, but the issue of having two submit buttons still persists. Even if the clicking of the first button causes the second to show, the first button will cause the page to reload with the results from the form's action resource. In this example, I have cancelled the form's submit event to show that the display of the second button works.
In the end, I think you are going about this all wrong. I think you should be making AJAX calls to your server-side resource and injecting the results of that call into your page - - no forms and no submits.
// Don't forget to add "var" to your variable declarations, otherwise the variables
// become global!
var sub1 = document.getElementById("btnSub1");
var sub2 = document.getElementById("btnSub2");
// Set up the event handler for the first button
sub1.addEventListener("click", myFunction);
function myFunction(e){
// Adjust classes, not individual styles
sub2.classList.remove("hidden");
// Cancel the native event and stop bubbling
e.preventDefault();
e.stopPropagation();
};
.hidden { display:none; }
<form>
<!-- Submit buttons don't get a name attriute unless you expect their value to be submitted
along with all the other form data. Inline styles should be avoided and internal style
sheets used instead. And, inline JavaScript event attributes (onclick, etc.) should not
be used. -->
<input type="submit" id="btnSub1" name="search" value="Search" >
<br>
<input type="submit" id="btnSub2" class="hidden" value="Find close results">
</form>
<?php
if(isset($_POST['search']))
{
echo "first search";
}
else if(isset($_POST['search_close']))
{
echo "second search";
}
else {
echo "nothing";
}
?>
So I have the code following and it all works but the on success / error I can figure it out.
This is settings.php
<li><button type="button" onclick="ApimanagementFunctioncall()" id="button1" class="btn btn-default btn-lg">Api management</button></li>
<script>
function ApimanagementFunctioncall(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("display").innerHTML = xhttp.responseText;
}
}
xhttp.open("GET", "Apimanagement.php", true);
xhttp.send();
}
</script>
The Apimanagement.php
MySQLI table here.
<div class="container">
<div class="row text-left">
<button type="button" class="btn btn-default btn-lg" data-toggle="modal" data-target="#AddApi"><span class="glyphicon glyphicon-plus"></span>Add Api</button>
</div>
</div>
<div class="modal fade" id="AddApi" role="dialog">
<?php
include ("ApiAdd.php");
?>
</div>
this is the Addapi.php
<?php
$errorMessage = "";
$UserId = "11";
if(isset($_POST['submit'])){
$VarKeyID = $_POST["KeyID"];
$VarVCode = $_POST["VerificationCode"];
$errorMessage1 = "";
$errorMessage2 = "";
$VkeyAdd= ""; $VCodeAdd = "";
if(empty($VarKeyID) == false){
if(is_numeric($VarKeyID) == true){
if(strlen($VarKeyID) !== 8){
echo '<script type="text/javascript">alert("Key Id is not the correct length of 8 numbers!\n");</script>';}
else{ $VKeyAdd = "true";}
}else{$errorMessage1 = '<script type="text/javascript">alert("Key Id should only be numbers!");</script>';}
}else{$errorMessage1 ='<script type="text/javascript">alert("Please Enter a Key ID!");</script>';}
if(empty($VarVCode) == false){
if(ctype_alnum($VarVCode) == true){
if(strlen($VarVCode) !== 64){
$errorMessage2 = "Verification Code should be 64 characters!";
}else{$VCodeAdd = "true";}
}else{$errorMessage2 = '<script type="text/javascript">alert("Verification Code should only be letters and numbers!");</script>';}
}else{$errorMessage2 ='<script type="text/javascript">alert("Please Enter a Verification Code!");</script>';}
If($VKeyAdd == "true"){
if($VCodeAdd == "true"){
echo "Next";}else{echo $errorMessage2;}
}else{echo $errorMessage1;}
}
?>
<div id="AddApi">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<span class="glyphicon glyphicon-remove"></span>
<h2> Add Api Key </h2>
Api create key here
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="POST">
Key ID</br> <input type="text" name="KeyID" maxlength="8" value=""></br>
Verification Code</br> <input type="text" name="VerificationCode" maxlength="64" min="64" value=""></br>
<input type="submit" name="submit" value="Submit" formtarget="_Self">
</form>
</div>
</div>
<div>
Now I know some code i have left out but the relevant code is here and works. The issue is when I click the input submit button of the form. It opens up the addApi.php on the server instead I would like it to echo the errors on the input form and if success go to the Settings.php page where the apimanagement.php page is loaded in the div.
<?php
session_start();
if(!isset($_SESSION['user_id']) && empty($_SESSION['user_id'])){
header("Location:login.php");
}
include 'connect.php';
include 'functions.php';
$my_id = $_SESSION['user_id'];
$hash = $_GET['hash'];
if(isset($_POST['message']) && !empty($_POST['message'])){
$new_message = $_POST['message'];
mysql_query("INSERT INTO `messages` VALUES('','$hash','$my_id','$new_message')");
header('Location: startcon.php?hash='.$hash);
}
?>
<link rel='stylesheet' href='css.css' />
<header>
<div id="logo"><img src="logo.jpg" height="35px" width="35px"></div>
<div id="options">Messenger     Friends     Friend Requests     <a href='find.php'>Find Friends</a>     <a href='logout.php'>Logout</a>   </div>
</header>
<div id='outerconversation'>
<div id="conversationheader"><a href='conversation.php' title='back'><img src='back.png' height='20px' width='18px' /></a></div>
<div id="innerconversations">
<?php
$message_query = mysql_query("SELECT from_id, message FROM `messages` WHERE `group_hash`='$hash'");
while($run_message = mysql_fetch_array($message_query)){
$from_id = $run_message['from_id'];
$message = $run_message['message'];
$user_query = mysql_query("SELECT `email`,`username` FROM `users` WHERE id='$from_id'");
$run_user = mysql_fetch_array($user_query);
$from_email = $run_user['email'];
$from_username = $run_user['username'];
echo "<hr color='#008298' /><span style='color: #008298; font-family: Arial; margin-left: 10px;'>$from_username <span style='color: #BAB9B9; font- style: italic;'>$from_email</span></span><br/><br/>";
echo "<span style='color: #008298; font-family: Segoe UI Light; margin- left: 30px;'><span style='color: #BAB9B9; font-family: Arial; margin-left: 10px;'>says: </span>$message</span><br/><br/>";
}
?>
</div>
<form method='POST'>
<?php
?>
<textarea name='message' placeholder="Type Message..." maxlength="400" rows='6' cols='145'></textarea>
<input type='submit' value="Send Message" />
</form>
</div>
I am making a chat system. I want to send message using ENTER key instead of input submit button and New line using Shift+Enter. I don't have strong knowledge of javascript and jquery. Please make a function that sends message using enter key and make new line using shift+enter key.
<form id="chat_form" method='POST'>
<textarea name='message' placeholder="Type Message..." maxlength="400" rows='6' cols='145' autofocus></textarea>
<input type='submit' value="Send Message" />
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
var shiftDown = false;
var chatForm = $("#chat_form");
var messageBox = chatForm.children("textarea");
$(document).keypress(function (e) {
if(e.keyCode == 13) {
if(messageBox.is(":focus") && !shiftDown) {
e.preventDefault(); // prevent another \n from being entered
chatForm.submit();
}
}
});
$(document).keydown(function (e) {
if(e.keyCode == 16) shiftDown = true;
});
$(document).keyup(function (e) {
if(e.keyCode == 16) shiftDown = false;
});
</script>