I am building a website that has a reservation. I use ajax to send information from forms into the another page which insert the information into my database. To make it even useful, I want to make a test connection into my database. After a user fills up all the fields required he will click the submit button and a test connection must check first before sending the data. And when the connection fails, it will tell the user that the connection is not set(maybe his internet connection is lost, or the server itself is failing). In that way, the website prevents prompting the user that their reservation data is sent, but actually NOT.
EDITED:
Here's my running and fixed code:
$("#esubmit2").click(function(){
var event2 = document.getElementsByName("eevent2")[0].value;
var engager2 = document.getElementsByName("eengager2")[0].value;
var contact2 = document.getElementsByName("econtact2")[0].value;
var eadd2 = document.getElementsByName("eeadd2")[0].value;
var venue2 = document.getElementsByName("evenue2")[0].value;
var datein2 = document.getElementsByName("edatein2")[0].value;
var message2 = document.getElementsByName("emessage2")[0].value;
var reg2 = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if(event2 == "" || event2 == " "){
$("#eevent2").focus();
return false;
}
else if(engager2 == "" || engager2 == " "){
$("#eengager2").focus();
return false;
}
else if(contact2 == "" || contact2 == " "){
$("#econtact2").focus();
return false;
}
else if(venue2 == "Venue:"){
$("#evenue2").focus();
return false;
}
else if(datein2 == "" || datein2 == " "){
$("#edatein2").focus();
return false;
}
else if(message2 == "" || datein2 == " "){
$("#emessage2").focus();
return false;
}
else if(eadd2 != ""){
if(reg2.test(eadd2) == false){
$("#eeadd2").focus();
$("#eeadd2").css("backgroundColor","#800517");
$("#eeadd2").css("color","#FFFFFF");
return false;
}
else{
sendreserve_event2(); // call function sendreserve()
return false;
}
}
else{
sendreserve_event2(); // call function sendreserve()
return false;
}
})
function sendreserve_event2(){ // send informations to database
var data_string = $("form#eform2").serialize(); // IMPORTANT
$.ajax({
type: "POST",
url: "submitreserve_eventpc.php",
data: data_string,
success: function(json) {
if(json == 1){
$("#eevent2").val("");
$("#eengager2").val("");
$("#econtact2").val("");
$("#eeadd2").val("");
$("#evenue2").val("Venue:");
$("#edatein2").val("");
$("#emessage2").val("");
$("#eeadd2").css("backgroundColor","#FFFFFF");
$("#eeadd2").css("color","#555");
alert("Reservation Successful!!! \n\nPlease wait for your reservation code to be send to your e-mail account or contact number.\n\nThank you!");
return false;
}
else{
alert("Sorry for the inconvenience but the connection to our database failed.\nPlease check you internet connection or refresh you page.\n\nIf one of the above failed please report to our admin.\nThank You.");
return false;
}
}//end success function
}); //end ajax call
return false; // IMPORTANT
}
submitreserve_eventpc.php:
if($test){
mysql_query("INSERT INTO tblevent(eventName,engager,contactNumber,emailAdd,venue,checkinDate,message) VALUES('$event2','$engager2','$contact2','$eadd2','$venue2','$datein2','$message2')");
$ok = 1;
}
else{
$ok = 0;
}
echo json_encode($ok);
If there's any improvement that you see please edit. For now this met my needs :)
You should do something like this.
Your php.file
<?php
$con=mysql_connect('localhost','root','root');
if($con){
// do insertion data here into the database
$sql = "Insert into table query";
if($sql){
echo "Data inserted successfully";
}else{
echo "Sorry! some error occured ".mysql_error();
}
}else{
echo "Unable to connect to the server";
}
?>
You could try something like this.
function sendreserve_event2(){ // send informations to database
var data_string = $("form#eform2").serialize(); // IMPORTANT
$.ajax({
type: "POST",
url: "submitreserve_eventpc.php",
data: data_string
}).done(function(data) {
data = $.parseJSON(data);
message = data.message;
if (message == "success")
{
$("#eevent2").val("");
$("#eengager2").val("");
$("#econtact2").val("");
$("#eeadd2").val("");
$("#evenue2").val("Venue:");
$("#edatein2").val("");
$("#emessage2").text("");
$("#eeadd2").css("backgroundColor","#FFFFFF");
$("#eeadd2").css("color","#555");
$("#esubmit2").blur();
alert("Reservation Successful!!! \n\nPlease wait for your reservation code to be send to your e-mail account or contact number.\n\nThank you!");
} else {
console.log(message);
}
});
return false; // IMPORTANT
}
In your PHP file could be changed to what is below.
$myDatabase = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$myDatabase)
{
$message = 'Could not connect: ' . mysql_error();
} else {
$event2 = $_POST['eevent2'];
$engager2 = $_POST['eengager2'];
$contact2 = $_POST['econtact2'];
$eadd2 = $_POST['eeadd2'];
$venue2 = $_POST['evenue2'];
$datein2 = $_POST['edatein2'];
$message2 = $_POST['emessage2'];
mysql_query("INSERT INTO tblevent(eventName,engager,contactNumber,emailAdd,venue,checkinDate,message) VALUES('$event2','$engager2','$contact2','$eadd2','$venue2','$datein2','$message2')");
$message = 'success';
}
$response = array('message' => $message);
echo json_encode($response); // This is the data that your AJAX function gets in .done
Related
After send my form data to php file its return if any error found. But its also return success before ajax redirect page. I want display error message only and if success, redirect another page.
ajax:
$("#msform").submit(function(){
$.ajax({
type:"post",
url:"pagesubmit.php",
data: $("#msform").serialize(),
dataType : 'json',
success: function(data){
if ( ! data.success) {
$(".help-block").fadeIn().html(data.error);
} else {
$(".help-block").fadeOut();
$("#msform")[0].reset();
window.location = 'http://dbsvawdez.com/' + data.success;
}
}
});
});
php:
include_once ("db.php");
global $dbh;
function check($name){
if(!$name || strlen($name = trim($name)) == 0){
$error ="* Username not entered";
}
else{
$name = stripslashes($name);
if(strlen($name) < 5){
$error ="* Name below 5 characters";
}
else if(!preg_match("/^([0-9a-z])+$/i", $name)){
$error ="* Name not alphanumeric";
}
else {
return 1;
}
}
}
$name = mysqli_real_escape_string($dbh, $_POST['name']);
$thisname = strtolower($name);
$retval = check($thisname);
if($retval ==1){ // if no error found
$success ='upage/userpage?user='.$_SESSION['username'].'';
}
$data = array();
$data['error'] = $error;
$data['success'] = $success;
if (!empty($data)) {
echo json_encode($data);
}
Solved the problem, in this way:
Ajax:
$("#msform").submit(function(){
// collect input name
ver name = var catag=$('#name').val();
$.ajax({
type:"post",
url:"pagesubmit.php",
data: $("#msform").serialize(),
success: function(data){
if ( data != 'success') {
$(".help-block").fadeIn().html(data);
} else {
$(".help-block").fadeOut();
$("#msform")[0].reset();
window.location = 'http://dbsvawdez.com/' + name;
}
}
});
});
php:
function check($name){
if(!$name || strlen($name = trim($name)) == 0){
echo "* Username not entered";
}
else{
$name = stripslashes($name);
if(strlen($name) < 5){
echo "* Name below 5 characters";
}
else if(!preg_match("/^([0-9a-z])+$/i", $name)){
echo "* Name not alphanumeric";
}
else {
return 1;
}
}
}
$name = mysqli_real_escape_string($dbh, $_POST['name']);
$thisname = strtolower($name);
$retval = check($thisname);
if($retval ==1){ // if no error found
echo 'success';
}
EDIT
Set your variables $success and $error
$success = "";
$error= "";
If you doesn't init them, you cannot use them and the .=operator is for concatenation not for set.
Then you should encode the response in php in JSON.
Something like
$response = json_encode(
array(
'success'=> true,
'route' => "mypage/info?user=$_SESSION['username']"
)
);
And return this, then access your response like you already do :
var success = response.success;
UPDATE
change this code to add an else statement :
if($retval ==1){ // if no error found
$success ='upage/userpage?user='.$_SESSION['username'].'';
}else{
$success = 'error';
}
and this line :
else {
return 1;
}
to :
else {
$error = 'none';
}
and in your javascript :
$("#msform").submit(function(){
$.ajax({
type :"post",
url :"pagesubmit.php",
data : $("#msform").serialize(),
dataType : 'json',
success : function(data){
if(data.success == 'error') {
$(".help-block").fadeIn().html(data.error);
}else{
$(".help-block").fadeOut();
$("#msform")[0].reset();
window.location = 'http://dbsvawdez.com/' + data.success;
}
}
});
});
I'm running some ajax on my website to handle form submission, However, For some reason whenever I check the response from PHP, it ignores my handling and goes straight to the bottom.
//Login Form Submission
$('form.loginform').on('submit', function (e) {
e.preventDefault();0
//Grab Data
var that = $(this),
url = that.attr('action'),
method = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: method,
data: data,
success: function (response) {
console.log("Ajax Response: \"" + response + "\"");
console.log(typeof response);
if(response === "0"){
document.getElementById('error_message').innerHTML = "Incorrect password";
document.getElementById('error_message').style.color = 'red';
document.getElementById('error_message').style.borderColor = 'red';
}else if(response === "1"){
window.location.href = "./index.php";
}else if(response === "2"){
document.getElementById('error_message').innerHTML = "Please fill all required fields.";
document.getElementById('error_message').style.color = 'red';
} else if(response === "3"){
document.getElementById('error_message').innerHTML = "That username does not exist. Please try again.";
document.getElementById('error_message').style.color = 'red';
document.getElementById('error_message').style.borderColor = 'red';
} else if(response === "4"){
document.getElementById('error_message').innerHTML = "Your account has been banned on this website. Please contact an administrator.";
document.getElementById('error_message').style.color = 'red';
document.getElementById('error_message').style.borderColor = 'red';
} else {
document.getElementById('error_message').innerHTML = "Error while logging in. Please try again.<br />If you continue to recieve this error, Please contact an administrator.";
document.getElementById('error_message').style.color = 'red';
document.getElementById('error_message').style.borderColor = 'red';
}
//This is the output from the php script
}
});
return false;
});
That is my current code, The output I get is
Ajax Response: "1"
String
However, It then goes straight to
'Error while logging in, Please contact an Administrator'
My question is Why is it ignoring the 'if' statements above the 'else', even though the response is '1'?
Try
response.trim() == "1"
since log shows its 1 and String so may be some white space is the issue.
I have some problems with jqGrid.
I've added a method that validates users input. If the department exist then it will show a warning message, "Department is Exist!"
Here's my jqGrid code:
afterSubmit: function(response, postdata){
var res = $.parseJSON(response.responseText);
if (res === "1") {
return [false,"Department Already Exist"];
} else {
return [true,"Sucess"];
}
}
And my php add method:
if($oper == 'add') {
$deptid = $_POST['idms_department'];
$deptnm = $_POST['department'];
if(checkUser($deptnm) == "FALSE"){
return "1";
} else {
$ins = "INSERT INTO ms_department(department) VALUES('$deptnm')";
if(mysql_query($ins)){
"Success INSERT msDept";
} else {
die("Failed : " .mysql_error());
}
}
mysql_close();
} else .... (another operation)
The message itself is not showing. How do you use the afterSubmit method properly?
thanks
UPDATE
i've change the method to
crudMessage = function(response,postdata){
var res = response.responseText; // response text is returned from server.
if (res === "1") {
return [false,"Department Already Exist"];
} else {
return [true,"Sucess"];
}
}
then removing the afterSubmit from the jqgrid body and add this line into the jqgrid navigation:
jQuery("#departments").jqGrid('navGrid','#pager-departments',{edit:true,add:true,del:true}, {closeAfterEdit: true},{beforeShowForm: function(form) { $('#idms_department', form).hide(); },closeAfterAdd:true},{afterSubmit: crudMessage},{closeAfterSearch:true},{});
here's newest php syntax:
include 'configuration.php';
function checkDepartment($department){
$query = "SELECT department FROM ms_department WHERE department ='$department' LIMIT 1";
$result= mysql_query($query);
return mysql_num_rows($result);
}
if($oper == 'add') {
$deptid = $_POST['idms_department'];
$deptnm = $_POST['department'];
if(checkDepartment($deptnm) == 1){
echo '1';
} else {
$ins = "INSERT INTO ms_department(department) VALUES('$deptnm')";
if(mysql_query($ins)){
"Success INSERT msDept";
} else {
die("Failed : " . mysql_error());
}
}
mysql_close();
} else
if($oper == 'edit'){ ....
In your code, why are you expecting res.insertStatus? From the snippet of PHP code that you provided, it seems you would want to write:
var res = $.parseJSON(response.responseText);
if (res === "User Already Exist!") {
Or maybe I am missing something? Have you tried debugging your code?
That should explain why the alert is not appearing.
Also, for what its worth, according to the jqGrid documentation for form editing:
afterSubmit
fires after response has been received from server. Typically used to display status from server (e.g., the data is successfully saved or the save cancelled for server-side editing reasons). Receives as parameters the data returned from the request and an array of the posted values of type id=value1,value2.
When used this event should return array with the following items [success, message, new_id]where
success is a boolean value if true the process continues, if false a error message appear and all other processing is stopped. (message is ignored if success is true).
new_id can be used to set the new row id in the grid when we are in add mode.
afterSubmit : function(response, postdata)
{
…
return [success,message,new_id]
}
Based on these docs, your final code should remove the alert and just use jqGrid directly:
if (res === "User Already Exist!") {
return [false, "TODO: put your error message here"];
}
Guys I'm trying to make a Log in form by using Ajax and PHP. Every-time when I submit the form I'm getting the right response, but the problem here is that I have an "IF CONDITION" in my Javascript file did not execute while I get a "success" response. I don't know why. This is my code, please anybody help.
Ajax File
function ajaxObj( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
Javascript File handling Log in - The problem is here in this file
function signin(){
var logstat = _("logstat");
var loge = _("SignInEmail").value;
var logp = _("SignInPasswordActive").value;
if(loge == "" || loge == "Email address" || logp == ""){
logstat.innerHTML = "Fill out all of the form data.";
} else {
_("loginbtn").style.display = "none";
logstat.innerHTML = 'please wait ...';
var ax = ajaxObj("POST", "signin.php");
ax.onreadystatechange = function() {
if(ajaxReturn(ax) == true) {
if(ax.responseText != "success"){
logstat.innerHTML = ax.responseText;
_("loginbtn").style.display = "block";
} else {
//Here is the problem I get success in Ajax Response, but this condition did not run
logstat.innerHTML = "login success";
_("loginbtn").style.display = "block";
}
}
}
ax.send("le="+loge+"&lp="+logp);
}
}
PHP File
<?php
if(isset($_POST['le']) && isset($_POST['lp'])){
$p = $_POST['lp'];
require_once('includes/database.php');
include_once('randStrGen.php');
$e = $_POST['le'];
$p_hash = md5($p);
$ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
if($e == "" || $e == "Email address" || $p == ""){
echo "Fill out all of the form data.";
exit();
} else {
$sql = "SELECT id, email, password FROM users WHERE email='$e' AND activated='1' LIMIT 1";
$query = mysqli_query($db->connection, $sql);
$numrows = mysqli_num_rows($query);
if($numrows == 0){
echo "This account is not exist";
exit();
}else{
$row = mysqli_fetch_array($query);
$db_id = $row['id'];
$db_em = mysqli_real_escape_string($db->connection, $row['email']);
$db_ps = substr($row['password'],10,-10);
if($p_hash != $db_ps){
echo "Email or Password combination failed";
exit();
}else{
//This is the successful Log in condition
echo "success";
exit();
}
}
exit();
}
exit();
}
?>
Try swaping the condition so checking if it's equals (even ===) to 'success' and do the rest in the else clause
I have a registration form which when filled and "Register" button pressed is being checked by js, to find empty fields and to check availability of username, or if email or mobile num was already used by sending info through ajax to php and receiving answer. But my js won't work all the way through. This is my js script:
$("#reg_button").click(function(){
user = $("#usr").val();
pass = $("#psw").val();
fname = $("#first_name").val();
sname = $("#second_name").val();
dateb = $("#date_birth").val();
email = $("#email").val();
mobnum = $("#mob_num").val();
if(user == ""){
alert("First name must be filled out");
$('#usr').focus();
return false;
}else if(pass == ""){
alert("Password must be filled out");
$('#psw').focus();
return false;
}else if(fname == ""){
alert("First name must be filled out");
$('#first_name').focus();
return false;
}else if(sname == ""){
alert("Second name must be filled out");
$('#second_name').focus();
return false;
}else if(dateb == ""){
alert("Date of birth must be filled out");
$('#date_birth').focus();
return false;
}else if(email == ""){
alert("Email must be filled out");
$('#email').focus();
return false;
}else if(mobnum == ""){
alert("Mobile number must be filled out");
$('#mob_num').focus();
return false;
}else{
ajaxCheck();
}
function ajaxCheck(){
$.ajax({
type: "POST",
url: "http://imes.*********.com/php/check_info_reg.php",
data: "usr="+user+"&email="+email+"&mob_num="+mobnum,
dataType: "json",
success: function(json){
if(json.success){
var user_conf = json.data.usr;
var email_conf = json.data.email;
var mob_conf = json.data.mob;
if(user_conf == "taken"){
alert("Username already taken. Choose another one.");
$('#usr').focus();
return false;
}
if(email_conf == "taken"){
alert("Email already registered. If you lost your password, retrieve it on login page.");
$('#email').focus();
return false;
}
if(mob_conf == "taken"){
alert("Mobile number already registered. If you lost your password, retrieve it on login page.");
$('#mob_num').focus();
return false;
}
}else{
//Here could go another ajax, for actualy sending the
//info into the php script which sends it to database.
}
},
beforeSend: function() { $.mobile.showPageLoadingMsg(); }, //Show spinner
complete: function() { $.mobile.hidePageLoadingMsg() }, //Hide spinner
});
return false;
}
});
And my php:
<?php
$username = mysql_real_escape_string($_POST['usr']);
$email = mysql_real_escape_string($_POST['email']);
$mob_num = mysql_real_escape_string($_POST['mob_num']);
include('mysql_connection.php');
mysql_select_db("jzperson_imesUsers", $con);
$sql1 = mysql_query("SELECT * FROM registered_user WHERE username='$username'");
$sql2 = mysql_query("SELECT * FROM registered_user WHERE email='$email'");
$sql3 = mysql_query("SELECT * FROM registered_user WHERE mobile_num='$mob_num'");
$res1 = mysql_num_rows($sql1);
$res2 = mysql_num_rows($sql2);
$res3 = mysql_num_rows($sql3);
if(isset($username) && !empty($username){
if($res1 >= 1){
//JSON message: Username already taken. Choose different.
echo json_encode(array('success'=>true, 'usr'=>"taken"));
}
}
elseif(isset($email) && !empty($email)){
if($res2 >= 1){
//JSON message: Email already registered. Retrieve on "login"(login => link).
echo json_encode(array('success'=>true, 'email'=>"taken"));;
}
}
elseif(isset($mob_num) && !empty($mob_num)){
if($res3 >= 1){
//JSON message: Mobile number already registered. Retrieve on "login"(login => link).
echo json_encode(array('success'=>true, 'mob'=>"taken"));
}
}
else{
echo json_encode(array('success'=>false));
}
?>
You are missing a parenthesis in your php file:
if(isset($username) && !empty($username){
Should be
if(isset($username) && !empty($username)){