PHP Ajax Html on submit issues - javascript

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.

Related

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

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
}
?>

How to send the selected value of a drop down menu to an email?

I have an question that send the selected value of a drop down menu to an email in php. I already send the text values to a email. But I did not know how to send the drop down menu value to a email. I did some code. But it does not work. Could anyone support me.
Here is the php, HTML and JS code.
php code...
<?php
if(isset($_POST['contactFrmSubmit']) && !empty($_POST['name']) && !empty($_POST['email']) && (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false) && !empty($_POST['message'])){
// Submitted form data
$name = $_POST['name'];
$email = $_POST['email'];
$message= $_POST['message'];
/*
* Send email to admin
*/
$to = 'support#ribelz.net';
$subject= 'Contact Request of privateeyelk.com';
$htmlContent = '
<h4>Contact request from : '.$email.'</h4>
<p>Name: '.$name.'</p>
<p>Email: '.$email.'</p>
<p>Message: '.$message.'</p>
';
// Set content-type header for sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
// Additional headers
$headers .= 'From: Private Eye<privateeyelk.com>' . "\r\n";
// Send email
if(mail($to,$subject,$htmlContent,$headers)){
$status = 'ok';
}else{
$status = 'err';
}
// Output status
echo $status;die;
}
?>
HTML code...
<!-- Contact form -->
<div class="modal fade" id="modalForm" role="dialog" style="width: 100%;">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true">×</span>
<span class="sr-only">Close</span>
</button>
<h4 class="modal-title" id="myModalLabel">Contact Form</h4>
</div>
<!-- Modal Body -->
<div class="modal-body">
<p class="statusMsg"></p>
<form role="form">
<div class="form-group">
<label for="inputName">Name</label>
<input type="text" class="form-control" id="inputName" placeholder="Enter your name" style="border: 1px solid #fff; border-bottom: 1px solid #ccc;"/>
</div>
<div class="form-group">
<label for="inputEmail">Email</label>
<input type="email" class="form-control" id="inputEmail" placeholder="Enter your email"/>
</div>
<div class="form-group">
<label for="inputMessage">Message</label>
<textarea class="form-control" id="inputMessage" placeholder="Enter your message"></textarea>
</div>
<div class="form-group">
<label for="inputMessage">Services</label>
<select name="size" class="form-control"
id="inputService" size="1">
<option value="Option1">Pr-Matrimonial Services</option>
<option value="Option2">Extra Marital Affairs</option>
<option value="Option3">Divorce Case Support</option>
</select>
</div>
</form>
</div>
<!-- Modal Footer -->
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary submitBtn" onclick="submitContactForm()">SUBMIT</button>
</div>
</div>
</div>
</div>
JS code...
<script>
function submitContactForm(){
var usernameRegex = /^[a-zA-Z0-9]+$/;
var reg = /^[A-Z0-9._%+-]+#([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
var name = $('#inputName').val();
var email = $('#inputEmail').val();
var message = $('#inputMessage').val();
var service = $('#inputService').val();
if(name.trim() == '' ){
alert('Please enter your name.');
$('#inputName').focus();
return false;
}else if(name.trim() != '' && !usernameRegex.test(name)){
alert('Please enter valid name.');
$('#inputName').focus();
return false;
}else if(email.trim() == '' ){
alert('Please enter your email.');
$('#inputEmail').focus();
return false;
}else if(email.trim() != '' && !reg.test(email)){
alert('Please enter valid email.');
$('#inputEmail').focus();
return false;
}else if(message.trim() == '' ){
alert('Please enter your message.');
$('#inputMessage').focus();
return false;
}else if(service.trim() == '' ){
alert('Please select your service.');
$('#inputService').focus();
return false;
}else{
$.ajax({
type:'POST',
url:'contact.php',
data:'contactFrmSubmit=1&name='+name+'&email='+email+'&message='+message+'&service='+service,
beforeSend: function () {
$('.submitBtn').attr("disabled","disabled");
$('.modal-body').css('opacity', '.5');
},
success:function(msg){
if(msg == 'ok'){
$('#inputName').val('');
$('#inputEmail').val('');
$('#inputMessage').val('');
$('#inputService').val('');
$('.statusMsg').html('<span style="color:green;">Thanks for contacting us, we\'ll get back to you soon.</p>');
}else{
$('.statusMsg').html('<span style="color:red;">Some problem occurred, please try again.</span>');
}
$('.submitBtn').removeAttr("disabled");
$('.modal-body').css('opacity', '');
}
});
}
}
</script>
Just add a new variable:
$value_from_dropdown = $_POST['your_select_name'];
Then you can use that variable in your script like you do for any other variable

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.

