$.post callback return strange data - javascript

I think this might be the cause of why my code is not working.. The 'if(name.val().length > 3)' is never can execute so I put an alert to test the returned data, this is what it look like :
my js
$(document).ready(function(){
var form = $("#customForm");
var name = $("#name");
var nameInfo = $("#nameInfo");
var email = $("#email");
var emailInfo = $("#emailInfo");
var pass1 = $("#pass1");
var passInfo = $("#pass1Info");
var pass2 = $("#pass2");
var pass2Info = $("#pass2Info");
var state = false;
name.keyup(validateName);
function validateName(){
if(name.val().length <= 3){
name.removeClass("valid");
nameInfo.removeClass("valid");
name.addClass("error");
nameInfo.addClass("error");
nameInfo.text("Minimum 4 characters!");
state = false;
}else{
if(name.val().length > 3){
var username=name.val();
$.post('validate.php',{names: username},function(data){
alert(data);
if(data!=0){
name.removeClass("valid");
nameInfo.removeClass("valid");
name.addClass("error");
nameInfo.addClass("error");
nameInfo.text("The username is already taken!");
state = false;
}else{
name.removeClass("error");
nameInfo.removeClass("error");
name.addClass("valid");
nameInfo.addClass("valid");
nameInfo.text("username available");
state = true;
}
});
}
}
}
return state;
//end
});
my PHP code :
<?php
$name = $_POST['names'];
$email = $_POST['emails'];
if($name !=""){
mysql_connect("localhost","root","") or die("Fail to connect to database");
mysql_select_db("reglog");
$uname = mysql_query("SELECT username FROM users WHERE username='$name'");
$count = mysql_num_rows($uname);
if($count !=0){
echo 1;
}else{
echo 0;
}
}
if($email !=""){
mysql_connect("localhost","root","") or die("Fail to connect to database");
mysql_select_db("reglog");
$useremail = mysql_query("SELECT email FROM users WHERE email='$email'");
$countemail = mysql_num_rows($useremail);
if($countemail !=0){
echo 1;
}else{
echo 0;
}
}
?>

It is throwing an warning. Make a habit of checking if a index is available in an array, thus removing possibilities of such error.
$email = isset($_POST['emails']) ? $_POST['emails'] : '';
or do not display any errors to suppress such warning (not recommended).
And as mentioned by Kai, you haven't passed any variables as emails.
$.post('validate.php',{ names: username, 'emails' : email }, ... }

