My AJAX query isnt validating properly - php

New to web design here. I have a login form that validates and works perfectly in php but when I try and validate using ajax it doesn't work. When i run the page it says it is a success no matter the input into the form. I have tried for days trying to get it to validate in many different methods. If there is a better way please let me know!
php here and is on same page as login form
if (isset($_POST['login'])) {
$email = mysqli_real_escape_string($con, $_POST['email']);
$password = mysqli_real_escape_string($con, $_POST['password']);
$result = mysqli_query($con, "SELECT * FROM users WHERE email = '" . $email. "' and password = '" . md5($password) . "'");
if ($row = mysqli_fetch_array($result)) {
echo json_encode('true');
$_SESSION['usr_id'] = $row['id'];
$_SESSION['usr_name'] = $row['name'];
$_SESSION['logged_in'] = true;
} else {
echo json_encode('false');
$errormsg = "Incorrect Email or Password!!!";
}
}
?>
$(document).ready(function() {
$('#login_submit').click(function() {
var form = $('#login_form').serialize();
$.ajax({
type: "POST",
url: "header.php",
data: form,
success:function (response){
alert('Hi');
},
error: function(response){
alert('Nope');
}
});
});
});
<form id="login_form" form role="form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="loginform">
<label class="login_form_labels"> Email:</label>
<input type="email" id="email" class="login_input" name="email"><br><br>
<label class="login_form_labels"> Password:</label>
<input type="password" id="password" class="login_input" name="password"><br>
<div id="stay_log">
Stay logged in.
<input type="checkbox" name="stayLoggedIn" value=1 id="checkbox_1">
</div>
<input class="login_form_btn" name="login" value="Submit" type="Submit" id="login_submit">
<button class="login_form_btn" type="button">Forget your Password?</button>
</form>
Please help!

set dataType as Json in your ajax as like given below
$.ajax({
type: "POST",
url: "header.php",
dataType: json,
data: form,
success:function (response){
alert('Hi');
},
error: function(response){
alert('Nope');
}
});
Try this...

I think you need to require pure JSON response from server side and handle it in your ajax success method.
In your PHP code.
$response=array();
if (!empty($_POST)) {
$email = mysqli_real_escape_string($con, $_POST['email']);
$password = mysqli_real_escape_string($con, $_POST['password']);
$result = mysqli_query($con, "SELECT * FROM users WHERE email = '" . $email. "' and password = '" . md5($password) . "'");
if ($row = mysqli_fetch_array($result)) {
echo json_encode('true');
$_SESSION['usr_id'] = $row['id'];
$_SESSION['usr_name'] = $row['name'];
$_SESSION['logged_in'] = true;
$response['type']="success";
$response['message']="Login done successfully";
} else {
$response['type']="error";
$response['message']="Incorrect Email or Password!!!";
}
}
else
{
$response['type']="error";
$response['message']="invalid post request";
}
ob_clean();
echo json_encode($response);
die();
In above way from server you can response in only json format.
In you ajax call javascript code
$(document).ready(function() {
$('#login_submit').click(function() {
var form = $('#login_form').serialize();
$.ajax({
type: 'post',
url: $('#login_form').attr("action"),
data: form,
dataType:'json'
success:function (response){
if(response.type=="success")
{
alert(response.message);
// write code for handle your success login;
}
else
{
alert(response.message);
// write code for handle your failure login;
}
},
error: function(response){
alert('Nope');
}
});
});
});
You have to handle JSON response from server side in your ajax success response

In jQuery/AJAX, the HTTP response code termines whether it is a success or not. So if the login failed, you should set a header in PHP indicating this failure.
if (.. login has failed .. ) {
// HTTP 401 = 'Unauthorized'.
http_response_code(401);
}
By doing this, you won't even have to process the resulting JSON, only maybe to get additional info. But the basic result will tell you enough: if the success callback was called, logging in was successful. If error was called, it was not successful for whatever reason.
This sets out your basic flow, and after that you could parse the result message to see any details of what's going on (internal server error, user unknown, password doesn't match, etc).
See List of HTTP response codes, for a list of alternatives and this question for an argumentation about using 401.

