after success my page wont reload but it just close the window
this is my jQuery script
jQuery("#edit").dialog({
modal: true,
resizable: false,
draggable: false,
autoOpen: false,
width: 400,
buttons: [
{
text: "Ok",
click: function() {
var message = "";
var id = jQuery.trim(jQuery("#id").val());
var fname = jQuery.trim(jQuery("#firstname").val());
var lname = jQuery.trim(jQuery("#lastname").val());
var email = jQuery.trim(jQuery("#email").val());
var telephone = jQuery.trim(jQuery("#telephone").val());
var mobile = jQuery.trim(jQuery("#mobile").val());
var address = jQuery.trim(jQuery("#address").val());
var bdate = jQuery.trim(jQuery("#bdate").val());
if (fname == "") {message += "Please enter firstname\n"};
if (lname == "") {message += "Please enter lastname\n"};
if (email == "") {
message += "Please enter email\n"
}
else{
if(!ValidateEmail(email)){
message += "Please enter valid email address.\n"
}
}
if (telephone == "") {message += "Please enter telephone\n"};
if (mobile == "") {message += "Please enter mobile\n"};
if (address == "") {message += "Please enter address\n"};
if (bdate == "") {message += "Please enter birthdate"};
if (message != "")
{
alert(message);
return false;
}
else
{
jQuery.ajax({
type: "POST",
dataType: "json",
url: "update.php",
async:true,
data: {
"id": id,
"firstname": fname,
"lastname": lname,
"email": email,
"telephone": telephone,
"mobile": mobile,
"address": address,
"bdate": bdate
},
sucess: function(){
window.location.reload(true);
}
});
}
}
},
{
text: "Cancel",
click: function() {
jQuery(this).dialog( "close" );
}
}
]
});
and here is my PHP
$id = $_POST['id'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$telephone = $_POST['telephone'];
$mobile = $_POST['mobile'];
$address = $_POST['address'];
$bdate = date("Y-m-d",strtotime($_POST['bdate']));
$sql = "UPDATE user SET
firstname='$firstname', lastname='$lastname', email='$email', telephone='$telephone', mobile='$mobile', address='$address', bdate='$bdate' WHERE id=$id";
$result = mysql_query($sql);
if($result){
echo json_encode(array(
"success" => true,
));
}
i tried also this but doesnt reload the page
sucess: function(data){
if(data.success == true){
window.location.reload(true);
}
}
also i changed the window.location.reload into location.reload and i tried also removing the true in it
Related
I have a login page and I have the API for matching the password. If the password doesn't match it will show an error message but my problem is if the password is matching also it showing an error message. because am looping the data so every time it is checking I need to break the loop if it matches how to do. Here is my
code
HTML
$(document).ready(function() {
localStorage.removeItem('role');
$(".login-error").hide();
$("#login").on("submit", function(e) {
e.preventDefault();
var form_data = $('#login').serialize();
var username = $("#name").val();
var pwd = $("#password").val();
$.ajax({
url: "https://api.myjson.com/bins/qt7fk",
type: "GET",
dataType: "json",
success: function(data) {
console.log(typeof(data));
// alert(JSON.stringify(data));
var arr = data;
arr.forEach(function(obj) {
console.log('name: ' + obj.name);
console.log('password: ' + obj.role);
var pass = obj.password;
// var decryptedBytes = CryptoJS.AES.decrypt(obj.password, "password");
var bytes = CryptoJS.AES.decrypt(pass.toString(), 'password');
var plaintext = bytes.toString(CryptoJS.enc.Utf8);
// alert(plaintext);
var role = obj.role;
if (role == "User") {
if (username == obj.name && pwd == plaintext) {
alert("New role");
document.getElementById('message').innerHTML = "Success"
/* window.location.href = "./job-insert.html?role=" + role; */
} else {
$("#login p").removeClass("d-none");
}
} else {
if (username == obj.name && pwd == plaintext) {
alert("Login succes");
document.getElementById('message').innerHTML = "Success"
/* window.location.href = "./dashboard.html?role=" + role; */
} else {
$("#login p").removeClass("d-none");
document.getElementById('message').innerHTML = "Please enter a correct login and password"
}
}
})
},
error: function(data) {
console.log(data);
}
});
});
});
I have forked and break your code when the password gets matched. You may test this from here: code
$(document).ready(function() {
localStorage.removeItem('role');
$(".login-error").hide();
$("#login").on("submit", function(e) {
e.preventDefault();
var form_data = $('#login').serialize();
var username = $("#name").val();
var pwd = $("#password").val();
$.ajax({
url: "https://api.myjson.com/bins/qt7fk",
type: "GET",
dataType: "json",
success: function(data) {
console.log(typeof(data));
// alert(JSON.stringify(data));
var arr = data;
var BreakException = {};
try {
arr.forEach(function(obj) {
console.log('name: ' + obj.name);
console.log('password: ' + obj.role);
var pass = obj.password;
// var decryptedBytes = CryptoJS.AES.decrypt(obj.password, "password");
var bytes = CryptoJS.AES.decrypt(pass.toString(), 'password');
var plaintext = bytes.toString(CryptoJS.enc.Utf8);
// alert(plaintext);
var role = obj.role;
if (role == "User") {
if (username == obj.name && pwd == plaintext) {
alert("New role");
document.getElementById('message').innerHTML = "Success"
/* window.location.href = "./job-insert.html?role=" + role; */
} else {
$("#login p").removeClass("d-none");
}
} else {
if (username == obj.name && pwd == plaintext) {
alert("Login succes");
document.getElementById('message').innerHTML = "Success"
throw BreakException;
/* window.location.href = "./dashboard.html?role=" + role; */
} else {
$("#login p").removeClass("d-none");
document.getElementById('message').innerHTML = "Please enter a correct login and password"
}
}
})
} catch (e) {
if (e !== BreakException) throw e;
}
},
error: function(data) {
console.log(data);
}
});
});
});
NOTE: You can break forEach like other loops. To make this thing done you need to add your code in try-catch and throw exception when the password gets matched. That is what I have done in your above code.
Everything from the server works perfectly well, but just this simple conditional statement is not working for some reason.
$(document).ready(function() {
$("#logsubmit").click(function() {
var username = $("#username").val()
var password = $("#pwd").val()
$.post("functions/logincheck.php", {
username: username,
password: password
}, function(result) {
if (result == "success") {
window.location = "/";
} else {
alert(result);
}
});
});
});
Even if the result == success the else statement is being executed for some reason.
The PHP script:
<?php
session_start();
include '../connect.php';
$username = $_POST['username'];
$password = $_POST['password'];
$lgchk = $con->prepare("select uid, pass from userlogin where uname = :uname");
$lgchk->bindParam(':uname', $username);
$lgchk->execute();
if ($lgchk->rowCount() > 0) {
while ($row = $lgchk->fetch(PDO::FETCH_ASSOC)) {
$pass = htmlentities($row['pass']);
$id = htmlentities($row['uid']);
}
if ($password == $pass) {
$_SESSION["myid"] = $id;
echo "success";
} else {
echo "Incorrect Password";
}
} else {
echo "Account Doesnt Exist";
}
?>
Do something like this
$(document).ready(function() {
$("#logsubmit").click(function() {
var username = $("#username").val()
var password = $("#pwd").val()
$.post("functions/logincheck.php", {
username: username,
password: password
}, function(result) {
var r = result.trim();
if (r == "success") {
window.location = "/";
} else {
alert(result);
}
});
});
});
Use trim method & then assign it to some other variable.
Hope this will help you.
I have a PHP file receiving data from Ajax but after receiving the data I am sending a success message from php using json_encode, but the message error is hit is being alerted even though the SQL query is successful. This process worked well for localhost but when I uploaded it in main server there is an error.
Here Is my JS file:
$(function() {
$("#userReg_btn").click(function(e) {
//user registration in
var array = [];
var flag = false;
var firstName = $("#uFn").val();
var lastName = $("#uLn").val();
var email = $("#uEa").val();
var pass = $("#uPn").val();
var mobile = $("#uMn").val();
var nID = $("#uNm").val();
var age = $("#uAn").val();
var prof = $("#uPc").val();
if (firstName == "" || lastName == "" || email == "" || pass == "" || mobile == "" || nID == "" || age == "" || prof == "") {
e.preventDefault();
alert("Please provide some input");
flag = false;
} else if (mobile.length != 11 || nID.length != 17) {
e.preventDefault();
alert("Please provide correct input");
flag = false;
} else {
array.push(firstName);
array.push(lastName);
array.push(email);
array.push(pass);
array.push(mobile);
array.push(nID);
array.push(age);
array.push(prof);
alert(array);
console.log(array);
flag = true;
}
if (flag == true) {
$.ajax({
url: "http://demoname.co/CustomerRegistration.php",
data: {
firstName: array[0],
lastName: array[1],
email: array[2],
pass: array[3],
mobile: array[4],
nID: array[5],
age: array[6],
prof: array[7]
},
type: "POST",
dataType: "json",
success: function(suc) {
alert("in success");
alert(suc);
console.log("success");
},
error: function(err) {
alert("error is hit");
alert(err);
console.log(err);
}
});
} else {
alert("Form error");
}
alert("USer Reg");
});
Here is my PHP file:
<?php
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 01 Jan 2016 00:00:00 GMT');
// The JSON standard MIME header.
header('Content-type: application/json');
$con=mysql_connect("localhost","username", "password");
mysql_select_db("database name",$con);
$fname = $_POST['firstName'];
$lname=$_POST['lastName'];
$username=$_POST['email'];
$password=$_POST['pass'];
$phone=$_POST['mobile'];
$nid=$_POST['nID'];
$age=$_POST['age'];
$profession=$_POST['prof'];
$query="INSERT INTO customerregistration(FirstName,LastName,Username,password,PhoneNumber,NID,Age,Profession) VALUES('$fname','$lname','$username','$password','$phone','$nid','$age','$profession');";
if(mysql_query($query))
{
$suc= 'success';
echo json_encode($suc);
}
else
{
echo mysql_error();
}
?>
I have used location.href in my earlier days but now its not redirecting to page. here is my code
function AuthenticateUserWithPage() {
var UId = $('#amwayId').val();//username
var UPw = $('#amwayPw').val();//password
var ischecked = $('#idSave').is(':checked');// check remember me checkbox status
if (UId != '' && UPw != '') {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "../KPPRMobService/PNBMobWebService.asmx/IsValidUserWithPage",
data: JSON.stringify({ username: UId, password: UPw, ischecked: ischecked }),
async: false,
success: function (data) {
var obj = data.d;
if (obj != "FALSE") {
var targetUrl = "http://" + window.location.host + obj;
window.location.href = targetUrl;
//window.location.replace(targetUrl);
return false;
}
else {
$('#amwayId').val('');
//if username or password is invalid
alert("Please check your ID or password. The ID is not registered or the ID/ password is wrong.");
}
},
error: function (result) {
//if error occured.
$('#amwayId').val('');
alert("You cannot log in. Contact support center for further inquiries..");
}
});
}
else {
//if username or password is null
alert("Please enter ID/ password.");
return false;
}
}
I use this link as reference: reference.Thanks in Advance.
Php:
$form_data = array();
$form_data['message'] = "success";
$form_data['redirect'] = "http://www.example.com/example";
echo json_encode($form_data)
Ajax:
if (data.message == 'success') {
window.location.href = data.redirect;
return false;
}else if(){
etc...
}
I am using a ajax-driven contact form and receive the error "ReferenceError: slickcontactparse is not defined".
Am not sure how to declare the function. Please help!!
js
$(document).ready(function(){
$('#slickform').submit(
function slickcontactparse() {
// EMAIL VALIDATION FUNCTION
var emailReg = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(#\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
// EDIT THIS SECTION IF DIFFERENT FORM ELEMENTS
// Values
var successmessage = "Thank you for email, we will be in contact soon!";
var failedmessage = "There was a problem, please try again!";
var usersname = $('#name');
var usersemail = $('#email');
var usersphone = $('#phone');
var userssubject = $('#subject');
var userscomment = $('#comment');
var usershuman = $('#human');
var isvalid = 1;
var url = "slickform.php";
//Checking information is correct before sending data
//CHECKING EMAIL IS PRESENT AND IS VALID
if (usersemail.val() == "") {
$(".slickbutton").animate({marginTop:'50px'},1000).delay(6000).animate({marginTop:'0px'},1000);
$(".errorcontainer").html('Please Insert Your Email!');
$(".errorcontainer").delay(1200).fadeIn(1000).delay(4000).fadeOut(1000);
$('input[type=submit]', $("#slickform")).removeAttr('disabled');
return false;
}
var valid = emailReg.test(usersemail.val());
if(!valid) {
$(".slickbutton").animate({marginTop:'50px'},1000).delay(6000).animate({marginTop:'0px'},1000);
$(".errorcontainer").html('Please Enter A Valid Email!');
$(".errorcontainer").delay(1200).fadeIn(1000).delay(4000).fadeOut(1000);
$('input[type=submit]', $("#slickform")).removeAttr('disabled');
return false;
}
//CHECKING EMAIL IS PRESENT AND IS VALID
//CHECKING USERS NAME IS PRESENT
if (usersname.val() == "") {
$(".slickbutton").animate({marginTop:'50px'},1000).delay(6000).animate({marginTop:'0px'},1000);
$(".errorcontainer").html('Please Insert Your Name!');
$(".errorcontainer").delay(1200).fadeIn(1000).delay(4000).fadeOut(1000);
$('input[type=submit]', $("#slickform")).removeAttr('disabled');
return false;
}
//CHECKING USERS NAME IS PRESENT
//CHECKING USERS PHONE NUMBER IS PRESENT AND IS ONLY NUMERIC
if (usersphone.val() == "") {
$(".slickbutton").animate({marginTop:'50px'},1000).delay(6000).animate({marginTop:'0px'},1000);
$(".errorcontainer").html('Please Insert Your Phone Number!');
$(".errorcontainer").delay(1200).fadeIn(1000).delay(4000).fadeOut(1000);
$('input[type=submit]', $("#slickform")).removeAttr('disabled');
return false;
}
var EnteredValue = $.trim(usersphone.val());
var TestValue = EnteredValue.replace(" ", "");
if (isNaN(TestValue)) {
$(".slickbutton").animate({marginTop:'50px'},1000).delay(6000).animate({marginTop:'0px'},1000);
$(".errorcontainer").html('Please Enter A Valid Phone Number!');
$(".errorcontainer").delay(1200).fadeIn(1000).delay(4000).fadeOut(1000);
$('input[type=submit]', $("#slickform")).removeAttr('disabled');
return false;
}
//CHECKING USERS NAME IS PRESENT
//CHECKING SUBJECT WAS SELECTED
if (userssubject.val() == "") {
$(".slickbutton").animate({marginTop:'50px'},1000).delay(6000).animate({marginTop:'0px'},1000);
$(".errorcontainer").html('Please Select A Subject!');
$(".errorcontainer").delay(1200).fadeIn(1000).delay(4000).fadeOut(1000);
$('input[type=submit]', $("#slickform")).removeAttr('disabled');
return false;
}
//CHECKING SUBJECT WAS SELECTED
//CHECKING THE USER IS HUMAN
if (usershuman.val() != 15) {
$(".slickbutton").animate({marginTop:'50px'},1000).delay(6000).animate({marginTop:'0px'},1000);
$(".errorcontainer").html('Your Are You Human Math Is Incorrect!');
$(".errorcontainer").delay(1200).fadeIn(1000).delay(4000).fadeOut(1000);
$('input[type=submit]', $("#slickform")).removeAttr('disabled');
return false;
}
//CHECKING THE USER IS HUMAN
//CHECKING THE USER IS HUMAN
if (userscomment.val() == "") {
$(".slickbutton").animate({marginTop:'50px'},1000).delay(6000).animate({marginTop:'0px'},1000);
$(".errorcontainer").html('You Forgot To Leave A Message!');
$(".errorcontainer").delay(1200).fadeIn(1000).delay(4000).fadeOut(1000);
$('input[type=submit]', $("#slickform")).removeAttr('disabled');
return false;
}
//CHECKING THE USER IS HUMAN
/*
*
* POSTING DATA USING AJAX AND
* THEN RETREIVING DATA FROM PHP SCRIPT
*
*/
$.post(url,{ usersname: usersname.val(), usersemail: usersemail.val(), usersphone: usersphone.val(), userssubject: userssubject.val(), userscomment: userscomment.val(), usershuman: usershuman.val(), isvalid: isvalid } , function(data) {
if(data == 'success'){
$(".slickbutton").animate({marginTop:'50px'},1000).delay(6000).animate({marginTop:'0px'},1000);
$(".successcontainer").html(successmessage);
$(".successcontainer").delay(1200).fadeIn(1000).delay(4000).fadeOut(1000);
$("#name").val('');
$("#email").val('');
$("#phone").val('');
$("#subject").val('');
$("#comment").val('');
$("#human").val('');
$('input[type=submit]', $("#slickform")).removeAttr('disabled');
} else {
$(".slickbutton").animate({marginTop:'50px'},1000).delay(6000).animate({marginTop:'0px'},1000);
$(".errorcontainer").html(failedmessage);
$(".errorcontainer").delay(1200).fadeIn(1000).delay(4000).fadeOut(1000);
$('input[type=submit]', $("#slickform")).removeAttr('disabled');
return false;
}
});
}
);
});
Here's the php:
if(isset($_REQUEST["isvalid"])){
$youremail = "test#test.com";
$usersname = $_POST["usersname"];
$usersemail = $_POST["usersemail"];
$usersphonenumber = $_POST["usersphone"];
$mailsubject = "Contact From Your Slickform";
$subject = $_POST["userssubject"];
$usersmessage = $_POST["userscomment"];
$message =
"$usersname has contacted you from your site.
$subject:
Their Message is as follows:
$usersmessage
...............................................
Contact details:
Phone Number: $usersphonenumber
Email Address: $usersemail";
$headers = 'From:' . $usersemail . "\r\n";
mail($youremail, $mailsubject, $message, $headers);
echo "success";
} else {
echo "failed";
}
Any help is appreciated. Thank you!
Either do this:
$('#slickform').submit(function() { // remove the callback fn name
or make a global function and use it like this:
slickcontactparse() {
// all your code
}
$(document).ready(function(){
$('#slickform').submit(slickcontactparse); // call it here as callback
});