Hi I wonder whether someone may be able to help me please.
I've put together this page which has working 'client' and 'server' side validation.
What I'm now trying to do is add a page refresh and 'scroll to top', once the page has passed validation.
To the script used in the first link I've added the following code to try and invoke this functionality:
setTimeout(function() {
$('body').fadeOut(400, function() {
location.reload();
setTimeout(function() {
$('body').fadeIn(400);
}, 500);
window.scrollTo(x - coord, y - coord);
});
}, 2000);
The problem I'm having, is that irrespective of whether the the form passes validation, the page refreshes as can be seen in this page. So the full JavaScript code looks like this:
Post Update - Through working with #rahul, I've now have a working solution as below. NB I only needed to change the JavaScript code
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#addlocation").validationEngine();
$("#addlocation").bind("jqv.field.result", function(event, field, errorFound, prompText){ console.log(errorFound) })
});
</script>
<script type="text/javascript">
$(document).ready(function(){
$('#addlocation').submit(function(){
//check the form is not currently submitting
if($(this).data('formstatus') !== 'submitting'){
//setup variables
var form = $(this),
formData = form.serialize(),
formUrl = form.attr('action'),
formMethod = form.attr('method'),
responseMsg = $('#saverecordresponse');
//add status data to form
form.data('formstatus','submitting');
//show response message - waiting
responseMsg.hide()
.addClass('response-waiting')
.text('Please Wait...')
.fadeIn(200);
//send data to server for validation
$.ajax({
url: formUrl,
type: formMethod,
data: formData,
success:function(data){
//setup variables
var responseData = jQuery.parseJSON(data),
klass = '';
//response conditional
switch(responseData.status){
case 'error':
klass = 'response-error';
break;
case 'success':
klass = 'response-success';
break;
}
//show reponse message
responseMsg.fadeOut(200,function(){
$(this).removeClass('response-waiting')
.addClass(klass)
.text(responseData.message)
.fadeIn(200,function(){
//set timeout to hide response message
setTimeout(function(){
responseMsg.fadeOut(200,function(){
$(this).removeClass(klass);
form.data('formstatus','idle');
});
},3000)
if (klass=='response-success')
{
setTimeout(function () {
$('body').fadeOut(400, function () {
location.reload();
setTimeout(function () {
$('body').fadeIn(400);
}, 500);
window.scrollTo(x - coord, y - coord);
});
}, 2000);
}
});
});
}
});
}
//prevent form from submitting
return false;
});
});
</script>
and this is a cut down version (I've deleted most of the validation rules for preview purposes) the PHP code which works in conjunction with the JavaScript and saves the record to a MySQL database.
<?php
//sanitize data
$userid = mysql_real_escape_string($_POST['userid']);
$locationname = mysql_real_escape_string($_POST['locationname']);
$returnedaddress = mysql_real_escape_string($_POST['returnedaddress']);
if(empty($locationname)){
$status = "error";
$message = "You need to enter a name for this location!";
}
else{
$query = mysql_query("INSERT INTO `table` (userid, locationname, returnedaddress) VALUES ('$userid', '$locationname', '$returnedaddress')");
if($query){ //if insert is successful
$status = "success";
$message = "Location Saved!";
}
else { //if insert fails
$status = "error";
$message = "I'm sorry, there has been a technical error!";
}
}
//return json response
$data = array(
'status' => $status,
'message' => $message
);
echo json_encode($data);
exit;
?>
I must admit, I'm not sure where the problem lies, but I'm the first to admit I'm a little new to JavaScript and jQuery.
I just wondered whether someone may be able to look at this please and let me know where I'm going wrong, or even perhaps suggest a better alternative to make the page refresh once the form passes validation.
you can easily get it done using return false
check if validation not passed return false
if(Yourvalidation!=true)
{
return false;
}
after this section
//response conditional
switch(responseData.status){
case 'error':
klass = 'response-error';
break;
case 'success':
klass = 'response-success';
break;
}
check value of klass like this
responseMsg.fadeOut(200, function () {
$(this).removeClass('response-waiting')
.addClass(klass)
.text(responseData.message)
.fadeIn(200, function () {
//set timeout to hide response message
setTimeout(function () {
responseMsg.fadeOut(200, function () {
$(this).removeClass(klass);
form.data('formstatus', 'idle');
});
}, 3000)
if (klass=='response-success')
{
setTimeout(function () {
$('body').fadeOut(400, function () {
location.reload();
setTimeout(function () {
$('body').fadeIn(400);
}, 500);
window.scrollTo(x - coord, y - coord);
});
}, 2000);
}
else
{
return false; //use return false in else condition
}
});
});
You can check the client and server side validation by using this
if(Page_ClientValidate())
return true;
else
return false;
Related
I have a function to check whether email exist, but I want to submit the form only if the email doesn't exist
So I wrote following function:
$("#form-1").on("submit",function(e){
e.preventDefault();
var given_email=document.getElementById("email");
var data = $("#form-1").serialize();
$.ajax({
type : 'POST',
url : 'check.php',
data : data,
beforeSend: function() {
$(".submit").val('sending ...');
},
success : function(response) {
var response = JSON.parse(response);
if(response.status=='error'){
alert("Sorry This Email Already Used ");
return false;
} if(response.status=='true') {
return true;
$(this).submit();
}
}
});
});
Now if it return true also i cant submit the form . Please help.
i saw this question and answer e.preventDefault doesn't stop form from submitting . But no effect
Notes
even i tried
if(response.status=='true') { $("#form-1").submit(); } .
But this also not working
The return statement is returning before the form is submitted
if(response.status == 'true') {
//return true; // returns before the form is submitted
$(this).submit();
return true; // move return after submit
}
Suggestion
You are thinking about this, the wrong way, let PHP handle the checking and insert in the backend.
First Solution
In your PHP do something like
$querycheck = mysqli_query($con,"SELECT * FROM Persons");
$countrows = mysqli_num_rows($querycheck );;
if($countrows == '1')
{
echo json_encode(['message' => 'Sorry This Email Already Used']);
}
else
{
// insert statement here
echo json_encode(['message' => 'Submitted']);
}
In your JS
$("#form-1").on("submit",function(e){
e.preventDefault();
var given_email=document.getElementById("email");
var data = $("#form-1").serialize();
$.ajax({
type : 'POST',
url : 'check.php',
data : data,
beforeSend: function() {
$(".submit").val('sending ...');
},
success : function(response) {
var response = JSON.parse(response);
alert(response.message); // display the message here to the user.
}
});
});
Second Solution
save the form in a variable.
$("#form-1").on("submit",function(e){
e.preventDefault();
const form = $(this); // get the current form
var given_email=document.getElementById("email");
var data = $("#form-1").serialize();
$.ajax({
type : 'POST',
url : 'check.php',
data : data,
beforeSend: function() {
$(".submit").val('sending ...');
},
success : function(response) {
var response = JSON.parse(response);
if(response.status=='error'){
alert("Sorry This Email Already Used ");
return false;
} if(response.status=='true') {
form.submit(); // submit the form here
return true;
}
}
});
});
I'm working on a registration form for my website and it is only working in Firefox (with some issues), but in Chrome it does not work at all.
For example, if I correctly fill out the form in Firefox and submit, the PHP page still loads instead of sending that content to my registration form via my ajax call. However in Chrome, the form doesn't appear to submit at all.
In fact, in Chrome the variable data is set to the $num value in my PHP script, which is then displayed in #modal-body.
Question: How can I get this to work in all browsers and why is my event.preventdefault() not working correctly for Firefox??
Here is my registration form submission code:
$('#register-form').submit(function() {
$('#register-form > .input-group').removeClass('has-error');
$('#register-form .form-required').each(function() {
if ($(this).val().trim() == "") {
empty = true;
$(this).parent().addClass('has-error');
errors = "<strong>You have not filled out the login form correctly.</strong>";
}
else {
$(this).parent().removeClass('has-error');
$(this).parent().addClass('has-success');
}
});
// All fields populated, process the form
if (!empty) {
$('.progress').fadeIn(800);
$('#modal-body').parent().removeClass("has-error");
var formData = {
'username' : $('input[name=usernameReg]').val(),
'email' : $('input[name=email]').val(),
'password' : $('input[name=passwordReg]').val()
};
// Process the form
$.ajax({
type : 'POST',
url : 'db.php',
data : formData,
dataType : 'json',
encode : true,
success : function(data) {
if (data) {
// Fade the resulting message in
setTimeout(function() {
$(".progress").fadeOut(1000);
$("#modal-body").fadeIn(1000);
$("#modal-body").html(data);
}, 1000);
// Fade the resulting message out
setTimeout(function() {
$("#modal-body").fadeOut(2000);
}, 3000);
}
else {
$('#modal-body').addClass('has-error');
$('#modal-body').html(data);
}
}
});
}
// There were empty fields on the form
else {
$('#modal-body').html(errors);
}
event.preventDefault();
});
Here is my PHP code that handles processing of the form and checking to make sure that the account does not already exist, then that it is created in the database:
$hashed = md5($salt.$_POST['passwordReg']);
$email = $_POST['email'];
// Check if account already exists
$username = strtolower($_POST['usernameReg']);
$statement = $conn->prepare($selects['username']);
$statement->bind_param('ss', $hashed, $username);
if ($statement->execute()) {
//$statement->bind_result($results);
$num;
while($statement->fetch()){
$num++;
}
$statement->free_result();
}
else {
trigger_error('Error executing MySQL query: ' . $statement->error);
}
$statement = null;
// If num > 0, account exists.
// printf($num) only present for debugging purposes
printf($num);
if ($num < 1) {
$statement = $conn->prepare("INSERT INTO `User` (username, email, password) VALUES(?,?,?)");
$statement->bind_param('sss', $username, $email, $hashed);
if ($statement->execute()) {
echo json_encode('You have registered successfully');
}
else {
echo json_encode('Sorry, registration failed. Please try again later.');
}
}
else {
echo json_encode('Sorry, registration failed. Please verify that you do not already have an account.');
}
break;
Pass the event into the callback
$('#register-form').submit(function(e) {
// your code...
e.preventDefault();
}
I have to validate my form which does a scheduling. I used ajax and php to do a query and search that time - that was choosen in a select - in the database. If there's one row saved, it returns 1 (or false), if doesn't, returns 0 (or true). Anyway, in the function callback, even it's true, the validate error appears, as if it had a real error. Printing the value, we see the value, but i dont know why it shows the error. I've tried everything, and nowhere i found the answer for this.
The js file: alteraDiv.js
jQuery.validator.addMethod('confereDia', function(value){
alert("entrou no método");
if (conf(value) == '0'){
alert("entrou no if");
return true;
}else{
alert("entrou no else");
return false;
}
});
var verifica;
function setVerifica(x){
verifica = x;
}
function conf(value){
$.ajax({
async: false,
url: 'confereDia.php?horarioInicial='+value,
dataType: 'text',
success: function(data) {
alert("entrou no success");
setVerifica(data);
alert("value:"+value);
return verifica;
},
error: function(data){
alert("ERROR. Dados: " + data);
}
});
}
The php file: confereDia.php
$horarioInicial = $_GET["horarioInicial"];
$query = "SELECT idAgendamento FROM agendamento WHERE horarioInicial = '$horarioInicial'";
$results = mysql_query($query);
if (mysql_num_rows($results) == 0) {
echo '0'; //good to register
} else {
echo '1'; //already registered
}
There are more codes in the files, but i think these are necessary for you understand and help me.. THANK YOU!!!
I am looking for a jQuery AJAX script alongside a PHP script that allows for the storage of information on a button click. The function defined within the jQuery should take three variables, all of which are defined pre-method call. I have the basis of operation complete but at the end of all operations - after the button is clicked and some time has passed - no data is added to the appropriate mysql database.
Here is my jQuery function "store"
<script type="text/javascript">
function store(ud, ld, tp) {
$.ajax({
url: 'http://www.exampledomain.com/folder/store.php',
type: 'POST',
data: 'ud='+ud+'&ld='+ld+'&tp='+tp
success : function() {
alert("WORKED!");
},
error : function() {
alert("DIDN'T WORK!");
},
complete : function() {
}
});
}
</script>
Here is the store.php file (very basic I know, I have also yet to secure this script via sanitizing user input)
<?php
require ('../mysqli_connect.php');
$errors = 0;
if(isset($_POST['ud']) && is_numeric($_POST['ud'])) {
$ud = $_POST['ud'];
} else {
++$errors;
}
if(isset($_POST['ld']) && is_numeric($_POST['ld'])) {
$ld = $_POST['ld'];
} else {
++$errors;
}
if(isset($_POST['tp'])) {
$tp = strip_tags(stripslashes($_POST['tp']));
} else {
++$errors;
}
if($errors == 0) {
$q = "INSERT INTO table_name (column_1, column_2, column_3, column_4) VALUES ('$ld', '$ud', NOW(), '$tp')";
mysqli_query($mysqli, $q);
} else {
echo 'There was a problem!';
}
?>
Assume that I have onclick="store(3, 3, A)" as an attribute for a certain element. How can I fix this? If I remove the onclick attribute how do I pass the necessary parameters to the jQuery function? I appreciate any and all help!
<-- EDIT -->
New jQuery & AJAX Script ...
<script type="text/javascript">
function store(ud, ld, tp) {
$.ajax({
url: 'http://www.exampledomain.com/folder/store.php',
type: 'POST',
data: 'ud='+ud+'&ld='+ld+'&tp='+tp,
error : function() {
alert("error");
},
success : function(data) {
alert(data);
},
complete : function() {
alert("complete");
}
});
}
$(function () {
$("a.rec").on("click", function () {
var $this = $(this),
ud = $this.data("ud"),
ld = $this.data("ld"),
tp = $this.data("tp");
store(ud, ld, tp);
});
});
</script>
Revised PHP
<?php
if($_SERVER['REQUEST_METHOD'] === "POST"){
require ('../mysqli_connect.php');
$errors = 0;
if(isset($_POST['ud'])) {
$ud = $_POST['ud'];
} else {
++$errors;
}
if(isset($_POST['ld'])) {
$ld = $_POST['ld'];
} else {
++$errors;
}
if(isset($_POST['tp'])) {
$tp = $_POST['tp'];
} else {
++$errors;
}
if($errors == 0) {
$q = "INSERT INTO table_name (column_1, column_2, column_3, column_4) VALUES ('$ld', '$ud', NOW(), '$tp')";
mysqli_query($mysqli, $q);
} else {
echo 'There was a problem!';
}
} else {
$url = 'http://www.exampledomain.com/error.php';
ob_end_clean();
header("Location: $url");
exit();
}
?>
Now for my HTML
<li>
<div class="sample classes">
<a class="rec" data-ud="13" data-ld="10" data-tp="SCI">
<input type="submit" title="Something" value="Something" />
</a>
</div>
</li>
However, when this button is clicked, it still does not do anything!
As you said onclick is something you are going to want to avoid. This is how you do it.
$(function () { //This function will be ran when the page loads
$(".button-class").on("click", function () { //This will run when any button is clicked
var $this = $(this),
ud = $this.data("ud"),
ld = $this.data("ld"),
tp = $this.data("tp");
store(ud, ld, tp);
});
});
HTML
<input type="button" class="button-class" data-ud="3" data-ld="3" data-tp="A"/>
I find it easier to use JSON and pass variables in an object to the server:
<script>
(function(){
var store = function (ud, lrid, type) {
var data = {
ud:ud,
lrid:lrid,
type:type
};
$.ajax({
url: 'http://www.exampledomain.com/folder/store.php',
type: 'POST',
data: data,
success : function(data) {
alert(data);
},
error : function() {
alert("DIDN'T WORK!");
},
complete : function() {
}
});
};
$('#btn').on('click', function(){
store(1,2,3);
});
}());
</script>
Use this script to test you are getting the variables on the server side:
<?php
# Put this in http://www.exampledomain.com/folder/store.php to test it works
if($_SERVER['REQUEST_METHOD'] === "POST"){
if(
isset($_POST['ud']) &&
isset($_POST['lrid']) &&
isset($_POST['type'])
)
{
$var = $_POST['ud'] . ", ".$_POST['ud'] . ", ".$_POST['type'] ." passed successfully via ajax!";
echo json_encode($var);
}
}
?>
I have utilized on key up function with ajax to check in my database if the course name already exist. A prompt then will be showed to the user after a match is found. I have used the distinct query in my model and then the controller returns the right value to the ajax however the returned value were duplicated or even multiple values are returned causing the pop up message in my page to show multiple times also. What is wrong with this? Thanks for the help.Here are my codes
View (Javascript):
<script>
var typingTimer;
var doneTypingInterval = 3000;
$('#course_name').keyup(function(){
typingTimer = setTimeout(check_course_name_exist, doneTypingInterval);
});
$('#course_name').keydown(function(){
clearTimeout(typingTimer);
});
function check_course_name_exist()
{
var course_name=$("#course_name").val();
var postData={
'course_name':course_name
};
$.ajax({
type: "POST",
url: "<?php echo base_url();?>courses/check_course_name_existince",
dataType:'json',
data: postData,
success: function(data)
{
if(data.msg == 'Exist')
{
console.log(data.msg);
$("#alert_exist").fadeIn(100);
$("#alert_exist").delay(3000).fadeOut(1000);
var a = 0;
$("input[type=radio][value=" + a + "]").attr("disabled",true);
document.getElementById('course_desc').disabled=true;
document.getElementById('userfile').disabled=true;
document.getElementById('is_public').disabled=true;
document.getElementById('submit').disabled=true;
}
else
{
console.log(data.msg);
var a = 0;
$("input[type=radio][value=" + a + "]").attr("disabled",false);
document.getElementById('course_desc').disabled=false;
document.getElementById('userfile').disabled=false;
document.getElementById('is_public').disabled=false;
document.getElementById('submit').disabled=false;
}
}
});
</script>
Controller:
function check_course_name_existince()
{
$course_name = $this->input->post('course_name');
$session_id = $this->session->userdata('username');
$result = $this->
course_booking_model->check_course_name_exist($session_id,$course_name);
if($result)
{
$msg="Exist";
}
else
{
$msg="Available";
}
echo json_encode(array('msg'=>$msg));
}
Model:
function check_course_name_exist($tennant_id,$course_name)
{
$where = array(
'tennant_id' => $tennant_id,
'course_name' => $course_name
);
$this->db->distinct();
$this->db->select('course_name');
$this->db->where($where);
$this->db->group_by('course_name');
$query=$this->db->get("courses");
if($query->num_rows()>0)
{
return true;
}
else
{
return false;
}
}
Image Output:
The console log function returns 2 identical values resulting to 2 message pop up.
Try adding some checks before setting a new timeout to prevent multiple triggers to your ajax call
var typingTimer = null;
var doneTypingInterval = 3000;
$('#course_name').keyup(function () {
if (!typingTimer) {
typingTimer = setTimeout(check_course_name_exist, doneTypingInterval);
}
});
$('#course_name').keydown(function () {
if (typingTimer) {
clearTimeout(typingTimer);
typingTimer = null;
}
});