You aren't passing emails as a post variable.
$.post('validate.php',{names: username},function(data){
should be
$.post('validate.php',{names: username, emails: email},function(data){
AS starx says, you should check post values with isset before running processes on the variables

Make return type to html and it will work.

Related

How to read a json file which contains an array from javascript

Please guys help me because i can't find out what i can do in order to read my javascript a json file which contains an array with one element.
My php file is working fine and the output is a .json file which contains this line: {"posts":[["30"]]}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("127.0.0.1", "root", "", "mysql3");
// Check connection
if($link === false) {
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$user_id =$_POST['user_id'];
$book_id =$_POST['book_id'];
$game_id =$_POST['game_id'];
$site_id =$_POST['site_id'];
$sql= "SELECT site_id FROM components WHERE user_id='$user_id' && book_id='$book_id' && game_id='$game_id' ORDER BY site_id DESC LIMIT 1";
$response = array();
$posts = array();
$result=mysqli_query($link, $sql);
while($row=mysqli_fetch_assoc($result)) {
$site_id=$row['site_id'];
$posts[] = array($site_id);
}
$response['posts'] = $posts;
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($response));
fclose($fp);
// Close connection
mysqli_close($link);
?>
Can anybody help me what i have to do (without using ajax) in order my javascript function reads that value? I want to rerad this value cause i want to manipulate this number.
function load3() {
var flag1 = true;
do{
var selection = window.prompt("Give the User Id:", "Type a number!");
if ( /^[0-9]+$/.test(selection)) {
flag1=false;
}
}
while(flag1!=false);
$("#user_id").val(selection)
var flag2 = true;
do{
var selection2 = window.prompt("Give the Book Id:", "Type a number!");
if ( /^[0-9]+$/.test(selection2)) {
flag2=false;
}
}
while(flag2!=false);
$("#book_id").val(selection2)
var flag3= true;
do{
var selection3 = window.prompt("Give the Game Id:", "Type a number!");
if ( /^[0-9]+$/.test(selection3)) {
flag3=false;
}
}
while(flag3!=false);
$("#game_id").val(selection3)
//i do not want to do with ajax!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
$.ajax({
type: 'POST',
url: 'http://127.0.0.1/PHP/loo.php',
data: $('#LoadGame').serialize(),
success: function (html) {
//do something on success?
$('#outPut').html(html);
var bingoValue=4;
if( $('#outPut').text().indexOf(''+bingoValue) > 0){
//alert('bingo!');
window.location.href='https://support.wwf.org.uk/';
//document.location.replace('https://developer.mozilla.org/en-US/docs/Web/API/Location.reload');
}
else {
alert('No!');
}
}
});
}
Thank you for your help!
Assuming this PHP code runs during your doc request,
You can read that json if you put it in a script tag
<script type="text/javascript">
window.myJson = <?php echo(json_encode($response)); ?>
</script
and it will be accessible as window.myJson in frontend

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

alert(message) returns an empty string

SOLVED by #Hanky 웃 Panky!
I am implementing a login function.
The javascript part:
function login() {
var n = $('#userl').val();
var p = $('#passl').val();
if ( n != "" && p != ""){
$.post("functions.php",{userl: n, passl: p}).done(function(mesaj){
if(mesaj == "")
alert("!!!!!!!!!!EMPTY STRING!!!!!");
else
alert(mesaj);
});
}
else {
alert("Enter name and/or passwort");
}
};
And the function from function.php looks:
function login($nume,$parola)
{
$sql = "SELECT id FROM `Users` WHERE nume ='".$nume."' ANY password = '".md5($parola)."'";
$q = mysql_query($sql);
if(!$q)
die(json_encode(array("mesaj" => "Invalid")));
else{
$x = mysql_fetch_array($q);
if (empty($x))
die(json_encode(array('mesaj' => 'The user does not exist')));
else {
// $user = new User($x['id']);
session_start();
$_SESSION['user_id'] = $x['id'];
$_SESSION['loggedin'] = "yes";
die(json_encode(array("mesaj"=>"you were logged")));
}
}
//this part may be useless
die(json_encode(array("mesaj"=>"you were not logged")));
}
if (isset($_POST['nume']) AND isset($_POST['parola']))
login($_POST['nume'], $_POST['parola']);
The problem is it keeps alerting the EMPTY STRING and I think it doesn'n even acccess my login function from php...so the message comes back the way it went: empty
$.post("functions.php",{userl: n, passl: p})
Compare that with
if (isset($_POST['nume']) AND isset($_POST['parola']))
And spot your error :)
You are sending user1 and pass1 and in PHP you are checking for nume and parola which don't exist obviously.

Redirect a logged in user from login page to user dashboard with php

I need your help to manage a php page with redirection function.
I want my logged in users to redirect to user dashboard instead of displaying login page by typing address in Browser's address Bar. How to prevent users to display login page
Login page codes are given below
<?php
include 'dbc.php';
$err = array();
foreach($_GET as $key => $value) {
$get[$key] = filter($value); //get variables are filtered.
}
if ($_POST['doLogin']=='Login')
{
foreach($_POST as $key => $value) {
$data[$key] = filter($value); // post variables are filtered
}
$user_email = $data['user_email'];
$pass = $data['pwd'];
if (strpos($user_email,'#') === false) {
$user_cond = "user_name='$user_email'";
} else {
$user_cond = "user_email='$user_email'";
}
$result = mysql_query("SELECT `id`,`pwd`,`full_name`,`approved`,`user_level` FROM users WHERE
$user_cond
AND `banned` = '0'
") or die (mysql_error());
$num = mysql_num_rows($result);
// Match row found with more than 1 results - the user is authenticated.
if ( $num > 0 ) {
list($id,$pwd,$full_name,$approved,$user_level) = mysql_fetch_row($result);
if(!$approved) {
//$msg = urlencode("Account not activated. Please check your email for activation code");
$err[] = "Account not activated. Please check your email for activation code";
//header("Location: login.php?msg=$msg");
//exit();
}
//check against salt
if ($pwd === PwdHash($pass,substr($pwd,0,9))) {
if(empty($err)){
// this sets session and logs user in
session_start();
session_regenerate_id (true); //prevent against session fixation attacks.
// this sets variables in the session
$_SESSION['user_id']= $id;
$_SESSION['user_name'] = $full_name;
$_SESSION['user_level'] = $user_level;
$_SESSION['HTTP_USER_AGENT'] = md5($_SERVER['HTTP_USER_AGENT']);
//update the timestamp and key for cookie
$stamp = time();
$ckey = GenKey();
mysql_query("update users set `ctime`='$stamp', `ckey` = '$ckey' where id='$id'") or die(mysql_error());
//set a cookie
if(isset($_POST['remember'])){
setcookie("user_id", $_SESSION['user_id'], time()+60*60*24*COOKIE_TIME_OUT, "/");
setcookie("user_key", sha1($ckey), time()+60*60*24*COOKIE_TIME_OUT, "/");
setcookie("user_name",$_SESSION['user_name'], time()+60*60*24*COOKIE_TIME_OUT, "/");
}
header("Location: dashboard.php");
}
}
else
{
//$msg = urlencode("Invalid Login. Please try again with correct user email and password. ");
$err[] = "Invalid Login. Please try again with correct user email and password.";
//header("Location: login.php?msg=$msg");
}
} else {
$err[] = "Error - Invalid login. No such user exists";
}
}
?>
I put your codes like this but got no effect. So please elaborate well and give example how to do it exactly.
<?php
include 'dbc.php';
if (isset ($_SESSION['status_logged']) && $_SESSION['status_logged'] = true) {
header('Location: dashboards.php');
}
else {
$_SESSION['status_logged'] = false;
}
$err = array();
foreach($_GET as $key => $value) {
$get[$key] = filter($value); //get variables are filtered.
}
if ($_POST['doLogin']=='Login')
{
foreach($_POST as $key => $value) {
$data[$key] = filter($value); // post variables are filtered
}
$user_email = $data['user_email'];
$pass = $data['pwd'];
if (strpos($user_email,'#') === false) {
$user_cond = "user_name='$user_email'";
} else {
$user_cond = "user_email='$user_email'";
}
$result = mysql_query("SELECT `id`,`pwd`,`full_name`,`approved`,`user_level` FROM users WHERE
$user_cond
AND `banned` = '0'
") or die (mysql_error());
$num = mysql_num_rows($result);
// Match row found with more than 1 results - the user is authenticated.
if ( $num > 0 ) {
list($id,$pwd,$full_name,$approved,$user_level) = mysql_fetch_row($result);
if(!$approved) {
//$msg = urlencode("Account not activated. Please check your email for activation code");
$err[] = "Account not activated. Please check your email for activation code";
//header("Location: login.php?msg=$msg");
//exit();
}
//check against salt
if ($pwd === PwdHash($pass,substr($pwd,0,9))) {
if(empty($err)){
// this sets session and logs user in
session_start();
session_regenerate_id (true); //prevent against session fixation attacks.
// this sets variables in the session
$_SESSION['user_id']= $id;
$_SESSION['user_name'] = $full_name;
$_SESSION['user_level'] = $user_level;
$_SESSION['HTTP_USER_AGENT'] = md5($_SERVER['HTTP_USER_AGENT']);
$_SESSION['status_logged'] = true; //new line
//update the timestamp and key for cookie
$stamp = time();
$ckey = GenKey();
mysql_query("update users set `ctime`='$stamp', `ckey` = '$ckey' where id='$id'") or die(mysql_error());
//set a cookie
if(isset($_POST['remember'])){
setcookie("user_id", $_SESSION['user_id'], time()+60*60*24*COOKIE_TIME_OUT, "/");
setcookie("user_key", sha1($ckey), time()+60*60*24*COOKIE_TIME_OUT, "/");
setcookie("user_name",$_SESSION['user_name'], time()+60*60*24*COOKIE_TIME_OUT, "/");
}
header("Location: dashboard.php");
}
}
else
{
//$msg = urlencode("Invalid Login. Please try again with correct user email and password. ");
$err[] = "Invalid Login. Please try again with correct user email and password.";
//header("Location: login.php?msg=$msg");
}
} else {
$err[] = "Error - Invalid login. No such user exists";
}
}
?>
You already have a session with the user data, so, it's simple, save the status in the same session and make a verification on the top of your script. Like this
Put this in your code
// this sets variables in the session
$_SESSION['user_id']= $id;
$_SESSION['user_name'] = $full_name;
$_SESSION['user_level'] = $user_level;
$_SESSION['HTTP_USER_AGENT'] = md5($_SERVER['HTTP_USER_AGENT']);
$_SESSION['status_logged'] = true; //new line
And put a verification on the top:
if (isset ($_SESSION['status_logged']) && $_SESSION['status_logged'] == true) {
header('Location: yourDashboardPage.php');
}
else {
$_SESSION['status_logged'] = false;
}

AJAX not returning a variable from php

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.

Categories