Ajax image preview before upload and form validation in codeigniter - javascript

I want to preview image in placeholder before uploading a image and form validation using ajax in codeigniter
what i have done is shown in the below code first i wrote image preview code in javascript then ajax to submit the form details and getting the response from the controller and showing in the view
view->
<?php echo form_open_multipart('items/itemsave', array('id' => 'uploadForm')) ?>
<?php if (!empty($msg)): ?>
<div class="alert <?php echo $msg_class ?>" role="alert">
<?php echo $msg; ?>
</div>
<?php endif; ?>
<div class="form-group text-center" style="position: relative;" >
<span class="img-div">
<div class="text-center img-placeholder" onClick="triggerClick()">
<h4>Update image</h4>
</div>
<img src="../uploads/2.png" name="profileDisplay" onClick="triggerClick()" id="profileDisplay" style="width: 200px; height: 200px">
</span>
<input type="file" name="profileImage" onChange="displayImage(this)" id="profileImage" class="form-control" style="display: none;">
<label>Profile Image</label>
</div>
<div class="form-group">
<input type="text" name="name" id="name" class="form-control" placeholder="Name" >
</div>
<div class="form-group">
<input type="text" name="location" id="location" class="form-control" placeholder="Location" >
</div>
<div class="form-group">
<input type="text" name="buyingprice" id="buyingprice" class="form-control" placeholder="Buying price" >
</div>
<div class="form-group">
<input type="text" name="sellingprice" id="sellingprice" class="form-control" placeholder="Selling Price" >
</div>
<div class="form-group">
<input type="text" name="category" id="category" class="form-control" placeholder="Category" >
</div>
<div class="form-group">
<input type="text" name="code" id="code" class="form-control" placeholder="Code" >
</div>
<div class="form-group">
<input type="text" name="description" id="description" class="form-control" placeholder="Description" >
</div>
<div class="form-group">
<button type="submit" name="save_profile" class="btn btn-primary btn-block">Save User</button>
</div>
<?php echo form_close() ?>```
javascript->
```<script type="text/javascript">
$(function() {
$("#uploadForm").on('submit', function(e) {
e.preventDefault();
//e.stopPropagation();
var contactForm = $(this);
$.ajax({
url: contactForm.attr('action'),
type: 'post',
data: contactForm.serialize(),
success: function(response){
console.log(response);
if(response.status == 'success') {
$("#uploadForm").show();
}
$("#message").html(response.message);
}
});
});
});
</script>
<script type="text/javascript">
function triggerClick(e) {
document.querySelector('#profileImage').click();
}
function displayImage(e) {
if (e.files[0]) {
var reader = new FileReader();
reader.onload = function(e){
document.querySelector('#profileDisplay').setAttribute('src', e.target.result);
}
reader.readAsDataURL(e.files[0]);
}
}
</script>
controller->
public function itemsave(){
$this->form_validation->set_rules('name','Name','required');
$this->form_validation->set_rules('location','Location','required');
$this->form_validation->set_rules('buyingprice','buyingprice','required');
$this->form_validation->set_rules('sellingprice','sellingprice','required');
$this->form_validation->set_rules('category','category','required');
$this->form_validation->set_rules('code','code','required');
$this->form_validation->set_rules('description','description','required');
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = 2048;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->load->library('upload', $config);
if($this->form_validation->run()==true && $this->upload->do_upload('profileImage'))
{
$response = array(
'status' => 'success',
'message' => "<h3>Category Added successfully.</h3>"
);
}
else
{
if ( ! $this->upload->do_upload('profileImage')) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('itemsadd', $error);
}
$response = array(
'status' => 'error',
'message' => validation_errors()
);
}
$this->output
->set_content_type('application/json')
->set_output(json_encode($response));
}
}

Related

How to convert HMAC_SHA256_MAC in PHP

