how to pass data javascript into php page without reloading the page - javascript

hi guys need help regarding how to pass a value to php using javacript without reloading the page. What i want to happen is that when i put a value in textbox name num1 that value will go to available.php.. advance thank u.
...
here is my code..
html code
<!-- Modal Staff-->
<div id="add" class="modal fade" role="dialog" tabindex="-1" >
<div class="modal-dialog">
<form action="dashboard.php" method="post">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×
</button>
<h4 class="modal-title">Set Available Student</h4>
</div>
<div class="modal-body">
<input type="text" name="num1" id="num1" class="form-control" />
</div>
<div class="modal-footer">
<input type="submit" name="submit" class="btn btn-success" value="Set">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</form>
</div>
</div>
javascript code
<script type="text/javascript">
function availble_chair()
{
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","available.php",false);
xmlhttp.send(null);
document.getElementById("count").innerHTML=xmlhttp.responseText;
}
availble_chair();
setInterval(function(){
availble_chair();
},1000);
</script>
and here is my php code available.php
<?php
$set = '';
$connection = mysqli_connect("localhost","root","","dbattendancelibrary");
$query=mysqli_query($connection,"SELECT COUNT(Time_in)-COUNT(Time_out) as Status FROM `tbl_student_form`");
$result = mysqli_fetch_array($query, MYSQLI_NUM);
if($result) {
if($result[0] <= $set) {
$availble = $set-$result[0];
echo "<p style='font-size:50px;margin-left:240px;'> " .$availble. "
</p>";
} else {
echo "<p class='alert alert-danger'>Library Already Full</p>";
}
}
?>

Javascript:
First, you need an on submit event listener so we can detect when the form was submitted.
// get a reference to your form
var form = document.getElementsByTagName('form');
// i suggest adding a classname or ID to your form if you have more then one form on the page
// if that is the case, then select the form by ID or class instead
// add event listener to the form
form.addEventListener('submit', function(event) {
// stop form submitting by default
event.preventDefault();
// get the value from the textbox, num1
var num1 = this.querySelector('#num1').value;
// send value of num1 to available.php via ajax
var xhr = new XMLHttpRequest();
xhr.open('GET', 'available.php');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
console.log("I worked!");
} else {
console.log("I didn't work!");
}
};
xhr.send(encodeURI('num1=' + num1));
}
PHP
To get the num1 value from AJAX request:
<?php
$num1 = isset($_GET['num1']) ? (int) trim($_GET['num1']) : 0;
if ($num1 > 0) {
// success
}
?>

Related

Disable input in Bootstrap 4 after error with calling Ajax

I have a form in Bootstrap 4 which, through XMLHttpRequest, verifies that a Serial Number is not already inserted.
If it already is, I open a div where I notify the user that the Serial Number is already present.
How can I disable the rest of the form or the Submit button when opening the div?
On the content of the div that opens there is a button that resets the form, so one method is worth the other.
It is enough for me that the rest of the form cannot be sent.
Thanks in advance.
Input Form
<div class="form-group">
<label for="id_cliente">Num. Tessera:</label>
<input type="number" class="form-control no-slide" id="id_cliente" placeholder="Inserisci Numero Tessera" name="id_cliente" required onchange="chkTessera(this.value)">
<div class="valid-feedback">Valido.</div>
<div class="invalid-feedback">Per favore compila questo campo.</div>
</div>
<div id="txtTessera"></div>
chk_Tessera Function
function chkTessera(str) {
if (str=="") {
document.getElementById("txtTessera").innerHTML="";
return;
}
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtTessera").innerHTML=this.responseText;
}
}
xmlhttp.open("GET","chk_tessera.php?key="+str,true);
xmlhttp.send(); }
chk_tessera.php
<?php
$db = new SQLiteDB();
$id_cliente = $_GET['key'];
$sql = <<<EOF
SELECT * FROM clienti WHERE id_cliente = $id_cliente;
EOF;
$result = $db->query($sql);
$num_righe = 0;
while($row = $result->fetchArray(SQLITE3_ASSOC) ){
++$num_righe;
}
if($num_righe > 0){
?>
<div class="mw-100 bg-warning">
<div class="alert alert-danger" >
<strong>ATTENZIONE!</strong> Il Numero di Tessera risulta già
assegnato.
<button type="button" class="btn btn-success btn-sm"
onclick="window.location.replace('ins_anagrafica_cliente.php')">OK</button>
</div>
</div>
<?php
}
?>
Just add a attribute to that element
$.ajax({
url: '',
success: function(){
$('#id_cliente').attr('disabled','disabled');
},
error: function(){}
});

