AJAX not returning a variable from php - javascript

I know there is a few questions like this on here. but I have done a lot of researching and bug fixing all day to try work out why my ajax does not return a response from the php file. All I want is for it to tell me a user has been registered so I can let the user move on with the signing up process. And I just need someones wise guidance to tell me what I am doing wrong!!
so I wont bore you with the validation part of the js file just the ajax
if(ValidationComplete == true){
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(register, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url:url,
type:type,
data: data,
dataType: 'json',
success: function(result){
alert(result.status);
console.log(result.data);
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
return false;
} else {
return false;
}
currently with this, if I remove the dataType bit the alert bit happens but currently with it there nothing does.
again I will just skip to the chase on the php file
$query = "INSERT INTO person
VALUES('','$first_Name','$surname','$email','$dob','$password',
'1','','0','1','','','','$emailCode')";
if($query_run =mysql_query($query)) {
echo json_encode(array("response"='true'));
Any help would be amazing!!!!!
updated code:
<?php
if( isset($_POST['firstname']) &&
isset($_POST['surname']) &&
isset($_POST['email']) &&
isset($_POST['day']) &&
isset($_POST['month']) &&
isset($_POST['year']) &&
isset($_POST['password']) &&
isset($_POST['re_type_password'])){
$first_Name = $_POST['firstname'];
$surname = $_POST['surname'];
$email = $_POST['email'];
$password = $_POST['password'];
$day = $_POST['day'];
$month = $_POST['month'];
$year = $_POST['year'];
$re_type_password = $_POST['re_type_password'];
$emailCode = md5($_POST['$first_Name'] + microtime());
if(!empty($first_Name)&&
!empty($surname)&&
!empty($email)&&
!empty($day) &&
!empty($month) &&
!empty($year) &&
!empty($password)&&
!empty($re_type_password)){
if(strlen($firstname)>30 || strlen($surname)>30 || strlen($email)>50){
echo 'the data enetered is to long';
} else {
if($password != $re_type_password){
echo 'passwords do not match, please try again.';
} else{
$query = "SELECT email FROM person WHERE email ='$email'";
$query_run = mysql_query($query);
if(mysql_num_rows($query_run)==1){
echo 'Email address already on databse';
} else{
if($day>31 || $month>12){
echo 'date of birth wrong';
} else{
$dob= $year.'-'.$day.'-'.$month;
$query = "INSERT INTO person
VALUES('','$first_Name','$surname','$email','$dob','$password'
,'1','','0','1','','','','$emailCode')";
if($query_run =mysql_query($query)) {
email($email, 'Email Confirmation', "hello ". $first_Name." ,
\n\n you need to activate your account so click the link ");
$return_data['status'] = 'success';
echo json_encode($return_data);
} else {
echo #mysql_error();
}
}
}
}
}
} else {
echo "<p id='error'> All fields are required. Please try again.</p>";
}
}
?>
<?php
} else if (loggedIn()) {
echo 'you are already registed and logged in';
}
?>
</body>
</html>

the last line it should be
echo json_encode(array("response"=>'true'));
see the added > in the array declaration, that is used to assign arrays with keys.
also in general you should put a error capture in your ajax statement, see this answer for more info
EDIT: Ok wow, that's some spaghetti code you have there, but after a little clean-up your problem is too many closing braces } you have to remove the } just before the following line also get rid of the closing and opening tags around this line, they serve no use.
} // <------- THIS ONE!
} else if (loggedIn()) {
echo 'you are already registed and logged in';
}
I should also mention two other issues with your code
You are accepting input from the user without cleaning it up and testing it properly. This is no no read here to find out more
You are using mysl_ functions, these are old and depreciated they are also security risks. Check out PDO instead
EDIT:
Add ini_set('error_reporting',1); to the top of your php script.

Related

jQuery AJAX Getting json parseError in the console and responses goes to error function but php script runs fine

I tried researching a lot before posting here.
There are two files login.php and login-validation.php
Login.php file contains code including login form and jQuery AJAX script to call login.validation.php
--- Code of login.php ---
$(document).ready(function() {
$('#login-form').submit(function(e) {
e.preventDefault();
mobile_no = $('#mobile_no').val();
upassword = $('#upassword').val();
console.log(mobile_no, upassword);
$.ajax({
type: "POST",
url: "server/login-validation.php",
data: {
Mobile_no: mobile_no,
Password: upassword
},
cache: false,
dataType:'json',
success: function(response) {
console.log("Data gone successfully");
if(response["type"] == 'LoginSuccess'){
$('#success-message').text(response); // This works but not below ones
}
if(response["type"] == 'WrongCredentials'){
$('#success-message').text(response);
}
else{
$('#success-message').text(response);
}
},
error: function(xhr, textStatus, errorThrown){
console.log(xhr.responseText); Shows my echo message i.e. Wrong credentials for wrong credentials
console.log(textStatus); // Shows parseError
console.log(errorThrown); // Shows SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
}
});
});
});
</script>
---Code of login.validation.php---
session_start();
$message = array(); //Creating array variable to display custom messages depending on [TYPE]
//Require DB
require_once('db.php');
//Get values from the login form
$Mobile_number = $mysqlconnect->real_escape_string(trim($_POST['Mobile_no']));
$Password = $mysqlconnect->real_escape_string(trim($_POST['Password']));
//Query database for valid input match
$validation = "SELECT * from team_captain WHERE Mobile_Number = '$Mobile_number'";
$query = $mysqlconnect->query($validation);
$result = mysqli_num_rows($query);
if($result > 0){
$fetch_pass = mysqli_fetch_array($query);
$password_hash = $fetch_pass['User_Password'];
if(password_verify($Password,$password_hash))
{
$message["type"] = 'LoginSuccess';
$_SESSION['sess_username'] = $fetch_pass['Full_Name'];
}
else{
$message["type"] = 'WrongCredentials';
echo "Wrong credentials". $mysqlconnect->error;
}
}
else{
$message["type"] = 'WrongMobile';
echo "Mobile number doesn't exists";
}
header('Content-type: application/json');
echo json_encode($message);
?>
Tried dataType: 'json' - Didn't work
Tried without dataType - Didn't work
Php script is running properly with right error messages for different "if" statements but AJAX responses goes to error:function() rather than success: function()
In the network tab - The response type is JSON and it displays [type] i.e [WrongCredentials]
Not understanding what is wrong here. Any help would be appreciated.
You need to parse the JSON response using jQuery.parseJSON()
var data = jQuery.parseJSON(response);
Now, you can check it
if(data.type == "LoginSuccess"){
// do something
}elseif(data.type == "Wrong Password"){
// do something else
}
And remove echo from your php code
session_start();
$message = array(); //Creating array variable to display custom messages depending on [TYPE]
//Require DB
require_once('db.php');
//Get values from the login form
$Mobile_number = $mysqlconnect->real_escape_string(trim($_POST['Mobile_no']));
$Password = $mysqlconnect->real_escape_string(trim($_POST['Password']));
//Query database for valid input match
$validation = "SELECT * from team_captain WHERE Mobile_Number = '$Mobile_number'";
$query = $mysqlconnect->query($validation);
$result = mysqli_num_rows($query);
if($result > 0){
$fetch_pass = mysqli_fetch_array($query);
$password_hash = $fetch_pass['User_Password'];
if(password_verify($Password,$password_hash))
{
$message["type"] = 'LoginSuccess';
$_SESSION['sess_username'] = $fetch_pass['Full_Name'];
}
else{
$message["type"] = 'WrongCredentials';
}
}
else{
$message["type"] = 'WrongMobile';
}
header('Content-type: application/json');
echo json_encode($message);
?>

Broke my javascript with if else

I feel like I'm missing something really simple, so I've decided to get over my stubbornness and actually ask a question here instead of wasting any more time.
I've started making my personal blog from scratch (for the personal challenge and learning experience of it) not too long ago and I'm currently on writing the code for email validation; the standard send email with token & email GET variables. It works properly (hooray), but there's one problem that was introduced when I decided to add email validation to the back end. The ajax call is still successful and returns the right string; however, once I added an else if statement to my javascript to handle showing error messages for invalid email that gets (or is forced) through, it seems to act as though there isn't a curly bracket--my success boolean which determines the success/failure of my alert is set to false and the string displayed to the user is also not as I intended. Here's my code and a screenshot to illustrate:
*I changed the if..else to a switch to see if it would change anything--it didn't.
//JAVASCRIPT
$("form").submit(function(event) {
if(request) request.abort;
var message = "";
var success = false;
var formMessageBox = document.getElementById("form-message");
var form = $(this);
var inputs = form.find("input");
var data = inputs.serialize();
inputs.prop("disabled", true);
request = $.ajax({
url: "php/form.php",
type: "post",
data: data
});
request.done(function(data) {
var submission = data;
switch (submission) {
case "success":
message = "You're good to go! You'll be receiving an email shortly from <strong>my_email</strong>, just to make sure everything's in the green";
$("form").innerHTML = "";
success = true;
break;
case "fail":
message = "Seems this email is already in my database; you may have submitted twice, or somebody might have hijacked your email--don't worry, it's more than likely the former.";
success = false;
break;
default:
message = submission;
success = false;
break;
}
});
request.always(function() {
inputs.prop("disabled", false);
if(success) {
formMessageBox.classList.add("alert-success");
if (formMessageBox.classList.contains("alert-danger")) formMessageBox.classList.remove("alert-danger");
}
else {
formMessageBox.classList.add("alert-danger");
if (formMessageBox.classList.contains("alert-success")) formMessageBox.classList.remove("alert-success");
}
formMessageBox.innerHTML = message;
});
event.preventDefault();
})
//PHP
<?php
if(!$_POST["email"]) {
echo "Please enter an email address";
exit(0);
}
if($_POST["email"] AND !filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)) {
echo "Please enter a valid email address";
exit(0);
}
$dbconn = mysqli_connect("localhost","username", "password", "db");
if (mysqli_connect_error()) die("There seems to be something wrong. Sorry, try again later");
require_once('CryptoLib.php');
$token = CryptoLib::randomString(16);
$name = isset($_POST['name']) ? $_POST['name'] : "user";
$email = $_POST['email'];
$emailTo="$email";
$subject="Web Devs' Corner Verification";
$body="http://www.allen-mcintoshii.com/webdevscorner/php/verify.php?conf-token=".$token."&email=".$email;
$headers="From: my_email";
$query = "INSERT INTO `users` (`name`, `email`, `conf_token`) VALUES ('$name', '$email', '$token')";
$result = mysqli_query($dbconn, $query);
if ($result AND mail($emailTo, $subject, $body, $headers)) echo "success";
else echo "fail"; ?>
My 'successful error'
To be honest, it's not all that critical, but it definitely is not what I intend to happen, so why not use this little quirk as a chance to learn something? Thanks in advance to everyone who decides to help me out.
Well, while I was trying to do something similar for another small project, I actually found my own soloution. I'll just leave it here in case anyone finds themselves in a similar predicament.
//PHP
<?php
session_start();
$errors = array();
$errors[] = "You have been successfully signed up! Welcome to your diary!";
$min_chars = 8;
$email = $_POST['email'];
$password = $_POST['password'];
if (!$email) {
$errors[] = "Please enter an email address.";
}
if ($email AND !filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = "Please enter a valid email address";
}
if (!$password) {
$errors[] = "Please enter a password.";
}
else {
if (strlen($password) < $min_chars) $errors[] = "Your password must be at least $min_chars characters";
if (!preg_match('`[A-Z]`', $password)) $errors[] = "Your password is required to have at least on capital letter";
}
if (!$errors[1]) {
$dbconn = mysqli_connect(args) //just hiding what needs to be hidden here;
if (mysqli_connect_error()) die("There seems to be something wrong. Sorry, try again later");
$query = "SELECT * FROM users WHERE `email` ='".mysqli_real_escape_string($dbconn, $email)."'";
$results = mysqli_num_rows(mysqli_query($dbconn, $query));
if ($results != 0) $errors[] = "We're sorry, that email is already in our database, did you mean to log in?";
else {
$query = "INSERT INTO `users` (`email`, `password`) VALUES ('".mysqli_real_escape_string($dbconn, $email)."', '".password."')";
$result = mysqli_query($dbconn, $query);
$_SESSION['id'] = mysqli_insert_id($dbconn);
}
}
if ($errors[1]) session_destroy();
echo json_encode($errors);
?>
//Javascript
$(document).ready(function() {
var msgBox = $("#message-box");
$("#signup").submit(function(e) {
e.preventDefault();
var formData = $(this).serialize();
$.post("signup.php", formData, function(data) {
var success = data.length == 1 ? true : null,
numErrors = data.length,
errors = "";
if (success != null) {
msgBox.addClass("alert-success");
msgBox.removeClass("alert-danger");
msgBox.html(data[0]);
}
else {
msgBox.addClass("alert-danger");
msgBox.removeClass("alert-success");
var i;
for (i = 1; i < numErrors; i++) {
errors = errors + "<li>" + data[i] + "</li>";
}
msgBox.html("<ul>" + errors + "</ul>");
}
}, "json")
})
$("#login").submit(function(e) {
$.post()
})
})
Instead of trying to return different strings in the event of pass/fail, I decided to let PHP return one JSON object at the end no matter what. By placing the success message at the very top and pushing any error messages as the code moves along, it becomes way easier to just check if the return data's length is only 1 or greater. If it's 1, there were no errors and everything went fine; else, a for loop iterates through all the returned messages starting from the second one, effectively printing out all errors occurred. I hope this helps anybody who found themselves in a similar bind

