editing multiple users using modal form (javascript, html) - javascript

Hi guys the issue I have is within my users admin page, I have displayed all the admin users within a table each assigned a delete and edit button.
When I click on edit the given users details appear in a modal form. Within the edit details there is a password and confirm password box, when I click on the edit details for the first user, the validation for confirm password appears as "passwords don't match" however when I click on the second user the confirm password does not validate.
Below is the source code I am having issues with any help will be much appreciated:
<a rel="tooltip" title="Edit" id="e<?php echo $id; ?>" href="#edit<?php echo $id; ?>" data-toggle="modal" class="btn btn-success"></i>Edit</a>
<div id="edit<?php echo $id;?>" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-body">
<div class="alert alert-info"><strong>Edit User</strong></div>
<form class="form-horizontal" method="post">
<div class="control-group">
<label class="control-label" for="inputEmail">Firstname</label>
<div class="controls">
<input type="text" id="inputEmail" name="firstname" value="<?php echo $row['firstname']; ?>" required>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputEmail">Lastname</label>
<div class="controls">
<input type="text" id="inputEmail" name="lastname" value="<?php echo $row['lastname']; ?>" required>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputEmail">Mobile Number</label>
<div class="controls">
<input type="text" id="inputEmail" name="mobilenumber" value="<?php echo $row['mobilenumber']; ?>" required>
</div>
</div>
<input type="hidden" id="inputEmail" name="id" value="<?php echo $row['admin_id']; ?>" required>
<div class="control-group">
<label class="control-label" for="inputPassword">Password</label>
<div class="controls">
<input type="text" name="password" id="password" required>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword">Confirm Password</label>
<div class="controls">
<input type="text" name="confirmpassword" id="confirmpassword" required>
</div>
</div>
<div class="control-group">
<div class="controls">
<button name="edit" type="submit" class="btn btn-success"> Update</button>
</div>
</div>
<script type="text/javascript">
window.onload = function () {
document.getElementById("password").onchange = validatePassword;
document.getElementById("confirmpassword").onchange = validatePassword;
}
function validatePassword(){
var confirmpassword=document.getElementById("confirmpassword").value;
var password=document.getElementById("password").value;
if(password!=confirmpassword)
document.getElementById("confirmpassword").setCustomValidity("Passwords Don't Match");
else
document.getElementById("confirmpassword").setCustomValidity('');
//empty string means no validation error
}
</script>
</form>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true"> Close</button>
</div>
</div>
<?php
if (isset($_POST['edit'])){
$admin_id=$_POST['id'];
$firstname=$_POST['firstname'];
$lastname=$_POST['lastname'];
$mobilenumber=$_POST['mobilenumber'];
$password= sha1 ($_POST['password']);
mysql_query("update admin set firstname = '$firstname', lastname = '$lastname', mobilenumber = '$mobilenumber', password = '$password' where admin_id='$admin_id'")or die(mysql_error()); ?>
<script>
window.location="adminusers.php";
</script>
<?php
}
}
?>
Validation issue
Validation issue 2

Related

i have problem with my javascript on codeigniter, parse to javascript

i have some problem, i want to push my data to form html with javascript obj but it can't push with id
this is my javascript
{if {form_case} == ubah}
<script type="text/javascript">
var data={data_by_id};
for (var obj in data)
{
alert(data[obj]);
$("#" + obj).val(data[obj]);
}
</script> {/if}
this my form html
<form class="form" form-case="{form_case}">
<div class="form-group">
<label for="Nama">Nama</label>
<input type="text" class=" riset form-control" id="nama_user" name="nama_user" placeholder="">
<div>
<?php print form_error('nama_user', '<small class="text-danger">', '</small>') ?>
</div>
</div>
<div class="form-group">
<label for="Username">Username</label>
<input type="text" class="form-control" id="username" name="username">
<div>
<?php print form_error('username', '<small class="text-danger">', '</small>') ?>
</div>
</div>
<div class="form-group">
<label for="Password">Password</label>
<input type="password" class="form-control" id="password" name="password">
<div>
<?php print form_error('password', '<small class="text-danger">', '</small>') ?>
</div>
</div>
<div class="form-group">
<div class="float-right">
<button class="btn btn-sm btn-primary" name="simpan" data-link="{base_url}/{lvl_auth}/{base_class}/store">Simpan</button>
<button type="reset" class="btn btn-sm btn-success" name="reset">Reset</button>
</div>
</div>
</form>
this my result in inspect element
enter image description here
then this ini my result on html it can't show the value in field
enter image description here

