vendredi 17 avril 2015

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.


Thank you in advance.


Aucun commentaire:

Enregistrer un commentaire