index.php
<form class="row g-3" action="<?php echo base_url('signin'); ?>" method="post" id="loginForm" onsubmit="return hashpass();">
<div class="col-12">
<label for="inputUsername" class="form-label">Username</label>
<input type="text" class="form-control" name="uname" id="uname" placeholder="Enter Username" required>
</div>
<div class="col-12">
<label for="inputChoosePassword" class="form-label">Password</label>
<div class="input-group" id="show_hide_password">
<input type="password" class="form-control border-end-0" name="password" required id="password" value="12345678" placeholder="Enter Password"> <i class='bx bx-hide'></i>
</div>
</div>
<div class="col-12">
<div class="d-grid">
<button type="submit" id="signin" class="btn btn-primary" onclick="hashpass();"><i class="bx bxs-lock-open"></i>Sign in</button>
</div>
</div>
</form>
<script src="<?php echo base_url(); ?>/assets/js/HmacSHA256.js"></script>
<script>
function hashpass(){
var FormName='loginForm';
document.forms[FormName]["password"].value=HMAC_SHA256_MAC("aSm0$i_20eNh3os", document.forms[FormName]["password"].value);
return true;
}
</script>
Home_Controller.php
public function signin()
{
$userModel = new UserModel();
$uname = $this->request->getPost('uname');
$password = $this->request->getPost('password');
$data = $userModel->signin($uname);
foreach($data as $key=>$value)
{
$auth_id=$value->auth_id;
$s_password=$value->password;
}
if(!empty($data))
{
if(password_verify($password, $s_password))
{
$session->set('auth_id',$auth_id);
$this->response->redirect(base_url('dashboard'));
}else{
$this->response->redirect(base_url());
}
}
else
{
$this->response->redirect(base_url());
}
}
If I get value from front end suppose value is demo enter from front end then get in controller If I print $2y$10$nxdb2IIIu0QMcXH0T0q0buKcugSUNT3muDOmelBO.fjTE5D8OrICq. So now without this script I want $2y$10$nxdb2IIIu0QMcXH0T0q0buKcugSUNT3muDOmelBO.fjTE5D8OrICq this output using PHP function.
Here is the php exmple.
<?php
echo hash_hmac('sha256', 'data', 'secret');
?>
Update the JS script
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/hmac-sha256.js"></script>
<script>
function hashpass(){
var FormName='loginForm';
document.forms[FormName]["password"].value=CryptoJS.HmacSHA256(document.forms[FormName]["password"].value, "aSm0$i_20eNh3os");
return true;
}
</script>
You can check the link.
Hash HMAC

Image seclection not working properly in Add / Remove Fields