Prevent Bootstrap Model from Closing after Submit Button

I want to prevent my Modal window to close after I push submit Form button.
I tried a different kind of ways jquery/credform/javascript etc and nothing gave me the result I want.
Inside my Modal, as you can see I have a Form with different things. All fields are requested by my PHP server.
Please help me out with this. I want it after I push submit to remain open so the user that completes the form get's a message inside a box that I made there
$('#myModal').on('hidden.bs.modal', function() {
this.modal('show');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Comanda prin Email</h4>
</div>
<div class="modal-body">
<?php include('forms.php'); ?>
<div class="container">
<form id="contact" action="<?= htmlspecialchars($_SERVER["PHP_SELF"]) ?>" method="post">
<div class=""><p style="text-align: center;">Dupa plasarea comenzi in maximum 24 ore ve-ti fi contactat Telefonic pentru confirmarea acesteia!!!</p></div>
<fieldset>
<sup>*</sup>
<input placeholder="Nume Produs" type="text" name="numeprodus" value="<?= $numeprodus ?>" tabindex="1" autofocus>
<span class="error"><?= $numeprodus_error ?></span>
</fieldset>
<fieldset>
<sup>*</sup>
<input placeholder="Marimea" type="text" name="marime" value="<?= $marime_produs ?>" tabindex="2" autofocus>
<span class="error"><?= $marime_error ?></span>
</fieldset>
<fieldset>
<sup>*</sup>
<input placeholder="Numele" type="text" name="nume" value="<?= $nume ?>" tabindex="3" autofocus>
<span class="error"><?= $nume_error ?></span>
</fieldset>
<fieldset>
<sup>*</sup>
<input placeholder="Prenumele" type="text" name="prenume" value="<?= $prenume ?>" tabindex="4" autofocus>
<span class="error"><?= $prenume_error ?></span>
</fieldset>
<fieldset>
<sup>*</sup>
<input placeholder="Adresa" type="text" name="adresa" value="<?= $adresa ?>" tabindex="5" autofocus>
<span class="error"><?= $adresa_error ?></span>
</fieldset>
<fieldset>
<sup>*</sup>
<input placeholder="Oras" type="text" name="oras" value="<?= $oras ?>" tabindex="6" autofocus>
<span class="error"><?= $oras_error ?></span>
</fieldset>
<fieldset>
<sup>*</sup>
<input placeholder="Cod Postal" type="text" name="codpostal" value="<?= $codpostal ?>" tabindex="7" autofocus>
<span class="error"><?= $codpostal_error ?></span>
</fieldset>
<fieldset>
<sup>*</sup>
<input placeholder="Email" type="text" name="email" value="<?= $email ?>" tabindex="8">
<span class="error"><?= $email_error ?></span>
</fieldset>
<fieldset>
<sup>*</sup>
<input placeholder="Numar Telefon" type="text" name="telefon" value="<?= $telefon ?>" tabindex="9">
<span class="error"><?= $telefon_error ?></span>
</fieldset>
<fieldset>
<textarea value="<?= $message ?>" name="message" tabindex="10">
</textarea>
</fieldset>
<fieldset>
<button name="submit" type="submit" id="contact-submit" data-submit="...Sending">Submit</button>
</fieldset>
<div class="success"><?= $success ?></div>
</form>
</div>
</div>
<div class="dv-atentionare"><p class="dv-att-p1">Atentie!</p><p class="dv-att-p2">Aveti la dispozitie 48 ore de la plasarea comenzi pentru a o putea anula!</p></div>
<div class="modal-footer">
<input class="btn btn-default">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
Thank you in advance!
Ok, so there are two solutions for this.
Use JQuery AJAX to submit form, and prevent default form behaviour. Link
Reopen the Modal, when form is returned from server. I might not be able to give you any PHP code for this but I have done this in Asp.Net MVC.
When you post your data to PHP, return some flag from there. Then you can use that flag to turn following script on/off.
// PHP if($some_flag == true)
<script>
$(document).ready(function(){
$('#myModal').modal('show');
})
</script>
// PHP endif
According to the docs data-dismiss="modal" is to dismiss the modal when the button is clicked.
Removing this attribute should stop the modal from closing when the button is clicked.

Get the value of textbox then pass to another modal

I want to get the value of a textbox (the value of order_id, to be more specific) from ordermodal.php then pass it to ordermodal2.php. In order to use it in my query.
This is my code for ordermodal.php
include_once 'ordermodal2.php';
/** *ordermodal.php **/
$id = "";
$order_date = "";
$order_time = "";
$order_id = "";
$order_deliverCharge = "";
$order_status = "";
$order_totalAmount= "";
$coordinates = "";
$driver_number = "";
$address = "";
$food_name="";
$special_request="";
$quantity="";
$amount="";
$orders="";
?>
<!-- MODALS --> <!-- DETAILS -->
<div id="myModal" class="modal fade" role="dialog" style="z-index: 1400;">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<form action="" method="post" class="form-horizontal">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><center>×</button>
<h4 class="modal-title" id="titleModal">Order Information</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="order_id" class="col-sm-2 control-label">Order ID</label>
<div class="col-lg-3">
<input type="text" input style="width:500px" class="form-control" name="ORDER_ID" id="ORDER_ID" placeholder="" value="" required="required" readonly>
</div>
</div>
<div class="form-group">
<label for="id" class="col-sm-2 control-label">User ID</label>
<div class="col-lg-3">
<input type="text" input style="width:500px" class="form-control" name="user_id" id="user_id" placeholder="" value="" required="required" readonly>
</div>
</div>
<div class="form-group">
<label for="order_date" class="col-sm-2 control-label">Order Date</label>
<div class="col-lg-3">
<input type="text" input style="width:500px" class="form-control" name="order_date" id="order_date" placeholder="" value="" required="required" readonly>
</div>
</div>
<div class="form-group">
<label for="order_time" class="col-sm-2 control-label">Order Time</label>
<div class="col-lg-3">
<input type="text" input style="width:500px" class="form-control" name="order_time" id="order_time" placeholder="" value="" required="required" readonly>
</div>
</div>
<div class="form-group">
<label for="order_deliverCharge" class="col-sm-2 control-label">Delivery Charge</label>
<div class="col-lg-3">
<input type="text" input style="width:500px" class="form-control" name="order_deliveryCharge" id="order_deliveryCharge" placeholder="" value="" required="required" readonly>
</div>
</div>
<div class="form-group">
<label for="order_totalAmount" class="col-sm-2 control-label">Total Amount</label>
<div class="col-lg-3">
<input type="text" input style="width:500px" class="form-control" name="order_totalAmount" id="order_totalAmount" placeholder="" value="" required="required" readonly>
</div>
</div>
<div class="form-group">
<label for="address" class="col-sm-2 control-label">Address</label>
<div class="col-lg-3">
<input type="text" input style="width:500px" class="form-control" name="address" id="address" placeholder="" value="" required="required" readonly>
</div>
</div>
<div class="form-group">
<label for="coordinates" class="col-sm-2 control-label">Coordinates</label>
<div class="col-lg-3">
<input type="text" input style="width:500px" class="form-control" name="coordinates" id="coordinates" placeholder="" value="" required="required" maxlength="11" readonly>
</div>
</div>
<div class="form-group">
<label for="driver_number" class="col-sm-2 control-label">Driver Number</label>
<div class="col-lg-3">
<input type="text" input style="width:500px" class="form-control" name="driver_number" id="driver_number" placeholder="" value="" required="required" readonly>
</div>
</div>
<div class="form-group">
<label for="order_status" class="col-sm-2 control-label">Order Status</label>
<div class="col-lg-3">
<input type="text" input style="width:500px" class="form-control" name="order_status" id="order_status" placeholder="" value="" required="required" readonly>
</div>
</div>
<?php
$order_id = trim(addslashes($_POST['ORDER_ID']));
$sql = "SELECT food_name, special_request, quantity, amount
FROM cart_tbl
WHERE order_id=$order_id";
$result = mysqli_query(connection(), $sql);
?>
<table class="table table-hover table-bordered">
<thead>
<tr>
<th>Food</th>
<th>Special Request</th>
<th>Quantity</th>
<th>Amount</th>
</tr>
</thead>
<?php
if(mysqli_num_rows($result)>0)
{
while($row = mysqli_fetch_array($result))
{
?>
<tr>
<td><?php echo $row["food_name"];?></td>
<td><?php echo $row["special_request"];?></td>
<td><?php echo $row["quantity"];?></td>
<td><?php echo $row["amount"];?></td>
</tr>
<?php
}
}
?>
</table>
<tbody>
</div>
<div class="modal-footer">
<button type="submit" input style="background-color:#4CAF50;color:white" name="submitDelivered" id="submitDelivered" class="btn btn-primary " onclick="if(!confirm('Are you sure you want to deliver order?')){return false;}" > Delivered </button>
<button type="submit" input style="background-color:#0000FF;color:white" name="submitAccept" id="submitAccept" class="btn btn-primary" onclick="if(!confirm('Are you sure you want to accept order?')){return false;}" > Accept </button>
<button type="button" style="background-color:#FFFF00;color:black" class="btn btn-success" data-toggle="modal" data-target="#myDropdown" onclick="send('<?= $_POST['ORDER_ID'] ?>')"> Send </button>
<button type="submit" input style="background-color:#f44336;color:white" name="submitCancel" class="btn btn-danger" onclick="if(!confirm('Are you sure you want to cancel order?')){return false;}">Cancel</button>
<?php
if(isset($_POST['submitDelivered'])){
$ororder_id = trim(addslashes($_POST['ORDER_ID']));
$query = "UPDATE order_tbl SET `order_status`='Delivered' WHERE `order_id` = $order_id";
if (mysqli_query(connection(), $query)) {
mysqli_query(connection(), "COMMIT");
$_SESSION['message'] = "Order Delivered"; }
else {
$_SESSION['message'] = mysqli_error(connection());
mysqli_query(connection(), "ROLLBACK");
}
}
if(isset($_POST['submitAccept'])){
$order_id = trim(addslashes($_POST['ORDER_ID']));
$query = "UPDATE order_tbl SET `order_status`='Accepted' WHERE `order_id` = $order_id";
if (mysqli_query(connection(), $query)) {
mysqli_query(connection(), "COMMIT");
$_SESSION['message'] = "Order Accepted"; }
else {
$_SESSION['message'] = mysqli_error(connection());
mysqli_query(connection(), "ROLLBACK");
}
}
if(isset($_POST['submitCancel'])){
$order_id = trim(addslashes($_POST['ORDER_ID']));
$query = "UPDATE order_tbl SET `order_status`='Cancelled' WHERE `order_id` = $order_id";
if (mysqli_query(connection(), $query)) {
mysqli_query(connection(), "COMMIT");
$_SESSION['message'] = "Order Cancelled"; }
else {
$_SESSION['message'] = mysqli_error(connection());
mysqli_query(connection(), "ROLLBACK");
}
}
?>
</div>
</form>
</div>
</div>
</div>
<script>
function send(order_id) {
document.getElementById("titleModal2").innerHTML = "Choose Driver";
document.getElementsByName("ORDER_ID_MODAL_2")[0].setAttribute("value", order_id);
document.getElementsByName("send")[0].setAttribute("name", "send");
}
</script>
And this is the code for my ordermodal2.php
<!-- Modal -->
<div class="modal fade" id="myDropdown" role="dialog" style="z-index: 1600;">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<form action="" method="post" class="form-horizontal">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">× </button>
<h4 class="modal-title" id="titleModal2">Choose Driver</h4>
</div>
<div class="modal-body" >
<div class="form-group">
<label for="order_id" class="col-sm-2 control-label">Order ID</label>
<div class="col-lg-3">
<input type="text" input style="width:450px" class="form-control" name="ORDER_ID_MODAL_2" id="ORDER_ID_MODAL_2" placeholder="" value="" required="required" readonly>
</div>
</div>
<strong> Select Driver : </strong>
<select name="empName">
<option value=""> -----------ALL----------- </option>
<?php
$databaseHost = "localhost";
$databaseUser = "";
$databasePassword = "";
$databaseName = "";
$con=mysql_connect($databaseHost ,$databaseUser ,$databasePassword )or die ('Connection Error');
mysql_select_db("",$con) or die ('Database Error');
$dd_res=mysql_query("SELECT driver_number FROM driver_tbl");
while($r=mysql_fetch_row($dd_res))
{
echo "<option value='$r[0]'> $r[0] </option>";
}
?>
</select>
</div>
<div class="modal-footer">
<button type="submit" input style="background-color:#FFFF00;color:black" name="send" class="btn btn-primary"onclick="if(!confirm('Are you sure you want to send order?')){return false;}" >Confirm!</button>
<?php
if(isset($_POST['send'])){
$order_id = trim(addslashes($_POST['ORDER_ID_MODAL_2']));
$query = "UPDATE order_tbl SET `order_status`='Dispatched' WHERE `order_id` = $order_id";
if (mysqli_query(connection(), $query)) {
mysqli_query(connection(), "COMMIT");
$_SESSION['message'] = "Order Dispatched"; }
else {
$_SESSION['message'] = mysqli_error(connection());
mysqli_query(connection(), "ROLLBACK");
}
}
?>
</div>
</form>
</div>
</div>
</div>
The output will be: when I click the send button in ordermodal then the ordermodal2 will popup obviously,then the Order Id textbox have a value in it already when send button from ordermodal is clicked(the value is same with the ordermodal.php) then when i click the send button in ordermodal2(this is where i need that value) it will change the driver status to dispatched. I hope you can help me with my problem. TIA!
From reading your code, it looks like it should be simple.....
Change
document.getElementsByName("ORDER_ID_MODAL_2")[0].setAttribute("value", order_id);
To
document.getElementsByName("ORDER_ID_MODAL_2")[0].value('<?php echo $order_id?>');

how can i validate the checkbox?

<form target="_self" id="immunization_info_form" class="form-validation save_immune25 update_immune25" role="form" method="POST" enctype="multipart/form-data">
<div class="form-group row" style="margin-top:10px;height:50px;">
<div class="checkbox checkbox-styled col-md-offset-1 col-md-4">
<label style="font-size:15px;"><input type="checkbox" id="checkbox25" name="ch" class="checkbx" value="25">
<span>Hepatitis A vaccine</span></label>
</div>
<div class="form-group col-md-4">
<!-- Date input -->
<input class="form-control edit25" id="date25" name="date" placeholder="Enter Date" value="<?php echo $date[25]; ?>" type="text" required>
</div>
</div>
<div class="row" style="padding:15px;">
<div class="col-md-3 col-md-offset-1">
<div class="form-group">
<h3 style="color:orange;">Clinic Name</h3><br>
<input name="clinic_name" id="clinic" class="form-control edit25" type="text" value="<?php echo $clinic_name[25]; ?>" required>
<label for="clinic_name"></label>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<h3 style="color:orange;">Name of the Health practitioner</h3><br>
<input name="hp_name" id="hp" class="form-control edit25" type="text" value="<?php echo $practitioner[25]; ?>" required>
<label for="hp_name"></label>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<h3 style="color:orange;">Lot no. of Vaccine</h3><br>
<input name="lotno" id="lot" class="form-control edit25" type="text" value="<?php echo $lotno[25]; ?>" required>
<label for="lotno"></label>
</div>
</div>
<div class="row col-md-offset-1">
<div class="col-md-6 text-right">
<input type="button" name="submit" value="SAVE" class="save btn btn-lg btn-primary ink-reaction justify" id="save_immune25">
</div>
</div>
</div>
</form>
i have added my html code also..
$('.save').on('click', function() {
var chk = $(this).parent().parent().parent().parent().parent().find('input [name="ch"]').attr('class');
if ($("." + chk).attr('checked', false)) {
alert("please check the checkbox");
} else {
alert("you have checked the checkbox");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
i have tried with this code and getting the alert "please check the checkbox" for both conditions if and else.
i just want to validate the checkbox whether it is checked or not .. if checked means it should display the relevant message if not checked also should display the message.
There are two things i am noticing:
Instead use .closest() against .parent() multiple times.
Do not set the attribute in the if condition, instead of .attr() use .prop().
You can change to this
var chk = $(this).closest('form').find('input[name="ch"]');// use form if you have one.
if (!$(chk).prop('checked')) {
$('.save').on('click', function() {
var chk = $(this).closest('form').find('input[name="ch"]');
if (!$(chk).prop('checked')) {
alert("please check the checkbox");
} else {
alert("you have checked the checkbox");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form target="_self" id="immunization_info_form" class="form-validation save_immune25 update_immune25" role="form" method="POST" enctype="multipart/form-data">
<div class="form-group row" style="margin-top:10px;height:50px;">
<div class="checkbox checkbox-styled col-md-offset-1 col-md-4">
<label style="font-size:15px;"><input type="checkbox" id="checkbox25" name="ch" class="checkbx" value="25">
<span>Hepatitis A vaccine</span></label>
</div>
<div class="form-group col-md-4">
<!-- Date input -->
<input class="form-control edit25" id="date25" name="date" placeholder="Enter Date" value="<?php echo $date[25]; ?>" type="text" required>
</div>
</div>
<div class="row" style="padding:15px;">
<div class="col-md-3 col-md-offset-1">
<div class="form-group">
<h3 style="color:orange;">Clinic Name</h3><br>
<input name="clinic_name" id="clinic" class="form-control edit25" type="text" value="<?php echo $clinic_name[25]; ?>" required>
<label for="clinic_name"></label>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<h3 style="color:orange;">Name of the Health practitioner</h3><br>
<input name="hp_name" id="hp" class="form-control edit25" type="text" value="<?php echo $practitioner[25]; ?>" required>
<label for="hp_name"></label>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<h3 style="color:orange;">Lot no. of Vaccine</h3><br>
<input name="lotno" id="lot" class="form-control edit25" type="text" value="<?php echo $lotno[25]; ?>" required>
<label for="lotno"></label>
</div>
</div>
<div class="row col-md-offset-1">
<div class="col-md-6 text-right">
<input type="button" name="submit" value="SAVE" class="save btn btn-lg btn-primary ink-reaction justify" id="save_immune25">
</div>
</div>
</div>
</form>

javascript - stop refresh if error is returned from php

I was wondering whether it would be possible to add something to my javascript which would allow a refresh if the form is submitted fine however will not refresh the page if an error is returned back from PHP.
is this possible? if so could anyone provide me with any guidance that will help me achieve this please. I have manage to get the javascript to refresh when the form is submitted and a message is returned.
this is the js:
function addCall() {
var data = $('#addForm').serialize();
$.post('../Admin/ManageCourses_AddSubmit.php', data, function(response){
$("#addForm").html(response);
//'soft'reload parent page, after a delay to show message
setTimeout(function(){
$('#addModal').modal('hide')
location.reload();
},3500);
}).fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
and the php which processes the form and validates it:
<?php
session_start();
if (empty($_POST['course_title'])) {
$message = " Value is required";
}
else {
$course_title = trim($_POST['course_title']);
# Validate Course #
if (!ctype_alpha($course_title)) {
$message = '<p class="error">Course title should be alpha characters only.</p>';
}
elseif (strlen($course_title) < 3 OR strlen($course_title) > 50) {
$message = '<p class="error">Course title should be within 3-50 characters long.</p>';
}
else {
include "../includes/db_conx.php";
try
{
$db_conx = new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password);
$db_conx->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = $db_conx->prepare("INSERT INTO `insights`.`course_details` (`course_title`) VALUES (:course_title)");
$sql->bindParam(':course_title', $course_title, PDO::PARAM_STR);
$sql->execute();
$message = "<p class='text-success'> Record Successfully Added <span class='glyphicon glyphicon-ok'/></p>";
}
catch(Exception $e) {
if( $e->getCode() == 23000)
{
$message = 'Course already exists in database';
}
else
{
$message = $e->getMessage();
}
}
}
}
die($message);
?>
It would really useful to the user to be able to make amendments to the form instead of rewriting it all again.
the form:
<div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="addModalLabel" aria-hidden="true">
<div class="modal-dialog">
<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">Add New Record: </h4>
</div>
<div class="modal-body">
<form id="addForm" class="addForm">
<div class="form-group">
<label class="control-label" for="forename">Forename:</label>
<div class="controls">
<input id="forename" name="forename" type="text" placeholder="Enter forename(s)" class="form-control" maxlength="100" required="">
</div>
</div>
<div class="form-group">
<label class="control-label" for="surname">Surname:</label>
<div class="controls">
<input id="surname" name="surname" type="text" placeholder="Enter surname" class="form-control" maxlength="100" required="">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="control-label" for="email">Email:</label>
<div class="controls">
<input id="email" name="email" type="email" placeholder="Enter a valid email" class="form-control" maxlength="255" value="" required="">
</div>
</div>
<div class="form-group">
<label class="control-label" for="username">Username:</label>
<div class="controls">
<input id="username" name="username" type="text" placeholder="username" class="form-control" value="" maxlength="50" required="">
</div>
</div>
<div class="form-group">
<label class="control-label" for="password">Password:</label>
<div class="controls">
<input id="password" name="password" type="password" placeholder="password" class="form-control" maxlength="40" required="">
</div>
</div>
<div class="form-group">
<label class="control-label" for="confirm_password">Confirm Password:</label>
<div class="controls">
<input id="confirm_password" name="confirm_password" type="password" placeholder="retype password" class="form-control" maxlength="40" required="">
</div>
</div>
<?php
include "../includes/db_conx.php";
try {
$db_conx = new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password);
$db_conx->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt2 = $db_conx->prepare('SELECT * FROM role_type');
$stmt2->execute();
$roles = $stmt2->fetchAll(PDO::FETCH_ASSOC);
}
catch(Exception $e)
{
die ("Could not connect to the database $mysql_dbname :" . $e->getMessage());
}
?>
<div class="control-group">
<label class="control-label" for="role_type">Select User Type:</label><p></p>
<select name="role">
<option value=''>Select One</option>";
<?php foreach($roles as $role): ?>
<option value="<?php echo $role['role_type_code'] ?>"><?php echo $role['role_title'] ?></option>
<?php endforeach ?>
</select>
</div>
<p></p>
<?php
include "../includes/db_conx.php";
try {
$db_conx = new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password);
$db_conx->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt3 = $db_conx->prepare('SELECT * FROM course_details ORDER BY course_title');
$stmt3->execute();
$courses = $stmt3->fetchAll(PDO::FETCH_ASSOC);
}
catch(Exception $e)
{
die ("Could not connect to the database $mysql_dbname :" . $e->getMessage());
}
?>
<div class="control-group">
<label class="control-label" for="course_details">Select Course:</label><p></p>
<select name="course">
<option value=''>Select One</option>";
<?php foreach($courses as $course): ?>
<option value="<?php echo $course['course_code'] ?>"><?php echo $course['course_title'] ?></option>
<?php endforeach ?>
</select>
</div>
<input type="hidden" name="form_token" value="<?php echo $form_token; ?>" />
</form>
</div>
<div class="modal-footer">
<div class="btn-toolbar">
<button type="button" class="btn btn-default" class="pull-right" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-success" class="pull-right" onclick="addUCall();">Submit <span class="glyphicon glyphicon-saved"></button>
</div>
</div>
</div>
</div>
</div>
Thank you in advance.
Your message variable contain both error and success message. It will reload page every time when it receives response.
Add this after $("#addForm").html(response); -
var n = response.search("class=\'text-success\'");
if(n!=-1){
//reload success
}
else{
//stay on page, errors
}
As you're returning the error messages in the response, check for the error class and do the reload if necessary.
$.post('../Admin/ManageCourses_AddSubmit.php', data, function(response){
if(response.contains("text-success")) {
// put your logic here for success
} else {
// logic for errors
}
});

Categories

Resources