AJax ignoring response - php

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.

Related

Not redirecting to another page after successful ajax request complete

I am validating a sign In form through ajax. After successful validation the form is not redirecting to the required page.
Ajax Codes
function login_submit(){
var stat="";
$("#submit").val("Loging in...");
$.ajax({
type: "POST",
url: "php/login.php",
data: {
uname: $("#uname").val(),
pass : $("#pass").val()
},
success: function(result) {
if(result=="parent"){
window.location = "http://localhost:90/auction/augeo/admin/parent_admin/index";
}
else if(result == "sucess_normal"){
window.location.assign("../normal_admin");
}
else if(result == "deactivated account") {
window.location.assign("reactivate_account/");
}
else if(result == "banned account") {
window.location.assign("banned_account/");
}
else{
$("#submit").val("Login");
$("#error_msg").css({color: 'red'});
document.getElementById("error_msg").innerHTML= result;
stat = false;
}
}
});
if(!stat)
return false;
}
The php code
if(isset($_POST['uname']) && isset($_POST['pass'])){
$username = encode($_POST['uname']);
$password = encrypt(encode($_POST['pass']));
// check if entered username and password is in the database
$result = mysqli_query($conn,"SELECT * From admin_account where admin_account.username = '$username' AND admin_account.password = '$password' ");
if($row = mysqli_num_rows($result) == 1){
$found = mysqli_fetch_array($result);
if($found['state'] == 1){
$account_id = $found['account_id'];
setcookie("admin_id", $account_id, time() + (86400 * 30), "/");
$_SESSION['admin_id'] = $account_id;
$result1 = mysqli_query($conn,"SELECT role_id From admin where admin_id = '$account_id'");
$found1 = mysqli_fetch_array($result1);
$_SESSION['account_type'] = $found1['role_id'];
if($found1['role_id'] == "1"){
echo "parent";
//header("Location: http://localhost:90/auction/augeo/admin/parent_admin/index");
}else{
echo "sucess_normal";
}
}
elseif($found['state'] == 2){
echo "banned account";
}
else{
$_SESSION['deactivated_id'] = $found['account_id'];
echo "deactivated account";
}
}
else{
echo "Incorrect Username or Password";
}
}
I have tried all I could do but to no avail. I want to check if result=="parent" and if result=="parent" it should redirect to window.location = "http://localhost:90/auction/augeo/admin/parent_admin/index"; but instead it is echoing out parent.
You say "it is echoing out parent". But this should never happen with the AJAX code you supplied.
So I'm suspecting that you have a form that's running its own default submit, and that is what you're seeing.
You may want to check out this answer:
$('#idOfYourForm').submit(function() {
var $theForm = $(this);
// This is a button or field, right? NOT the form.
$("#submit").val("Logging in...");
$.post(
'php/login.php',
{
uname: $("#uname").val(),
pass : $("#pass").val()
}
).done(function(result) {
// check the result
alert("Server said: " + result);
});
// prevent submitting again
return false;
});
You get the button with
$("#submit")
This is ok, but if the button is defined as:
<input type="submit" id="submit" value="..." />
You'll get a subsequent submit of the form the button is defined in.
To avoid this, a far easier solution to the other suggested, is to not use a submit button at all. Instead, use a simple action button. These are two examples, the second of which is probably better because it is easier to design with bootstrap/HTML5/CSS...
<input type="button" id="submit" value="..." />
or better:
<button type="button" id="submit">...</button>
In case of slow server/network, you'll probably want to aid AJAX usability by disabling the button:
$("#submit").val("Logging in...").prop("disable", "disable");
This helps avoiding multiple submits when the server is slow and the user impatient.

how to send recaptcha response data using ajax to php file