I have created Add / Remove fields to collect data such as Member Pic, Member name, Member Email, Member Role, and Member FB Id. Everything is working perfectly.
The only problem I am facing is that when I want to change the already saved image of a member with a new one, then it changes the first image only. Means If I try to change the second or third or next member's image it updates the first image only. This happens only with the pre-saved images only.
If I add a new member then it works perfectly.
Following is the code:
<div class="card">
<div class="card-header text-center">
<b>Team Members</b>
</div>
<div class="card-body">
<?php
$member_details = $wpdb->get_var( $wpdb->prepare( "SELECT member_details FROM {$wpdb->prefix}project_members WHERE author_id = %s AND project_id = %s", $current_user_id, $project_id ) );
$member_details_decode = json_decode( $member_details, true );
?>
<div class="row">
<div class="col-md-4">
<?php
if ( ! empty( $member_details_decode['member_images'][0] ) ) { ?>
<img src="<?php echo site_url( '/wp-content/img/member-images/' ); echo $member_details_decode['member_images'][0]; ?>" class="img-thumbnail" id="output_member0">
<?php } else { ?>
<img src="<?php echo site_url( '/wp-content/assets/img/blank-image.png' ); ?>" class="img-thumbnail" id="output_member0">
<?php }
?>
<br><br>
<label class="btn btn-success btn-block btn-file">Select Image<input type="file" name="member_image[]" onchange="preview_member(event, 0)" style="display: none;"></label>
</div>
<div class="col-md-8">
<div class="form-group">
<label for="member_name"><b>Member Name</b> <b style="color:#FF0000;">*</b></label>
<input type="text" class="form-control" name="member_name[]" value="<?php if ( $member_details_decode['member_names'][0] != '' ) echo esc_attr( $member_details_decode['member_names'][0] ); ?>">
</div>
<div class="form-group">
<label for="member_email"><b>Email Address</b> <b style="color:#FF0000;">*</b></label>
<input type="text" class="form-control" name="member_email[]" value="<?php if ( $member_details_decode['member_emails'][0] != '' ) echo esc_attr( $member_details_decode['member_emails'][0] ); ?>">
</div>
<div class="form-group">
<label for="member_role"><b>Role in Project</b> <b style="color:#FF0000;">*</b></label>
<input type="text" class="form-control" name="member_role[]" value="<?php if ( $member_details_decode['member_roles'][0] != '' ) echo esc_attr( $member_details_decode['member_roles'][0] ); ?>">
</div>
<div class="form-group">
<label for="member_fb"><b>Facebook Username</b> <b style="color:#FF0000;">*</b></label>
<input type="text" class="form-control" name="member_fb[]" value="<?php if ( $member_details_decode['member_fbs'][0] != '' ) echo esc_attr( $member_details_decode['member_fbs'][0] ); ?>">
</div>
</div>
</div>
<?php
$member_count = count( $member_details_decode['member_images'] );
for ( $i=1; $i < $member_count; $i++ ) { ?>
<div class="all-member-fields"><hr>
<div class="row">
<div class="col-md-4">
<?php
if ( ! empty( $member_details_decode['member_images'][$i] ) ) { ?>
<img src="<?php echo site_url( '/wp-content/img/member-images/' ); echo $member_details_decode['member_images'][$i]; ?>" class="img-thumbnail" id="output_member0">
<?php } else { ?>
<img src="<?php echo site_url( '/wp-content/assets/img/blank-image.png' ); ?>" class="img-thumbnail" id="output_member0">
<?php }
?>
<br><br>
<label class="btn btn-success btn-block btn-file">Select Image<input type="file" name="member_image[]" onchange="preview_member(event, 0)" style="display: none;"></label>
</div>
<div class="col-md-8">
<div class="form-group">
<label for="member_name"><b>Member Name</b> <b style="color:#FF0000;">*</b></label>
<input type="text" class="form-control" name="member_name[]" value="<?php if ( $member_details_decode['member_names'][$i] != '' ) echo esc_attr( $member_details_decode['member_names'][$i] ); ?>">
</div>
<div class="form-group">
<label for="member_email"><b>Email Address</b> <b style="color:#FF0000;">*</b></label>
<input type="text" class="form-control" name="member_email[]" value="<?php if ( $member_details_decode['member_emails'][$i] != '' ) echo esc_attr( $member_details_decode['member_emails'][$i] ); ?>">
</div>
<div class="form-group">
<label for="member_role"><b>Role in Project</b> <b style="color:#FF0000;">*</b></label>
<input type="text" class="form-control" name="member_role[]" value="<?php if ( $member_details_decode['member_roles'][$i] != '' ) echo esc_attr( $member_details_decode['member_roles'][$i] ); ?>">
</div>
<div class="form-group">
<label for="member_fb"><b>Facebook Username</b> <b style="color:#FF0000;">*</b></label>
<input type="text" class="form-control" name="member_fb[]" value="<?php if ( $member_details_decode['member_fbs'][$i] != '' ) echo esc_attr( $member_details_decode['member_fbs'][$i] ); ?>">
</div>
</div>
</div>
<button type="button" class="btn btn-danger" id="remove-member-fields" style="float: right;">Remove Member</button><br><br></div>
<?php }
?>
<div id="member-fields">
</div>
<button type="button" class="btn btn-success btn-block" id="add-member-fields">Add Member</button>
</div>
</div>
My Javascript Code:
<script type="text/javascript">
var i = 0;
function preview_member(event, inp) {
var reader = new FileReader();
console.log(inp);
reader.onload = function() {
var output = document.getElementById('output_member' + inp);
output.src = reader.result;
};
reader.readAsDataURL(event.target.files[0]);
}
jQuery(document).ready(function($) {
//fadeout selected item and remove
$(document).on("click", '#remove-member-fields', function(event) {
event.preventDefault();
$(this)
.parent()
.fadeOut(300, function() {
$(this).empty();
return false;
});
});
//add input
$('#add-member-fields').click(function() {
i++;
var rows = `<div class="all-member-fields"><hr><div class="row"><div class="col-md-4"><img src="<?php echo esc_url( site_url('/wp-content/assets/img/blank-image.png') ); ?>" class="img-thumbnail" id="output_member${i}"><br><br><label class="btn btn-success btn-block btn-file">Select Image<input type="file" name="member_image[]" onchange="preview_member(event, ${i})" style="display: none;"></label></div><div class="col-md-8"><div class="form-group"><label for="member_name"><b>Member Name</b> <b style="color:#FF0000;">*</b></label><input type="text" class="form-control" name="member_name[]"></div><div class="form-group"><label for="member_email"><b>Email Address</b> <b style="color:#FF0000;">*</b></label><input type="text" class="form-control" name="member_email[]"></div><div class="form-group"><label for="member_role"><b>Role in Project</b> <b style="color:#FF0000;">*</b></label><input type="text" class="form-control" name="member_role[]"></div><div class="form-group"><label for="member_fb"><b>Facebook Username</b> <b style="color:#FF0000;">*</b></label><input type="text" class="form-control" name="member_fb[]"></div></div></div><button type="button" class="btn btn-danger" id="remove-member-fields" style="float: right;">Remove Member</button><br><br></div>`;
$(rows)
.fadeIn("slow")
.appendTo('#member-fields');
return false;
});
});
</script>
You forgot to add your $i to preview_member() and to image id in your loop
Your preview_member() functions changes element with id output_member0 everytime.
In your for loop:
Change images ID from id="output_member0" to id="output_member<?= $i ?>" in your
Change onchange="preview_member(event, 0)" to onchange="preview_member(event, <?= $i ?>)"