PHP & AJAX - No refresh data when fetch to another page and send it as a Modal

I am now sending data to another page without refresh but my problem is the modal, I cannot send it as a modal but I can send the data into text. why ?
here is an image of my page
here is my code
for ajax4.html
This is where I submit data and perform inserts
<h1>AJAX POST FORM</h1>
<form id="postForm">
<input type="text" name="name" id="name2">
<input type="submit" value="Submit">
</form>
<script>
document.getElementById('postForm').addEventListener('submit', postName);
function postName(e){
e.preventDefault();
var name = document.getElementById('name2').value;
var params = "name="+name
;
var xhr = new XMLHttpRequest();
xhr.open('POST', 'process.php', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function(){
console.log(this.responseText);
}
xhr.send(params);
}
</script>
my ajax5.html
This is where I fetch the data and also, here is where I want to show the modal
**EDIT** here is my current HTML
<h1>Users</h1>
<div id="users"></div>
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">User List</h4>
</div>
<div class="modal-body" id="user-list">
<p>User list here</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
<script>
var still_fetching = false;
//fetch data every 3 seconds (3000)
setInterval(function(){
if (still_fetching) {
return;
}
still_fetching = true;
loadUsers();
}, 3000);
//need to update a bit this function
function loadUsers(){
var xhr = new XMLHttpRequest();
xhr.open('GET', 'users.php', true);
xhr.onload = function(){
if(this.status == 200){
var users = JSON.parse(this.responseText);
var output = '';
for(var i in users){
output += '<div id="myModal" class="modal">' +
'<div class="modal-content">' +
'<span class="close">×</span>' +
'<p>'+users[i].id+'</p>' +
'<p>'+users[i].name+'</p>' +
'</div>' +
'</div>';
}
//document.getElementById('users').innerHTML = output;
document.getElementById('user-list').innerHTML = output;
document.getElementById('myModal').style.display = "block"; //show modal
still_fetching = false;
}
}
xhr.send();
}
</script>
</body>
</html>
process.php
<?php
//Connect to a database
$conn = mysqli_connect('localhost','root','','ajaxtest');
echo 'Processing....';
//Check for POST variable
if(isset($_POST['name'])){
$name = mysqli_real_escape_string($conn, $_POST['name']);
//echo 'GET: Your name is '. $_POST['name'];
$query = "INSERT INTO users(name) VALUES('$name')";
if(mysqli_query($conn, $query)){
echo 'User Added...';
}else{
echo 'ERROR: '.mysql_error($conn);
}
}
//Check for GET variable
if(isset($_GET['name'])){
echo 'GET: Your name is '. $_GET['name'];
}
There are some problem in your code.
1. You check the name parameter:
if(isset($_GET['name']))
But you don't provide it when get.
xhr.open('GET', 'users.php', true);
Provide it.
xhr.open('GET', 'users.php?name=shingo', true);
2. The response isn't a JSON string:
echo 'GET: Your name is '. $_GET['name'];
JSON.parse(this.responseText);
Assuming your modal is using Bootstrap:
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">User List</h4>
</div>
<div class="modal-body" id="user-list">
<p>User list here</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Edit your JS function:
function loadUsers(){
var xhr = new XMLHttpRequest();
xhr.open('GET', 'users.php', true);
xhr.onload = function(){
if(this.status == 200){
var users = JSON.parse(this.responseText);
var output = '';
for(var i in users){
output +=
'<div>' +
'<p>'+users[i].id+'</p>' +
'<p>'+users[i].name+'</p>' +
'</div>';
}
//document.getElementById('users').innerHTML = output;
document.getElementById('user-list').innerHTML = output;
document.getElementById('myModal').style.display = "block"; //show modal
still_fetching = false;
}
}
xhr.send();
}

Modal box does not close on successfull ajax return

I have a modal window that pops up whenever a screen is ideal for 3 minutes. It asks for a PIN to be entered and there is a Continue button on that to be clicked after the PIN is entered in it. On using this Continue button, an insert is made in a database table. Now my problem here is on entering the PIN and clicking on Continue button, the modal does not hides or closes itself. Although the database insertion is done but the modal does not hides. What can be possibly going wrong in this. Any suggestion will be highly helpful. My code,
<div class="modal fade" id="myModal" role="dialog" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog">
<!-- Modal content-->
<form name="frmActive" id="frmActive" action="" method="post">
<div class="modal-content" style="height:250px;">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Ideal Time activation</h4>
</div>
<div class="modal-body">
<p>Please enter activation <b>PIN</b><font color="red">*</font><br>
<p id="msg" style="color:#F00;"></p>
<input type="password" name="pin" id="pin" value="" maxlength="4" onKeyUp="checkNumber(this)" class="form-control" placeholder="Enter Pin">
<input type="hidden" id="inactiveTime">
<p style="font-size:11px"><b><font color="red">*</font><font color="grey"><b>PIN</b><i> is mentioned in your welcome email.</font></i></b></p><br>
</div>
<div class="modal-footer">
<button type="button" id="btnSubmit" name="submit" value="submit" class="btn btn-success"><i class="glyphicon glyphicon-floppy-disk"></i> Continue</button>
<input type="hidden" id="module_id" value="<?php echo $moduleId ; ?>">
<input type="hidden" id="chapter_id" value="<?php echo $chapterId ; ?>">
</div>
</div>
</form>
</div>
</div>
jQuery("#btnSubmit").on("click", function(){
var pin = jQuery("#pin").val();
var chapter_id = jQuery("#chapter_id").val();
var module_id = jQuery("#module_id").val();
var nowDate = jQuery.now();
var inactiveTime = jQuery("#inactiveTime").val();
var seconds = (nowDate - inactiveTime) / 1000;
var formData = new FormData();
formData.append("pin", pin);
formData.append("seconds", seconds);
formData.append("module_id", module_id);
formData.append("chapter_id", chapter_id);
$.ajax({
url: "processActivation.php",
type: "POST",
data: formData,
processData: false,
contentType: false,
success: function(result){
if(result['status'] == 'active')
{
jQuery('#myModal').modal('hide');
}
else
{
$("#msg").html(result) ;
}
}
});
});
And processActivation.php,
<?php
$uid = $_SESSION['session_user_id'];
$dobCheck = $db->idToField("tbl_user", "dob", $uid);
$dob = explode("-", $dobCheck);
$pin = $_REQUEST['pin'];
$moduleId = $_REQUEST['module_id'];
$chapterId = $_REQUEST['chapter_id'];
$time_taken = $_REQUEST['seconds'];
$created = date("Y-m-d h:i:s");
if($pin != $dob[0])
{
echo "Please enter valid PIN."; die;
}
else
{
$dataactivation = array("user_id"=>$uid, "module_id"=>$moduleId, "chapter_id"=>$chapterId,"time_taken"=>$time_taken, "created"=>$created);
$db->query_insert("tbl_activation", $dataactivation);
header('Content-Type: application/json', true, 200);
echo json_encode(array('status' => 'active'));
exit();
}
?>
I want to know if
header('Content-Type: application/json', true, 200);
echo json_encode(array('status' => 'active'));
exit();
is the right way?? Because all of the above operations are being performed correctly and upon that console.log(result) does not shows up anything. Something wrong with the above couple of lines. Very helpful if somebody points out the error in this.
Use the hide function from jQuery.
jQuery('#myModal').hide();
As I know modal('hide') is used for bootstrap modals.
A quick fix maybe, instead of doing
echo json_encode(array('status' => 'active')); and if(result['status'] == 'active')
do
echo "active"; and if(result == 'active')
Use
jQuery('#myModal').toggle().click();
instead of
jQuery('#myModal').modal('hide');

Bootstrap Modal Not Running "showHint" Function

Please bear with me because I don't think I'm asking the right question in my title, but I have tons of code that I can share and hopefully you all can help me get on track. I'm hoping I'm just calling the wrong variable and I've just gone blind to my code.
I have a "dashboard" page that has a series of 10 bootstrap buttons. I've already created a modal that allows a user to lookup a "billing code" and depending on the result returned, the modal will expand to show the complete form and allow to add a new code or update an existing. I then duplicated the "billing code" files to create the modal for "client contact" information. When I click the button for the "client contact" modal, the dialog fires just fine, but when I type in an email address, nothing happens - whether the contact exists or not.
I've included the code for the dashboard, the working billing code modal and the not working client contact modal. I hope it's enough without being too much. Any and all help is greatly appreciated.
dashboard.php
<?php
session_start();
require_once('includes/config.php');
require_once('handlers/billing-code.handler.php');
require_once('handlers/clientContacts.handler.php');
if (!isset($_SESSION['loggedin'])) {
header("location: index.php?error=1");
}
$page->titleSet('Project Task List Dashboard');
// Load Classes
$admin = new Admin();
$projects = new Projects();
$helpers = new Helpers();
// run query to welcome user
$user = $_SESSION['user'];
$getUser = $helpers->genQuery("SELECT * FROM users WHERE userID = $user");
switch ($getUser[0]['userTypeID']) {
case 1:
$dashboard = 'includes/dashboards/super-admin-dashboard.php';
break;
case 2:
$dashboard = 'includes/dashboards/user-dashboard.php';
break;
case 3:
$dashboard = 'includes/dashboards/admin-dashboard.php';
break;
case 4:
$dashboard = 'includes/dashboards/mgr-dashboard.php';
break;
case 5:
$dashboard = 'includes/dashboards/pm-dashboard.php';
break;
}
// include the admin dashboard options based on user type
require_once($dashboard);
// run query to get short list of open upcoming due projects
$openProjects = $helpers->genQuery("SELECT * FROM projects WHERE completed = 0 LIMIT 0,10");
$page->contentSet('
<table width="90%" align="center" cellspacing="5" cellspacing="10" style="margin-bottom:20px;">
<tr>
<th>Project ID</th>
<th>Project Name</th>
<th align="left">Project Type</th>
<th align="left">Assigned To</th>
<th align="center">Due Date</th>
<th align="center">% Complete</th>
<th align="center">Status</th>
</tr>
');
foreach ($openProjects AS $projects) {
// alternating rows
$x++;
$rowColor = (($x%2 == 0) ? 'white-row-bg' : 'gray-row-bg');
// run query to get staff information
$staff = $helpers->genQuery("SELECT staffName FROM staff WHERE staffID = \"".$projects['staffID']."\"");
// run query to get project type information
$projectType = $helpers->genQuery("SELECT projectTypeName FROM projectType WHERE projectTypeID = \"".$projects['typeID']."\"");
// Calculate whether or not the project is on time
$ontime = $helpers->daysLeft($projects['dueDate']);
$icon = ($ontime > 0 ? "green" : "red");
$page->contentSet('
<tr class="'.$rowColor.'">
<td align="left">'.$projects['projectID'].'</td>
<td align="left">'. substr($projects['projectName'],0,30).(strlen($projects['projectName']) > 30 ? '...' : '').'</td>
<td align="left">'.$projectType[0]['projectTypeName'].'</td>
<td align="left">'.$staff[0]['staffName'].'</td>
<td align="center"><a href="#" title="View all projects that are due on '.date("n/j/Y",strtotime($projects['dueDate'])).'">'.date("n/j/Y",strtotime($projects['dueDate'])).'</td>
<td align="center">'.$projects['percentComplete'].'%</td>
<td align="center"><img src="images/'.$icon.'-light-icon.png" /></td>
</td>
</tr>
');
}
$page->contentSet('
</table>
');
include('modals/billing-codes-options-modal.php');
include('modals/client-contacts-options-modal.php');
display_page();
?>
working Billing Code Files
billing-codes-options-modal.php
<?php
session_start();
require_once('includes/config.php');
echo '
<script src="js/showHint.js" type="text/javascript" languag="javascript"></script>
';
$page->contentSet('
<!-- Modal -->
<div class="modal fade" id="addUpdateBillingCodes" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add/Update Billing Codes</h4>
<p>To add a new billing code, simply type the 6-digit code into the field below. If the code already exists, you will then have the opportunity to update the code\'s existing information; otherwise, you will be able to add the new code and its details. Click here for the complete list of billing codes.</p>
</div>
<div class="modal-body">
<form action="" method="post" name="billingCodes">
<p>
<label>Billing Code: </label>
<input type="text" name="billingCode" size="30" onchange="showHint(this.value)" /> <span style="cursor:hand;" class="glyphicon glyphicon-search"></span>
</p>
<span id="lookup">
</span>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
');
echo '
<script>
/* must apply only after HTML has loaded */
$(document).ready(function () {
$("#addUpdateBillingCodes").on("submit", function(e) {
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax({
url: formURL,
type: "POST",
data: postData,
success: function(data, textStatus, jqXHR) {
$(\'#addUpdateBillingCodes .modal-header .modal-title\').html("Result");
$(\'#addUpdateBillingCodes .modal-body\').html(data);
$("#addUpdateBillingCodes").remove();
},
error: function(jqXHR, status, error) {
console.log(status + ": " + error);
}
});
e.preventDefault();
});
$("#submitForm").on(\'click\', function() {
$("#addUpdateBillingCodes").submit();
});
});
</script>
';
?>
showHint.js
// JavaScript Document
function showHint(str) {
if (str.length == 0) {
document.getElementById("lookup").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("lookup").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "modals/lookups/billingCodelookup.php?q=" + str, true);
xmlhttp.send();
}
}
billing-code.handler.php
<?php
// load classes
$helpers = new Helpers();
$modals = new Modals();
// declare connection variable
$mysqli = new MySQLi(DB_HOST,DB_USER,DB_PASS,DB_BASE);
// declare errors array variable
$errors = array();
// scrub the data input
$billingCode = $helpers->escapePostValues($_POST['billingCode']);
$billingCodeDepartment = $helpers->escapePostValues($_POST['billingCodeDepartment']);
$billingCodeNickname = $helpers->escapePostValues($_POST['billingCodeNickname']);
// determine if this is a new billing code
if (isset($_POST['addBillingCode']) && $_POST['billingCodeAdd'] == 1) {
// add new billing code to table
$addBillingCodeQuery = "INSERT INTO billingCodes (billingCodeDepartment,billingCodeNickname,billingCode) VALUES ('".$billingCodeDepartment."','".$billingCodeNickname."','".$billingCode."')";
// if billing code has been added, display success message
if (mysqli_query($mysqli,$addBillingCodeQuery)) {
$errors['newrecord'] = '<p class="success center">Billing Code '.$billingCode.' has been successfully added.</p>';
}
}
if (isset($_POST['updateBillingCode']) && $_POST['billingCodeUpdate'] == 1) {
// update existing billing code information
$updateBillingCodeQuery = "UPDATE billingCodes SET billingCodeDepartment='$billingCodeDepartment', billingCodeNickname='$billingCodeNickname',billingCode='$billingCode' WHERE billingCode='$billingCode'";
// if the billing code information has been updated, display confirmation message
if (mysqli_query($mysqli,$updateBillingCodeQuery)) {
$errors['recordupdated'] = '<p class="success center">Billing Code '.$billingCode.' has been successfully updated.</p>';
}
}
?>
billingCodeLookup.php
<?php
session_start();
require_once('../../includes/config.php');
$helpers = new Helpers();
$billingCode = $_GET['q'];
$lookup = $helpers->genQuery("SELECT * FROM billingCodes WHERE billingCode=\"".$billingCode."\"");
echo '<p><label for="billingCodeDepartment">Department: </label><input type="text" name="billingCodeDepartment" value="'.$lookup[0]['billingCodeDepartment'].'" size="30" /></p>';
echo '<p><label for="billingCodeNickname">Nickname: </label><input type="text" name="billingCodeNickname" value="'.$lookup[0]['billingCodeNickname'].'" size="30" /></p>';
if ($lookup) {
echo '
<p>
<input type="hidden" name="billingCodeUpdate" value="1" />
<input type="submit" name="updateBillingCode" value="Update Billing Code" class="label-indent" />
</p>';
}
else {
echo '
<p>
<input type="hidden" name="billingCodeAdd" value="1" />
<input type="submit" name="addBillingCode" value="Add New Billing Code" class="label-indent" />
</p>';
}
?>
Not Working Client Contact Lookup Files
client-contact-options-modal.php
<?php
session_start();
require_once('includes/config.php');
// modal form for adding comments to a project
echo '
<script src="js/clientLookup.js" type="text/javascript" languag="javascript"></script>
';
$page->contentSet('
<!-- Modal -->
<div class="modal fade" id="addUpdateClientContacts" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add/Update Client Contacts</h4>
<p>To add a new contact, simply type in the email address of the contact into the field below. If the client contact already exists, you will then have the opportunity to update the contact\'s existing information; otherwise, you will be able to add the new contact and its details.</p>
</div>
<div class="modal-body">
<form action="" method="post" name="clientContacts">
<p>
<label for"clientContactEmail">Email Address: </label>
<input type="text" name="clientContactEmail" size="20" onchange="showHint(this.value)" /> <span style="cursor:hand;" class="glyphicon glyphicon-search"></span>
</p>
<span id="lookup">
</span>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
');
echo '
<script>
/* must apply only after HTML has loaded */
$(document).ready(function () {
$("#addUpdateClientContacts").on("submit", function(e) {
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax({
url: formURL,
type: "POST",
data: postData,
success: function(data, textStatus, jqXHR) {
$(\'#addUpdateClientContacts .modal-header .modal-title\').html("Result");
$(\'#addUpdateClientContacts .modal-body\').html(data);
$("#addUpdateClientContacts").remove();
},
error: function(jqXHR, status, error) {
console.log(status + ": " + error);
}
});
e.preventDefault();
});
$("#submitForm").on(\'click\', function() {
$("#addUpdateClientContacts").submit();
});
});
</script>
';
?>
clientContactLookup.php
<?php
session_start();
require_once('../../includes/config.php');
$helpers = new Helpers();
$email = $_GET['q'];
$lookup = $helpers->genQuery("SELECT * FROM clientContacts WHERE clientContactEmail=\"".$email."\"");
echo '
<p><label for="clientContactFirst">First name: </label><input type="text" name="clientContactFirst" value="'.$lookup[0]['clientContactFirst'].'" size="30" /></p>
<p><label for="clientContactLast">Last name: </label><input type="text" name="clientContactLast" value="'.$lookup[0]['clientContactLast'].'" size="30" /></p>
<p><label for="clientContactPhone">Phone: </label><input type="text" name="clientContactPhone" value="'.$lookup[0]['clientContactPhone'].'" size="30" /></p>
<p><label for="clientContactExt">Extension: </label><input type="text" name="clientContactExt" value="'.$lookup[0]['clientContactExt'].'" size="30" /></p>'
;
if ($lookup) {
echo '
<p>
<input type="hidden" name="clientContactUpdate" value="1" />
<input type="submit" name="updateClientContact" value="Update Client Contact" class="label-indent" />
</p>';
}
else {
echo '
<p>
<input type="hidden" name="clientContactAdd" value="1" />
<input type="submit" name="addClientContact" value="Add New Client Contact" class="label-indent" />
</p>';
}
?>
clientLookup.js
// JavaScript Document
function clientLookup(str) {
if (str.length == 0) {
document.getElementById("lookup").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("lookup").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "modals/lookups/clientContactLookup.php?q=" + str, true);
xmlhttp.send();
}
}
clientContacts.handler.php
<?php
// load classes
$helpers = new Helpers();
$modals = new Modals();
// declare connection variable
$mysqli = new MySQLi(DB_HOST,DB_USER,DB_PASS,DB_BASE);
// declare errors array variable
$errors = array();
// scrub the data input
$clientContactEmail = $helpers->escapePostValues($_POST['clientContactEmail']);
$clientContactFirst = $helpers->escapePostValues($_POST['clientContactFirst']);
$clientContactLast = $helpers->escapePostValues($_POST['clientContactLast']);
$clientContactPhone = $helpers->escapePostValues($_POST['clientContactPhone']);
$clientContactExt = $helpers->escapePostValues($_POST['clientContactExt']);
// determine if this is a new client contact
if (isset($_POST['addClientContact']) && $_POST['clientContactAdd'] == 1) {
// add new billing code to table
$addClientContactQuery = "INSERT INTO clientContacts (clientContactFirst,clientContactLast,clientContactPhone,clientContactExt,clientContactEmail) VALUES('".$clientContactFirst."','".$clientContactLast."','".$clientContactPhone."','".$clientContactExt."','".$clientContactEmail."')";
// if contact has been added, display success message
if (mysqli_query($mysqli,$addBillingCodeQuery)) {
$errors['newrecord'] = '<p class="success center">Contact information for '.$clientContactFirst.' '.$clientContactLast.' has been successfully added.</p>';
}
}
if (isset($_POST['updateClientContact']) && $_POST['clientContactUpdate'] == 1) {
// update existing client contact information
$updateClientContactQuery = "UPDATE clientContacts SET clientContactFirst='$clientContactFirst',clientContactLast='$clientContactLast',clientContactPhone='$clientContactPhone',clientContactExt='$clientContactExt',clientContactEmail='$clientContactEmail' WHERE clientContactEmail='$clientContactEmail'";
// if the contact information has been updated, display confirmation message
if (mysqli_query($mysqli,$updateClientContactQuery)) {
$errors['recordupdated'] = '<p class="success center">Contact information for '.$clientContactFirst.' '.$clientContactLast.' has been successfully updated.</p>';
}
}
?>
This actually wound up being a very simple fix: I didn't realize I was using the same span id in both modal files (). The onchange event now passes the id as a variable to the showHint function and the file structure has been reduced to requiring only one javascript file.

PHP Ajax Html on submit issues

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.

Categories