I am tring to send data from ajax but getting post error. I also took help form ReCaptcha 2.0 With AJAX but still I am getting the same POST error in php fle.
$("#submit").click(function(){
var name = $("#name").val();
var mobile = $("#mobile").val();
var email = $("#email").val();
var subject = $("#subject").val();
var message= $("#message").val();
if(name=='' || mobile=='' || email=='' || subject=='' || message==''{
$("#errmsg").html("All fields are required");
} else {
//$("#reqmsg").html(username);
$.ajax({
type: "POST",
url: "insertquery.php",
data: "name="+name+"&mobile="+mobile+"&email="+email+"&subject="+subject+"&message="+message+"&g-recaptcha-response="+grecaptcha.getResponse(),
success: function(data){
if(data=="ok"){
alert("query submitted");
window.location="http://www.intuitioninteriors.in";
} else {
$("#errmsg").html("some went wrong.please try again");
}
}
});
return false;
}
});
Above is the ajax file.
include("database.php");
$name=$_POST["name"];
$mobile=$_POST["mobile"];
$email=$_POST["email"];
$subject=$_POST["subject"];
$message=$_POST["message"];
$captcha = "";
if (isset($_POST["g-recaptcha-response"]))
$captcha = $_POST["g-recaptcha-response"];
$url="http://www.google.com/recaptcha/api/siteverify";
$privatekey="xxxxxxxxxxxxxxxxxxxxxxxxx";
$response = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$privatekey."&response=".$captcha."&remoteip=".$_SERVER["REMOTE_ADDR"]), true);
if ($response["success"] != false) {
$query="insert into query values(NULL,'$name','$mobile','$email','$subject','$message')";
$result=mysqli_query($conn,$query)or die(mysqli_error($conn));
if($result){
echo 'ok';
} else {
echo 'not ok';
}
} esle{
echo 'not verified';
}
This is php file.
Error: POST http://intuitioninteriors.in/insertquery.php 500 (Internal Server Error)
How can I fix it?

Javascript, Php, Ajax