Form Submit with using Jquery Ajax PHP

I know there is a lot of similar questions but I am working on this exact same problem for two days and I just gave up.
So after the form is submitted, I want to prevent the current page (updates.php) to redirect to another page (test.php).
I am trying to do this with Jquery Ajax, but in this point, I am open to any solution.
updates.php:
<form action="test.php" method="post">
<div class="row form-group">
<div class="col-md-12">
<label class="sr-only" for="name">Name</label>
<input type="text" id="name" name="name" class="form-control" style="background:white;opacity:.5;border:none;" placeholder="Name:" required>
</div>
</div>
<input type = "hidden" id="id" name = "id" value = "4" />
<div class="row form-group">
<div class="col-md-12">
<label class="sr-only" for="subject">Comment</label>
<input type="text" name="subject" id="subject" class="form-control" style="background:white;opacity:.5;border:none;" placeholder="Write a comment..." required>
</div>
</div>
<div class="form-group">
<input type="submit" value="Post Comment" class="btn btn-primary">
</div>
</form>
test.php:
<?php
$id = $_POST['id'];
$username = $_POST['name'];
$comment = $_POST['subject'];
if(!empty($username) || !empty($comment))
{
$conn = mysqli_connect('localhost','Admin','admin123','website');
if(!$conn)
{
echo "Connection Error: " . mysqli_connect_error();
}
else
{
$INSERT = "INSERT INTO comments (id, name, comment) VALUES (?,?,?)";
$stmt = $conn -> prepare($INSERT);
$stmt -> bind_param("iss", $id, $username, $comment);
$stmt -> execute();
}
}
else { echo "All fields are required"; die();}
?>
Whatever I did I couldn't stop test.php to open.
Try this as your updates.php file instead:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
function submitWithAjax(){
var name = document.getElementById("name").value;
var id = document.getElementById("id").value;
var subject = document.getElementById("subject").value;
$.post( "test.php", {name: name, id: id, subject: subject})
.done(function(data) {
alert( "Data Loaded: " + data );
});
}
</script>
</head>
<body>
<form>
<div class="row form-group">
<div class="col-md-12">
<label class="sr-only" for="name">Name</label>
<input type="text" id="name" name="name" class="form-control" style="background:white;opacity:.5;border:none;" placeholder="Name:" required>
</div>
</div>
<input type = "hidden" id="id" name = "id" value = "4" />
<div class="row form-group">
<div class="col-md-12">
<label class="sr-only" for="subject">Comment</label>
<input type="text" name="subject" id="subject" class="form-control" style="background:white;opacity:.5;border:none;" placeholder="Write a comment..." required>
</div>
</div>
<div class="form-group">
<input type="submit" value="Post Comment" class="btn btn-primary" onclick="event.preventDefault();submitWithAjax();">
</div>
</form>
</body>
</html>