First use alert(response) to find out the response you are getting. It should be true or false.
success:function (response){
if(response === "true")
{
alert("hi");
}
else
{
alert("nope");
}
},

Related

PHP Script doesnt return variables to AJAX

The code is for simple login validation.
The PHP script doesnt seem to run when returning values to JavaScript but runs fine when there are not variables to return.
So is there anything wrong or do I need to add anything else to return the values from PHP.
<?php
header('Content-type: application/json; charset=utf-8');
include("config.php");
$formd=array();
//Fetching Values from URL
$username2=$_POST['username1'];
$password2=$_POST['password1'];
$query = mysqli_query($db,"SELECT username FROM login WHERE username = '$username2'");
$result=mysqli_fetch_assoc($query);
$sql=mysqli_query($db,"SELECT password FROM login WHERE username = '$username2'");
$resul=mysqli_fetch_assoc($sql);
$row = mysqli_fetch_array($query,MYSQLI_ASSOC);
$count = mysqli_num_rows($query);
$pass=$resul['password'];
if((password_verify($password2,$pass))and($count==1)) {
echo "ds";
} else {
echo "no";
$formd['no']="Invalid password or username"
}
mysqli_close($db); // Connection Closed
echo json_encode($formd);
exit();
?>
JavaScript
<script>
$(document).ready(function(){
$("#submit").click(function(){
var username = $("#username").val();
var password = $("#password").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'username1='+ username + '&password1='+ password;
if(username==''||password=='') {
alert("Please Fill All Fields");
} else {
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
dataType: "json",
data: dataString,
success: function(data){
alert(data.no);
}
});
}
return false;
});
});
</script>
your Php code has 2 echo statements
if((password_verify($password2,$pass))and($count==1))
{
echo "ds"; // first
}
else
{
echo "no"; // first
$formd['no']="Invalid password or username"
}
mysqli_close($db); // Connection Closed
echo json_encode($formd); // second
This way, your php script returns malformed JSON data and hence $.ajax() cannot handle it.
Also, as others pointed out, please use the developer console to verify your script returns the expected data.
The if else part of your php script has an echo statement and then outside the if else you echo the array $formd. This malforms the JSON response. Also, you should use exit(1) as there is no exception being raised in your code.
Here the snippet you should use to get the script working.
if((password_verify($password2,$pass))and($count==1))
{
echo "ds";
}
else
{
// echo "no"; this is not required
$formd['no']="Invalid password or username"
}
mysqli_close($db); // Connection Closed
echo json_encode($formd);
exit(1);

When submiting a contact us form I wanted to stay in this cantact form