I have a problem with this my script.
$("#login").click(function(event) {
event.preventDefault();
var email = $("#email").val();
var pass = $("#password").val();
$.ajax({
url : "login.php",
method: "POST",
data: {userLogin:1, userEmail:email, userPassword:pass},
success : function(data){
if(data == "1"){
alert(data);
}
}
})
I want it to alert a value that I am getting from an echo in another php file
<?php
if(isset($_POST['userLogin'])){
$email = mysqli_real_escape_string($con, $_POST['userEmail']);
$password = md5($_POST['userPassword']);
$sql_login = "SELECT * from database where email = '$email' AND password = '$password'";
$query_login = mysqli_query($con, $sql_login);
$count_login = mysqli_num_rows($query_login);
if($count_login == 1){
$row_login = mysqli_fetch_assoc($query_login);
$_SESSION['uid'] = $row_login['user_id'];
$_SESSION['name'] = $row_login['first_name'];
echo "1";
}
}
?>
If I didn't put the alert(data) in an if condition, it displays the value I echo, but I need the condition to enable the right user logged in.
What can IF can also ELSE.
In your ajax add the else conditions to see if it helps uncover the issue:
if (data == "1") {
alert('youre in');
} else {
alert('try again');
}
And in your php, also account for the else condition (and do strict checking on that count of rows with ===):
if ($count_login === 1) {
// code ...
echo '1';
} else {
echo 'Sorry, the login is incorrect';
}
It works fine for me, if i always echo "1", the alert(data) show 1, in an if condition and out, pls, echo something else if isset($_POST['userLogin']) or $count_login == 1 are false, or put an
error : function(data) {
$('body').append("<div>"+data.responseText+"</div>")
}
in your ajax, to debug the prob. Because in your .php file, when you echo nothing, it returns a data in error, not in success, maybe that's your prob.

check database connection after button is click

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','$message‌​2')");
$message = 'success';
}
$response = array('message' => $message);
echo json_encode($response); // This is the data that your AJAX function gets in .done

JQuery/Ajax calling function incorrectly

Summary: This is a basic, stand alone web form. Just html form, with a JQuery included for the functions.
I have a form that checks email and username for uniqueness and validity (of email). I'm using a JQuery onChange event to call each function, which is an Ajax call to a php file.
The JQuery for the username check is as follows:
$("#username").change(function() {
var username = $("#username").val();
var msgbox_username = $("#username_status");
var dataString = "username="+ username;
$("#username_status").html('<img src="images/loader.gif">Checking Availability.');
if (username != "" && username.length >= 6){
$.ajax({
Type: "POST",
url: "functions/check_username.php",
data: dataString,
success: function(msg_username) {
$("#username_status").ajaxComplete(function (event, request) {
if (msg_username == 'Username Ok') {
$("#username").removeClass("red").addClass("green");
msgbox_username.html('<font color="Green">Available</font>');
} else {
$("#username").removeClass("green").addClass("red");
msgbox_username.html(msg_username);
}
});
}
});
return false;
} else {
$("#username").removeClass("green").addClass("red");
msgbox_username.html('<font color="Red">Username of 6 or more characters is required</font>');
}
});
The check_username.php file is as follows:
<?php
$username = $_GET["username"];
include_once("../includes/connect.php");
$query = "SELECT username
FROM sss_users
WHERE username = '$username'";
$result = mssql_query($query);
if(mssql_num_rows($result) > 0 && strlen($username) >= 6) {
echo '<font color="#cc0000"><strong>' . $username . '</strong> is already in use. </font>';
} else {
echo 'Username Ok';
}
?>
Continuing with the pattern, the email JQuery:
$("#email").change(function() {
var email = $("#email").val();
var msgbox_email = $("#email_status");
var dataString = "email="+ email;
$("#email_status").html('<img src="images/loader.gif">Checking Availability.');
var atpos = email.indexOf("#");
var dotpos = email.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= email.length){
$("#email").removeClass("green").addClass("red");
msgbox_email.html('<font color="Red">Valid Email Required</font>');
} else {
$.ajax({
Type: "POST",
url: "functions/check_email.php",
data: dataString,
success: function(msg_email) {
$("#email_status").ajaxComplete(function (event, request) {
if (msg_email == 'Email Ok') {
$("#email").removeClass("red").addClass("green");
msgbox_email.html('<font color="Green">Available</font>');
} else {
$("#email").removeClass("green").addClass("red");
msgbox_email.html(msg_email);
}
});
}
});
return false;
}
});
And the email PHP:
<?php
$email = $_GET["email"];
include_once("../includes/connect.php");
$query = "SELECT email
FROM sss_users
WHERE email = '$email'";
$result = mssql_query($query);
if(mssql_num_rows($result) > 0) {
echo '<font color="#cc0000"><strong>' . $email . '</strong> is already in use. </font>';
} else {
echo 'Email Ok';
}
?>
They each work seperately, but if I put an invalid username in the box and then put a valid email, somehow the check_username.php file is called and no matter what is in the box (valid or not) it thinks it's a valid username.
An example is:
All functions are called on the OnChange Event
1) type in the username asdfasdf (which is available)
2) Delete the username asdfasdf from the text box (this works correctly, displaying a username must have at least 6 characters)
3) type in any valid email
Result: the valid email works correctly, but the username field (which is blank) recalls what was there before (asdfasdf) and says it is a valid username (even though the field is still blank.)
Hope this makes sense. Any suggestions?
SOLUTION
As noted below, the .ajaxComplete() was calling all functions with that tag. Therefore, when I made the following changes it worked:
$("#username_status").ajaxComplete(function (event, request) { ... code here ... });
changed to:
$("#username_status").ajaxComplete(function (event, request, settings) { ... code and new if statement ... });
And then I wrapped
if(settings.url == 'functions/check_username.php') {}
around the validation code. This process was done for both the username and email validation.
http://api.jquery.com/ajaxComplete/
Whenever an Ajax request completes, jQuery triggers the ajaxComplete
event. Any and all handlers that have been registered with the
.ajaxComplete() method are executed at this time.
Maybe both handlers are being fired.

Categories