Uncaught RangeError: Maximum call stack size exceeded jquery-1.11.3.min.js:5?

hello friends have this problem,when I click the link shows me the error: Uncaught RangeError: Maximum call stack size exceeded?
<a onclick='EditarMatricula();' class="btn blue btn-sm"><i class="fa fa-check-circle"></i> Actualizar</a>
This is mi code edit.php
<?php
include_once('../conexion.php');
$idEdit = $_POST['idEdit'];
$mat_edit = $DB_con->prepare("SELECT matricula.idmatricula, matricula.fecha, CONCAT(alumno.nombres,' ',alumno.apellidos) AS alumno, matricula.idalumno, periodo.nombre AS periodo, matricula.idperiodo, grado.nombre AS grado, matricula.idgrado, aula.nombre AS aula, matricula.idaula, matricula.tipo, matricula.turno FROM matricula INNER JOIN alumno ON matricula.idalumno = alumno.idalumno INNER JOIN periodo ON matricula.idperiodo = periodo.idperiodo INNER JOIN grado ON matricula.idgrado = grado.idgrado INNER JOIN aula ON matricula.idaula = aula.idaula WHERE matricula.idmatricula = $idEdit");
$mat_edit->execute();
$fila_matricula = $mat_edit->fetch(PDO::FETCH_ASSOC);
?>
<script>
$(function() {
$("#alumno_edit").autocomplete({
source: "autocompletar/buscaralunom.php",
minLength: 2,
select: function(event, ui) {
$('#idalumno_edit').val(ui.item.idalumno);
}
});
});
$(function() {
$("#periodo_edit").autocomplete({
source: "autocompletar/buscarpernom.php",
minLength: 2,
select: function(event, ui) {
$('#idperiodo_edit').val(ui.item.idperiodo);
}
});
});
$(function() {
$("#grado_edit").autocomplete({
source: "autocompletar/buscargranom.php",
minLength: 2,
select: function(event, ui) {
$('#idgrado_edit').val(ui.item.idgrado);
}
});
});
$(function() {
$("#aula_edit").autocomplete({
source: "autocompletar/buscaraulnom.php",
minLength: 2,
select: function(event, ui) {
$('#idaula_edit').val(ui.item.idaula);
}
});
});
</script>
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">EDITAR MATRÍCULA</h4>
</div>
<div class="modal-body">
<form method="POST" class="form-horizontal well">
<div>
<input name="ideditar" id="ideditar" class="form-control" type="hidden" value="<?php print $fila_matricula['idmatricula'] ?>">
</div>
<div class="form-group">
<label class="col-lg-2 control-label">Fecha:</label>
<div class="col-lg-10">
<input name="fechamostrara_edit" id="fechamostrara_edit" class="form-control" required type="text" value="<?php print date("d-m-Y",strtotime($fila_matricula['fecha'])) ?>" readonly>
<input name="fecha_edit" id="fecha_edit" class="form-control" type="hidden" value="<?php print $fila_matricula['fecha'] ?>" readonly="">
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label">Alumno:</label>
<div class="col-lg-10">
<input name="alumno_edit" id="alumno_edit" class="form-control" type="text" value="<?php print $fila_matricula['alumno'] ?>">
<input name="idalumno_edit" id="idalumno_edit" class="form-control" type="hidden" value="<?php print $fila_matricula['idalumno'] ?>">
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label">Periodo:</label>
<div class="col-lg-10">
<input name="periodo_edit" id="periodo_edit" class="form-control" type="text" value="<?php print $fila_matricula['periodo'] ?>">
<input name="idperiodo_edit" id="idperiodo_edit" class="form-control" type="hidden" value="<?php print $fila_matricula['idperiodo'] ?>">
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label">Grado:</label>
<div class="col-lg-10">
<input name="grado_edit" id="grado_edit" class="form-control" type="text" value="<?php print $fila_matricula['grado'] ?>">
<input name="idgrado_edit" id="idgrado_edit" class="form-control" type="hidden" value="<?php print $fila_matricula['idgrado'] ?>">
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label">Aula:</label>
<div class="col-lg-10">
<input name="aula_edit" id="aula_edit" class="form-control" type="text" value="<?php print $fila_matricula['aula'] ?>">
<input name="idaula_edit" id="idaula_edit" class="form-control" type="hidden" value="<?php print $fila_matricula['idaula'] ?>">
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label">Tipo:</label>
<div class="col-lg-10">
<label class="radio-linea">
<input type="radio" name="tipo_edit" class="icheck" data-radio="iradio_flat-blue" value="Regular" <?php if ($fila_matricula['tipo'] == 'Regular') echo 'checked="checked"'; ?> > <span>Regular</span>
</label>
<label class="radio-linea">
<input type="radio" name="tipo_edit" class="icheck" data-radio="iradio_flat-blue" value="Becado" <?php if ($fila_matricula['tipo'] == 'Becado') echo 'checked="checked"'; ?> > <span>Becado</span>
</label>
<label class="radio-linea">
<input type="radio" name="tipo_edit" class="icheck" data-radio="iradio_flat-blue" value="Especial" <?php if ($fila_matricula['tipo'] == 'Especial') echo 'checked="checked"'; ?> > <span>Especial</span>
</label>
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label">Turno:</label>
<div class="col-lg-10">
<label class="radio-linea">
<input type="radio" name="turno_edit" class="icheck" data-radio="iradio_flat-blue" value="Mañana" <?php if ($fila_matricula['turno'] == 'Mañana') echo 'checked="checked"'; ?> > <span>Mañana</span>
</label>
<label class="radio-linea">
<input type="radio" name="turno_edit" class="icheck" data-radio="iradio_flat-blue" value="Tarde" <?php if ($fila_matricula['turno'] == 'Tarde') echo 'checked="checked"'; ?> > <span>Tarde</span>
</label>
<label class="radio-linea">
<input type="radio" name="turno_edit" class="icheck" data-radio="iradio_flat-blue" value="Noche" <?php if ($fila_matricula['turno'] == 'Noche') echo 'checked="checked"'; ?> > <span>Noche</span>
</label>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<a class="btn dark btn-sm" data-dismiss="modal"><i class="fa fa-times-circle"></i> Salir</a>
<a onclick='EditarMatricula();' class="btn blue btn-sm"><i class="fa fa-check-circle"></i> Actualizar</a>
</div>
</div>
</div>
<script>
$(function() {
$("#fechamostrara_edit").datepicker({format: "dd-mm-yyyy", orientation:"bottom", autoclose: true});
$("#fechamostrara_edit").change(function(event) {
var fechamostrara_edit = $("#fechamostrara_edit").val();
fechamostrara_edit = fechamostrara_edit.split("-").reverse().join("-");
$("#fecha_edit").val(fechamostrara_edit);
});
});
</script>
And this is mat.js
function EditarMatricula(){
var id = $("#ideditar").val();
var fecha_edit = $("#fecha_edit").val();
var idalumno_edit = $("#idalumno_edit").val();
var idperiodo_edit = $("#idperiodo_edit").val();
var idgrado_edit = $("#idgrado_edit").val();
var idalula_edit = $("#idaula_edit").val();
var tipo_edit = $("input[name='tipo_edit']:checked").val();
var turno_edit = $("input[name='turno_edit']:checked").val();
$.ajax({
type: 'POST',
url: 'class/matriculaeditar.php',
data: {ideditar:id, fecha_edit:fecha_edit, idalumno_edit:idalumno_edit, idperiodo_edit:idperiodo_edit, idgrado_edit:idgrado_edit, idaula_edit:idaula_edit, tipo_edit:tipo_edit, turno_edit:turno_edit },//parametros
success: function(data){
$(".mensajeeditar").hide();
$(".mensajeeditar").html("<div class='smseditar'> SE ACTUALIZO LOS DATOS <br> De la Matrícula</div>");
$('.mensajeeditar').fadeIn('slow');
ListarMatriculas();
}
}).done(function() {
$(".mensajeeditar").fadeOut( 4000, "linear");
$("div").removeClass('modal-backdrop');
$('#myModal-Edit').modal('hide');
$('html, body').animate({ scrollTop: 0 }, 0);
});
}
function ListarMatriculas(){
$.ajax({
url: 'matricula_lista.php',
type: 'GET',
success: function(data){
$("#miTabla").html(data);
$("#miTabla").hide();
$("#miTabla").fadeToggle('slow','linear');
}
});
}

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