I am new in HTML and PHP, I have created a contact form for the users where they can add their messages. When they click on the send button I want the page to stay on this contact form and show a text message below that says it is succesfully sent. Here is my code some of it .
if (isset($_POST['submit']))
{
if (!isset($_POST['name'])) {
echo "please enter the name";
}else {
if (!isset($_POST["emailaddress"])) {
echo "please enter the email adresse ";
}else {
if (!isset($_POST["subject"])) {
echo " Please enter the message ";
} else {
$nom = $_POST['name'];
$email = $_POST['emailaddress'];
$msg = $_POST['subject'];
$sql = "INSERT INTO contacts (name, email, message) VALUES ('$nom', '$email', '$msg') ";
if (!mysql_query($sql)){
die ('error : ' . mysql_error());
} else {
mysql_close($link);
?>
</br></br>
<p25><center>sent succesfully! thanks</center></p25>s
<?php
echo "<script>setTimeout(\"location.href = 'no-sidebar.php'\",8000);</script>";
You need to understand each line of code.
if (!isset($_POST['name'])) {
echo "please enter the name";
}
The page will get reloaded on the first instance.
You need to do the form validation part in javascript. In this way, if some validation error happens, it can be displayed somewhere in the page without reloading it.
Then send the data to php through ajax, where you set your model and pass it to database and send a response back to javascript which can then print the message that the form has been submitted successfully.
Here's what I'm saying:
<input type="text" id="email" />
<button id="submit">Submit</button>
<div id="status"></div>
Javascript Part:
$(document).ready(function(){
$('#submit').on('click', function(){
var email = $('#email').val();
if(email.trim().length === 0){
$('#status').html('Email not provided');
}else{
$.ajax({
type : 'POST',
data : {action: 'sendData' , email : email}, // object
url : 'example.php',
cache: false,
success: function(response){
$('#status').html(response);
}
});
}
});
});
And in the php side, then you can just get the value which is already validated and return true or false based on your data insertion result to database.
example.php
<?php
if(isset($_POST['action']) && $_POST['action'] == 'sendData'){
$email = $_POST['email'];
if(dbinsertion successful){
echo "Success";
}else{
echo "Something went wrong";
}
}
?>
You have to use jquery here. Hope you understood.

Send data from form with ajax without redirect

It seems this should be a simple thing to do but something is still going wrong. I am using the code of the top answer on this page: jQuery Ajax POST example with PHP
When I submit the form, instead of passing that data to the upvote.php and having it edit the database accordingly, it redirects me to /upvote.php?bar=hfAb1he49kk. It is taking the data that I need & redirecting to the php page and adding the data the url. Why is it doing that?
PHP
<?php
// Create connection
$con=mysqli_connect("localhost","root","root","test");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM videos ORDER BY votes DESC");
while($row = mysqli_fetch_array($result)) {
echo "<div class='entry'>";
$id = $row['id'];
echo "<form action='upvote.php'>
<input type='hidden' name='bar' id='bar' value='" . $id . "' />
<input type='submit' value='upvote'/>
</form>";
echo '<iframe width="560" height="315" src="https://www.youtube.com/embed/' . stripslashes($row['id']) . '" frameborder="0" allowfullscreen></iframe>';
echo $row['votes'];
echo "</div>";
}
?>
JQuery
<script>
var request;
// bind to the submit event of our form
$(form).submit(function(event){
if (request) {
request.abort();
}
// setup some local variables
var $form = $(this);
// let's select and cache all the fields
var $inputs = $form.find("input, select, button, textarea");
// serialize the data in the form
var serializedData = $form.serialize();
// let's disable the inputs for the duration of the ajax request
// Note: we disable elements AFTER the form data has been serialized.
// Disabled form elements will not be serialized.
$inputs.prop("disabled", true);
// fire off the request to /form.php
request = $.ajax({
url: "/upvote.php",
type: "post",
data: serializedData
});
// callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
// log a message to the console
console.log("Hooray, it worked!");
});
// callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
// log the error to the console
console.error(
"The following error occured: "+
textStatus, errorThrown
);
});
// callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
// reenable the inputs
$inputs.prop("disabled", false);
});
// prevent default posting of form
event.preventDefault();
});
</script>
upvote.php
<?php
$con=mysqli_connect("localhost","root","root","test");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$bar = $_POST['bar'];
mysqli_query($con,"UPDATE videos SET votes = votes + 1 WHERE id = '" . $bar . "'");
mysqli_close($con);
?>
function postData(event){
event.preventDefault()
$.ajax({
type: "POST",
url: "yourfile.php",
data: $('#myForm').serialize()
}).done(function( result ) {
// do something
});
}
<form id="myForm">
<input type="submit" onclick="postData(event)" value="submit">
In a php file
$bar = $_POST['bar'];
$query = "UPDATE videos SET votes = votes + 1 WHERE id = '" . $bar . "'";
echo $query; //will echo you query to the done function of the ajax
exit();
mysqli_query($con,$query);
mysqli_close($con);
maybe add
event.preventDefault();
to prevent the form action
$("#foo").submit(function(event){
event.preventDefault();
Seb

Database slice the last two characters of the password (?!)

I have a very frustrating problem. I have a client which send a registration form to the server. The handler is a php file.
The problem is the following: the client send the form data to the php, the php store it in the mysql database. But if I try to give a name which is contains a space - I don't know why - in the database the the password's length is reduced by two.
I searched long hours, but found nothing. I'm on the edge of madness, so I would like to ask you to help me to find the problem.
Here is the registration form:
<!-- REGISTRATION -->
<div data-role="page" id="regScreen">
<div data-role="content">
<div class="profileCircle">
<img src="img/iskola.jpg" />
</div>
<div class="space"></div>
<form action="" method="post" id="regForm" name="regForm">
<input type="text" name="nev" id="regName" placeholder="Teljes név" data-mini="true"/>
<input type="email" name="mail" id="regEmail" placeholder="Email cím" data-mini="true"/>
<input type="password" name="jelszo" id="regPassword" placeholder="Jelszó" data-mini="true"/>
<input type="submit" data-inline="true" data-mini="true" value="Regisztráció" name="rendben" id="rendben" />
</form>
</div>
<a href="#loginScreen"><div class="circle leftBottom c1">
<img src="img/ikonok/vissza.png" />
</div></a>
</div>
This is the script which should handle the registration on the client side:
function registration(){
var name = $('#regForm #regName').val();
var email = $('#regForm #regEmail').val();
var password = $('#regForm #regPassword').val();
if((password == "" || password == null) || (email == "" || email == null)){
navigator.notification.alert("Nem töltött ki minden adatot!", function(){}, "Figyelem!");
}else{
$.ajax({
url: host + "regisztracio.php",
type: 'post',
dataType: 'json',
data: {rendben:'ok', nev: name, mail: email, jelszo: password},
success: function(data){
if(data.ok){
navigator.notification.alert('Sikeresen regisztrált!\nMostmár be tud jelentkezni a saját felhasználónevével!',function(){
$.mobile.changePage("#loginScreen");
},'Üdvözöljük!');
}else{
navigator.notification.alert(data.uzenet,function(){},'Figyelem!');
if(data.help){
navigator.notification.confirm('Kívánja, hogy új jelszót küldjünk erre az email címre?',function(){
console.log(button);
}, 'Segíthetünk?', 'Igen, Nem');
}
}
},
error: function(err){
console.log('jajj');
navigator.notification.alert(err.message,function(){},'Hiba!');
}
});
}
}
And finally here is the php code:
<?php
if (isset($_POST['rendben'])) {
require("mysql.php");
$nev = $_POST['nev'];
$mail = $_POST['mail'];
$jelszo = $_POST['jelszo'];
if (empty($_POST['nev']) OR empty($_POST['mail']) OR empty($_POST['jelszo'])) {
$string = array("ok" => false, "uzenet" => "Nem töltött ki minden adatot!");
echo json_encode($string);
}else{
$sql = "SELECT *
FROM felhasznalok
WHERE mail = '{$mail}'";
$eredmeny = mysql_query($sql);
if (mysql_num_rows($eredmeny) == 0) {
$sql = "INSERT INTO felhasznalok
(nev, mail, jelszo, kep)
VALUES
('{$nev}', '{$mail}', '{$jelszo}', '{$kep}')";
mysql_query($sql);
$string = array("ok" => true);
echo json_encode($string);
}else{
$string = array("ok" => false, "help" => true, "uzenet" => "Ezzel az email címmel már regisztráltak, lehet, hogy elfelejtette a jelszavát?");
echo json_encode($string);
}
}
}?>
If you need I will upload a picture from the database table.
I hope you can help me.
Please forgive not a full answer as such but the formatting is better than a comment:
As others have already suggested:
Echo your sql statement. This is what is being stored in the db after all. This will show you whether your problem lies before or after the data is stored in the db.
var_dump($_POST) if your sql is good as this checks the code in between the receipt of data and its storage in the DB - you can see what your script actually sends.
escape your text to prevent 'sql injection' - Always escape the text because you never know when you are going to change your client page and it is safer that way. Your case is a prime example of why you never trust data from the client.
FWIIW, I suspect that the problem lies in the javascript. One problem with the use of libraries like jquery is that they actually don't make easy stuff easier. They make it more complex. A bit like a slide rule though, once learned, they make some complicated stuff no harder than the easy stuff. There is a code-portability benefit too.
Even so, IMHO, for a simple ajax call, you're actually better off using pure JS, certainly as a beginner. w3schools.com has an excellent AJAX tutorial and code examples.
mysql_* extensions are deprecated. You would be wise to learn mysqli_ (which is nearly identical) or PDO.
My guess is that you are having troubles with jQuery.param encoding of spaces (+, one character, instead of %20, three characters).
You can try manually replacing the ' ' with '%20' in the password field (note: you probably have the same problem in all fields, only you haven't noticed it yet) using the .beforeSend setting:
url: host + "regisztracio.php",
type: 'post',
dataType: 'json',
data: {rendben:'ok', nev: name, mail: email, jelszo: password},
beforeSend: function (req, data) {
data.jelszo = data.jelszo.replace(/\+/g, "%20");
},
success: function(data){
...
Also (but this is unrelated), on the PHP side, notice that you can simplify a bit your code to encode the answer in one place only:
$string = array("ok" => false);
// Ez ad némi biztonságot
$fields = array('nev','mail','jelszo');
foreach($fields as $field)
{
if (empty($_POST[$field]))
$string['uzenet'] = "Nem töltött ki minden adatot: ${field}!";
else
${$field} = mysql_real_escape_string($_POST[$field]);
}
if (!isset($string['uzenet']) {
$sql = "SELECT *
FROM felhasznalok
WHERE mail = '{$mail}'";
$eredmeny = mysql_query($sql);
if (mysql_num_rows($eredmeny) == 0) {
$sql = "INSERT INTO felhasznalok
(nev, mail, jelszo, kep)
VALUES
('{$nev}', '{$mail}', '{$jelszo}', '{$kep}')";
if (false === mysql_query($sql))
$string['uzenet'] = 'Volt egy adatbázis hiba!';
else
$string['ok'] = true;
}else{
$string['help'] = true;
$string['uzenet'] = 'Ezzel az email címmel már regisztráltak, lehet, hogy elfelejtette a jelszavát?';
}
}
die(json_encode($string)); // No more output after this.

Post the data failed in php

I have some trouble during post my data, show 500 internal server error.
So, I think it must be unsyncronize between client side and server side. I have check but I dont have any clue.This the following php script:
<input type="text" id="use" name="use">
<input type="password" id="pass" name="pass"></td>
<input type="hidden" name="action" value="logaccept">
if ($("#passlog").valid()){
var params = $("#passlog").serialize();
$.ajax({
type:"post",
url:"process3.php",
data:params,
cache:false,
async:false,
success: function(data){
//do something
}
});
}
This the server side:
switch(postVar('action')) {
case 'logaccept' :
passlog(postVar('use'),postVar('pass'));
break;
}
function passlog($use,$pass){
$Use = mysql_real_escape_string($use);
$Pass= mysql_real_escape_string($pass);
//build query
$sql = "SELECT Privilege FROM admin WHERE user='".$Use."' AND password='".$Pass."'";
echo $sql;
$data=mysql_query($sql) or die(_ERROR26.": ".mysql_error());
if($data){
$priv = mysql_fetch_assoc($sql);
}else{
echo 0; // If login fails
}
?> //show Parse error: syntax error, unexpected $end in /var/www/html/process3.php on line 74
Could you tell me what's wrong with my script?
You have a syntax error in file process3.php - thats why you get the internal server error - that is the first thing you have to correct

Categories