Javascript getting into infinite loop

When i unchecked the input checkboxes the share.php javascript goes into an infinite loop opening new windows.
with all 3 checked no problem occur.
in some point it is going wrong but i cant find where.
Im not sure why it is happening
<form action="functions/share.php" method="POST" target="_blank">
<p>
<textarea class="form-control" style="resize: none;height: 90px;padding: 10px;border-radius: 3px;" name="summary" required>Build a fully customizable Personal Website in seconds - for free.</textarea>
</p>
<div class="text-center">
<input type="checkbox" name="LinkedIn" value="yes" checked><i class="fa fa-linkedin"></i>
<input type="checkbox" name="FaceBook" value="yes" checked><i class="fa fa-facebook"></i>
<input type="checkbox" name="Twitter" value="yes" checked><i class="fa fa-twitter"></i>
</div>
<p><input type="submit" class="btn btn-primary btn-lg btn-block" value="Share" ></p>
</form>
share.php
<?php
if(isset($_POST['summary'])){
$linkedIn = "";
$faceBook = "";
$twitter = "";
if($_POST['LinkedIn'] == "yes"){
$linkedIn = "http://www.linkedin.com/";
}
if($_POST['FaceBook'] == "yes"){
$faceBook = "http://www.facebook.com/";
}
if($_POST['Twitter'] == "yes"){
$twitter = "http://www.twitter.com/";
}
}
?>
<html>
<body>
<div id="linkedin" style="display: none;">
<?php
echo htmlspecialchars($linkedIn);
?>
</div>
<div id="facebook" style="display: none;">
<?php
echo htmlspecialchars($faceBook);
?>
</div>
<div id="twitter" style="display: none;">
<?php
echo htmlspecialchars($twitter);
?>
</div>
<script>
var div = document.getElementById("linkedin");
var linkedin= div.textContent;
var div = document.getElementById("facebook");
var faceBook= div.textContent;
var div = document.getElementById("twitter");
var twitter= div.textContent;
if(linkedin != " "){
window.open(linkedin);
};
if(faceBook != " "){
window.open(faceBook);
};
if(twitter != " "){
window.open(twitter);
};
close();
</script>
</body>
</html>
First thing,You must change the checking sentence from
if($_POST['LinkedIn'] == "yes")
to
if(isset($_POST['LinkedIn']))
Second thing,you must remove the close sentence in your JS code close();
when you make those two changes, the checked links will open. If there were a box that is not checked then a window will open with link http://localhost/functions/share.php. to solve this problem declare the links inside the 'JS' code.
Your final code:
<?php
if(isset($_POST['summary'])){
$linkedIn = "";
$faceBook = "";
$twitter = "";
if(isset($_POST['LinkedIn']))
$linkedIn = htmlspecialchars("http://www.linkedin.com/");
else
$linkedIn = "";
if(isset($_POST['FaceBook']))
$faceBook = htmlspecialchars("http://www.facebook.com/");
else
$faceBook = "";
if(isset($_POST['Twitter']))
$twitter = htmlspecialchars("http://www.twitter.com/");
else
$twitter = "";
}
?>
<html>
<body>
<script>
var linkedin= "<?php echo $linkedIn; ?>";
var faceBook= "<?php echo $faceBook; ?>";
var twitter= "<?php echo $twitter; ?>";
if(linkedin != "")
window.open(linkedin);
if(faceBook != "")
window.open(faceBook);
if(twitter != "")
window.open(twitter);
//close();
</script>
</body>
</html>

Categories