Live username Checking is not working

I am trying to make register page with jquery and php where user put his username and while he is inserting in text box his username, my website check immediately if it is available or not and show! But my code is not working.
Here is my js code :
$(".r74re").keyup(function (e){
var user_name = $(this).val();
if(user_name.length >= 4)
$.post('liveusername.php', {'username':user_name}, function(data) {
$('.step1 input.usrname:focus').css({
'background': '#fff url("images/loader.gif") 275px no-repeat',
'background-size':'10px 20px'
});
setTimeout(function (){
if(data.success){
console.log("in positive " + data);
$('.step1 input.usrname:focus').css({
'background-color': 'lightgreen',
'background-size':''
});
}else{
console.log("in negative " + data);
$('.step1 input.usrname:focus').css({
'background-color': 'red',
'background-size':''
});
}
}, 1000);
});
Here is my php code that $.Post call when keyup event is :
include ("dbcon.php");
include ("funchuge.php");
if(isset($_POST["username"]))
{
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
die();
}
//sleep(1);// for animating
if(strlen($_POST["username"]) > 3){
selfValidator($_POST["username"]);
$username = filter_var($_POST["username"], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW|FILTER_FLAG_STRIP_HIGH);
$statement = $conn->prepare("SELECT username FROM users WHERE username=:usname");
$statement->bindparam(':usname', $username);
$statement->execute();
if($statement->fetch()){
$message = "ItExists";
echo json_encode(['success' => true, 'messages' => $message]);
}else{
$message = "NotExists";
echo json_encode(['success' => false, 'messages' => $message]);
}
}
}
I test a lot and i found problem in js code in line if(data.success) this condition is not working.. it always show me else condition if user allso exists.. i dont know why happening this ? Someone can help me found out my problem.
You need to parse the returned PHP string into JSON before you can access it like an object. Add this line above your setTimeout.
data = JSON.parse(data);

Using Javascript to run a php script to check username

I've been trying to build a registeration form for a website I am building. I can do the basics but I want it to check the username availability without reloading the page.
JAVASCRIPT
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script>
$(document).ready(function()
{
$("#Username").focusout(function()
{
//Check if usernane if available
var username = $("#Username").val();
$.post("scripts/check_username.php", {username: username}, function(data)
{
if(data == 'false')
{
alert('Username not available');
$("#Username").setCustomValidity("This username is already taken!");
}
else
{
alert('Username available');
}
});
return false;
});
});
</script>
HTML
<form id="registerForm">
<table>
<tr><td>Username</td><td><input id="Username" class='textInput' type='text' name='username' required></td></tr>
PHP SCRIPT
<?php
include 'open_connection.php';
$result = 'true';
$username = mysql_real_escape_string($_POST['username']);
$result = mysql_query("SELECT * FROM tblMembers WHERE Username='$username'");
while($row = mysql_fetch_array($result))
{
$result = 'false';
}
echo $result;
?>
When I leave the textbox it says username available no matter what. I placed a username "test" in the database... no luck
Please help
PHP:
$output = 'true';
$username = mysql_real_escape_string($_POST['username']);
$result = mysql_query("SELECT * FROM tblMembers WHERE Username='$username'");
while($row = mysql_fetch_array($result))
{
$output = 'false';
}
echo $output;
Ans Script:
<script>
$(document).ready(function()
{
$("#Username").focusout(function()
{
//Check if usernane if available
$.post("scripts/check_username.php", {username: $("#Username").val()}, function(data)
{
if(data =='false')
{
$("#Username").setCustomValidity("This username is already taken!");
}
else
{
alert('Username available');
}
});
return false;
});
});
</script>
By the way, don't use mysql_* function, they're deprecated. use Mysqli or PDO. Next thing is you forgot to put semi-colon that the end of your statements !
You specify $("#Username").value do you mean to use $("#Username").val()?
$('#Username').value is probably returning you rubbish which will not exist in your DB.
Do you use Developer Tools or Firebug?
It would be easy to see where the issue lies if you examined the $.post to check_username.php:
(1) is the correct post request being sent? I think your data object should be {"username":username}
(2) is your script responding true? or something else? You only know it's not returning false by the way your if statement is structured.

JavaScript Prompt Box Cancel Button?

I have a JavaScript function as follows:
function popup(username) {
var req = createAjaxObject();
var message = prompt("Message:","");
if(message != ""){
req.onreadystatechange = function() {
if (req.readyState == 4) {
alert(req.responseText);
}
}
req.open('POST','getmessage.php',true);
req.setRequestHeader("Content-type","application/x-www-form-urlencoded");
req.send("username=" + username +"&message="+message);
} else {
alert("Please enter a message");
}
}
When the Cancel button is hit, the form is still processed through getmessage.php. Any way to have the Cancel button do nothing?
EDIT:
Here is the way this function is called:
<?php
mysqlLogin();
$username = $_COOKIE['sqlusername'];
$sql = mysql_query("SELECT username FROM `users` WHERE username!='$username'");
if(mysql_num_rows($sql) != 0) {
echo "<table class='usertable' align='center'>";
while($row = mysql_fetch_array($sql)){
$username = $row['username'];
echo "<tr><td><center>" . $row['username'] . "</center></td><td> Send Message</td></tr>";
}
echo "</table>";
} else {
echo "<center>No users found!</center>";
}
?>
The PHP script its linked to:
<?php
$id = rand(1,1500);
$poster = $_POST['username'];
$message = $_POST['message'];
$to = $_COOKIE['sqlusername'];
require('functions.php');
mysqlLogin();
$sql = mysql_query("INSERT INTO `messages` VALUES ('$id','$message','$to','$poster','')");
if($sql){
echo "Message sent!";
} else {
echo "Woops! Something went wrong.";
}
?>
In the case of Cancel, the prompt result is null, and null != '' (as per ECMA-262 Section 11.9.3).
So, add an extra explicit check for null inequality:
if(message != "" && message !== null) {
However, since the message is either some string or null and you only want to pass when it's a string with length > 0, you can also do:
if(message) {
This means: if message is truthy (i.e. not null or an empty string, amongst other falsy values), then enter the if clause.
Are you using Safari by any chance? I have found that Safari seems to be returning empty string instead of null when the user clicks Cancel.
See here: Safari 5.1 prompt() function and cancel.
Yeah, my suggested comment does work
var message = prompt("Message:","");
if(message){
alert("Not working!");
} else {
alert("Working!");
}
JSFiddle
var message = prompt("Message:","");
if(message){
alert("Message accepted, now i can process my php or script and blablabla!");
} else {
alert("Cancel Press or Empty Message, do nothing!");
}
var message = prompt('type any...', '');
if(message+'.' == 'null.')
{
alert("you've canceled");
}
else
{
alert("type ok");
}
$.messager.prompt('Save To File', 'FileName:', function(e){
if (e.response!='undefined'){
if (r!="")
{
alert('Your FileName is:' + r);
}
else
{
$.messager.alert('Err...','FileName cannot empty!!!');
}
}
});

Categories