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.
Related
My target is, after I submit the form, there'll be a modal after reload that shows the transaction details. I have made a next page transaction details, however, it is much better to do the receipt php on onload modal after submission. But I don't know how to start. I provided a screenshot below of my current work. Any help will be appreciated. Thank you
View:
<button type="button" data-id="<?php echo $rows->userID; ?>" data-firstname="<?php echo $rows->firstname; ?>" class=" showmodal btn btn-success btn-sm text-bold " data-toggle="modal" data-target="#fundModal"><i class="fas fa-hand-holding-usd mr-1"></i> FUND </button> // This button shows modal when clicked
//This is my modal for transferring fund
<div class="modal fade" id="fundModal" tabindex="-1" role="dialog">
<div class="modal-dialog " role="document">
<div class="modal-content">
<div class="modal-header bg-green">
<h5 class="modal-title text-bold" id="exampleModalLabel">Fund</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body bg-white text-center">
<label><h3>Transfer fund:</h3></label>
<br>
<!-- FORM -->
<div id="errorMessage" style="color: red; display: none; font-size: 11px"></div>
<form method="POST" action="<?php echo site_url('network/form_validation');?>">
<div class="input-group input-group-sm" style="width: 100%" >
<input type="hidden" id="usertransferid" name="userID">
<input type="hidden" id="firstname" name="receiptname" value="<?php echo $rows->firstname; ?>">
<div class="col-lg-12" >
<input type="text" placeholder="Enter Amount" name="amount" autocomplete="new-amount" value="" class="form-control number" id="box" >
<br>
<?php echo $this->session->flashdata('warning'); ?>
<input type="password" placeholder="Enter Password" autocomplete="new-password" name="fundpass" class="form-control" id="password" required ">
<br>
<!-- buttons -->
<input type="submit" class="btn btn-success text-bold" name="save" id="insert" value="Transfer">
</div>
</div>
</form>
</div>
</div>
</div>
</div>
Controller:
public function form_validation()
{
$this->load->library('form_validation');
$this->form_validation->set_rules("amount","Amount", 'required|numeric');
$this->load->library('form_validation');
$this->form_validation->set_rules('fundpass', 'fundpass', 'callback_password_check');
if($this->form_validation->run() == false) {
echo '<script>alert("Invalid input of Password!");</script>';
redirect('network/agents', 'refresh');
}
else {
if($this->form_validation->run())
{
$ref= $this->session->userdata('uid') + time ();
$id = $this->input->post('userID');
$fname = $this->input->post('receiptname');
$pData = array(
'userID' => $id,
'transactionSource' => 'FR',
'refNumber' => 'FI' . $ref,
"amount" =>$this->input->post("amount"),
"transType" =>"in",
);
$this->networks->fundin($pData);
$ref= $this->session->userdata('userID') + time ();
$data1 = array(
'userID' => $this->session->userdata('uid'),
"transactionSource" => 'FR',
"refNumber" => 'FO' . $ref,
"amount" =>$this->input->post("amount"),
"transType" =>"out",
);
$this->networks->insert_data($data1);
// return json_encode($data1);
$_SESSION["amount"] = $this->input->post("amount");
$_SESSION["receivedID"] = $id;
$_SESSION["receiptFName"] = $fname;
$_SESSION["reference"] = $this->input->post("refNumber");
redirect(base_url() . "network/receipt");
}
else
{
$this->index();
}
}
}
public function password_check($fundpass)
{
$id = $this->session->userdata('uid');
if($this->session->userdata('password')!== md5($fundpass)) {
$this->form_validation->set_message('password_check', 'The {field} does not match');
return false;
}
return true;
}
Model:
function fundin($data)
{
// Fund in
$id = $this->input->post('userID');
$sqlInsertLedger = "INSERT INTO transaction_ledger (transactionSource, transType, refNumber, userID, amount, currentBalance, previousBalance, remarks, createdBy)
select '".$data['transactionSource']."', '".$data['transType']."', '".$data['refNumber']."', ".$data['userID'].", ".$data['amount'].", sum(TU.currentPoints + ".$data['amount'].") as totalPoints, TU.currentPoints,
'funded by agent', '".$this->session->userdata('uid')."'
from users TU where TU.userID=?";
$Q = $this->db->query($sqlInsertLedger, $data['userID']);
//update user table
$sqlUpdate = "update users set currentPoints = currentPoints + ? where userID = ?";
$Q = $this->db->query($sqlUpdate, array($data['amount'], $data['userID']));
}
function insert_data($data1)
{
// fund out
$sql1 = "select * from transaction_ledger where userID = ? order by ledgerID desc limit 0,1";
$Q1 = $this->db->query($sql1, $data1['userID']);
$R1 = $Q1->row_array();
$ref= $this->session->userdata('userID') + time ();
$idata1 = array(
'userID' => $data1['userID'],
'transactionSource' => 'FR',
'transType' => 'out',
'refNumber' => 'FO' . $ref,
'amount' => $data1['amount'],
'currentBalance' => $R1['currentBalance'] - $data1['amount'],
'previousBalance' => $R1['currentBalance'],
'remarks' => 'transfer fund to agent',
);
$this->db->insert('transaction_ledger', $idata1);
$sqlUpdate = "update users set currentPoints = '".$idata1['currentBalance']."', dateUpdated = '".date('Y-m-d h:i:s')."'where userID = ?";
$this->db->query($sqlUpdate, $idata1['userID'] );
}
You can programmatically open the bootstrap modal when document ready
Just like
$(document).ready(function(){
$("#fundModal").modal('show');
});
</script>
I would suggest to do with ajax call for better user experience.
$( "#formId" ).on('submit', function(e){
e.preventDefault();
let $form = $(this);
$.post( 'post-url-here', $form.serialize(), function(result) {
var result = JSON.parse(result);
if( result.status == 'success' ) {
$("#fundModal").modal('show');
}
});
});
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
}
?>
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');
I am loading record details into a modal allowing the user to edit. What I am trying to achieve is to have the user update the record in the modal and then submit to the MySQL table via AJAX / jQuery, however, afte pressing the "Save Changes" button nothing happens. I checked the JS Query and can confirm that the button is linked correctly and also managed to update the database when directly addressing the PHP update script. Not sure why the script refuses to start
Modal:
<div id="output"></div>
<!-- Modal MYMODAL -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Edit Record</h4>
</div>
<div class="modal-body">
<!-- ID No. -->
<div class="form-group">
<label>ID No.:</label>
<input type="number" class="form-control" id="dataPID" name="dataPID" size="5" disabled />
</div>
<!-- /.id number -->
<!-- Category -->
<div class="form-group">
<label>Category:</label>
<input type="text" class="form-control" id="dataCat" name="dataCat" />
</div>
<!-- /.category -->
<!-- Issue -->
<div class="form-group">
<label>Issue:</label>
<input type="text" class="form-control" id="dataIssue" name="dataIssue" />
</div>
<!-- /.issue -->
<!-- Department Responsible -->
<div class="form-group">
<label>Department Responsible:</label>
<input type="text" class="form-control" id="dataDeptResp" name="dataDeptResp" />
</div>
<!-- /.department responsible -->
<!-- Experience -->
<div class="form-group">
<label>Experience:</label>
<input type="text" class="form-control" id="dataExp" name="dataExp" />
</div>
<!-- /.experience -->
<!-- textarea -->
<div class="form-group">
<label>Description:</label>
<textarea class="form-control" id="dataDesc" name="dataDesc" rows="3" ></textarea>
</div>
</div>
<div class="modal-footer">
<button type="button" id="SaveChanges" name="SaveChanges" class="btn btn-primary">Save Changes</button>
<button type="button" id="DeleteRecord" name="DeleteRecord" class="btn btn-danger">Delete Record</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- /.Modal MYMODAL -->
Javascript:
$("#SaveChanges").click(function() {
$.ajax({
type: "POST",
url: "plugins/MySQL/ajax_action.php",
data: { action:"update_mysqli",PID:$("#dataPID").val(), Category:$("#dataCat").val(), Issue:$("#dataIssue").val(), Department_Responsible:$("#dataDeptResp").val(), Experience:$("#dataExp").val(), Description:$("#dataDesc").val()}, //your form data to post goes here as a json object
dataType: "json",
contentType:"text",
success: function(data) {
$('#output').html(data);
drawVisualization();
},
});
});
ajax_action.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
if(isset($_POST['action']) && ($_POST['action']=='update_mysqli')) {
// include connection details
include 'connect_db.php';
//Open a new connection to the MySQL server
$db = new mysqli($dbhost,$dbuser,$dbpass,$dbname);
//Output any connection error
if ($db->connect_error) {
die('Error : ('. $db->connect_errno .') '. $db->connect_error);
}
// get variables and sanitize
$pid = mysqli_real_escape_string($db,$_POST['PID']);
$cat = mysqli_real_escape_string($db,$_POST['Category']);
$issue = mysqli_real_escape_string($db,$_POST['Issue']);
$dept_resp = mysqli_real_escape_string($db,$_POST['Department_Responsible']);
$exp = mysqli_real_escape_string($db,$_POST['Experience']);
$desc = mysqli_real_escape_string($db,$_POST['Description']);
// check if record exists based on ID number
$result = $db->query("SELECT * FROM qci_problems_index_new WHERE PID='".$pid."'");
// if record is found, update accordingly
if ($result->num_rows > 0){
$sql = "UPDATE qci_problems_index_new SET Category = '$cat', Issue = '$issue', Department_Responsible = '$dept_resp', Experience = '$exp', Description = '$desc' WHERE PID = '$pid'";
if (!$db->query($sql)) {
echo "Error - Update of record PID " . $pid . " failed: (" . $db->errno . ") " . $db->error;
}
} else {
// if no record with relevant PID is found, create new record
$sql = "INSERT INTO `qci_problems_index_new`(`PID`, `Category`, `Issue`, `Department_Responsible`, `Experience`, `Description`) VALUES ('".$pid."', '".$cat."', '".$issue."', '".$dept_resp."', '".$exp."', '".$desc."')";
if (!$db->query($sql)) {
echo "Error - could not insert new record: (" . $db->errno . ") " . $db->error;
}
}
echo "Success, record updated successfully";
//close connection
$db->close();
}
EDIT 1:
Chrome Console says the following:
EDIT 2:
updated code
Change you data type to json and content type to text,add your get variable to the post request
$("#SaveChanges").click(function() {
$.ajax({
type: "POST",
url: "plugins/MySQL/ajax_action.php",
data: { action:"update_mysqli",PID:$("#dataPID").val(), Category:$("#dataCat").val(), Issue:$("#dataIssue").val(), Department_Responsible:$("#dataDeptResp").val(), Experience:$("#dataExp").val(), Description:$("#dataDesc").val()}, //your form data to post goes here as a json object
dataType: "json",
contentType:"text",
success: function(data) {
$('#output').html(data);
drawVisualization();
},
});
});
php
if(isset($_POST['action']) && ($_POST['action']=='update_mysqli')) {
You are passing the value "update_mysql" in "action" parameter in the ajax URL(plugins/MySQL/ajax_action.php?action=update_mysql). On the other hand your condition in ajax_action.php will only be executed the code if the value of "action" parameter is "update_mysqli"
Change the following line
if(isset($_GET['action']) && ($_GET['action']=='update_mysqli'))
to
if(isset($_GET['action']) && ($_GET['action']=='update_mysql'))
in your ajax_action.php file.
OR
Alternatively, you can pass value update_mysqli instead of update_mysql for your action parameter in ajax call.
Since you are using mysqli, you will prefer this for the sake of best practice as you are using mysqli functions inside code.
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.