hide and show in AJAX - javascript

I have an Ajax function called login
function Login(){
$.ajax({
url: 'http://creative.coventry.ac.uk/~4078078/moviereviews/v1.0/index.php/user/adduser/'+$("#loginusername").val(),
headers: {authorization:window.btoa($("#loginusername").val()+':'+$("#loginpassword").val())},
contentType: "text",
dataType: 'json',
success: function(data) {
authorisation = window.btoa($("#loginusername").val()+':'+$("#loginpassword").val()); //create a variable to pass to the cookie
createCookie('cookie',authorisation,0); //create our authorisation cookie for the client
alert("Login Successful!");
$("#loginbox").hide(); //hide the login button
$("#logout").show(); //show the logout button
$("#addreview").show(); //show the add a review button
$("#adminpanel").show();//show the admin panel page
$("#editreview").show();
$("#deletereview").show();
$("#loginusername").val(''); //clear the name box
$.mobile.changePage("#home" ); //show the menu
},
error: function (response) {
var r = jQuery.parseJSON(response.responseText);
alert("Error:" + r.error.text);
}
});
}
At the moment it shoes delete review button but in html it hides it as the user is not logged in,
what I want it to do is when One specific user is logged in show delete button only on the review he has posted not on the others how do I do that with in Ajax
PHP code web service:
function deletereview_delete($id=null){{
// authorization required by the user to post a review
$headers = apache_request_headers();
{
if (empty($headers['authorization'])) {
$info->status = 'failure';
$info->error->code = 15;
$info->error->text = 'Authorization required';
$this->response($info, 401);
}
}
$string = base64_decode($headers['authorization']);
list($username, $password) = explode(':', $string);{ // checking to see if the Authorization string is valid
$this->load->database();
$sql = 'SELECT COUNT(userid) AS records FROM users '.'WHERE authorization = "'.$headers['authorization'].'";';
$query = $this->db->query($sql);
$data = $query->row();
if ($data->records == "0") {
$info->status = 'failure';
$info->error->code = 19;
$info->error->text = 'authorization string is not valid';
$this->response($info, 401);
}
}}
{
if (!isset($id)){// check if the ID is specified in the URI
$info->status = 'failure';
$info->error->code = 11;
$info->error->text = 'id not specified in URI';
$this->response($info, 400);
}}
{ // if the resource exist
$this->load->database();
$sql = 'SELECT COUNT(id) AS records FROM reviews WHERE id = '.$id.';';
$query = $this->db->query($sql);
$data = $query->row();
if ($data->records == "0") {
$info->status = 'failure';
$info->error->code = 12;
$info->error->text = 'id does not exist or have a resource';
$this->response($info, 404);
}
}{ // checking to see if the Authorization string is valid
$this->load->database();
$sql = 'SELECT username from reviews where id = "'.$id.'" and username= (select username from users where username ="'.$username.'" and authorization = "'.$headers['authorization'].'");';
$query = $this->db->query($sql);
$data = $query->row();
if ( $data == false) {
$info->status = 'failure';
$info->error->code = 19;
$info->error->text = 'You do not have permission to delete this review';
$this->response($info, 401);
}
}
$this->load->database();
$sql= 'SELECT * FROM reviews WHERE id= "'.$id.'";';
$query= $this->db->query($sql);
$data->record = $query->row();
$criteria = array('id'=>$id);
$this->db->delete('reviews', $criteria);
$data->rows = $this->db->affected_rows();
$data->message = 'Review has been deleted';
$this->response($data,200);
}

you will have to get a server side flag or variable with a post like
function Login(){
$.ajax({
url: 'http://creative.coventry.ac.uk/~4078078/moviereviews/v1.0/index.php/user/adduser/'+$("#loginusername").val(),
headers: {authorization:window.btoa($("#loginusername").val()+':'+$("#loginpassword").val())},
contentType: "text",
dataType: 'json',
success: function(data) {
authorisation = window.btoa($("#loginusername").val()+':'+$("#loginpassword").val()); //create a variable to pass to the cookie
createCookie('cookie',authorisation,0); //create our authorisation cookie for the client
alert("Login Successful!");
$("#loginbox").hide(); //hide the login button
$("#logout").show(); //show the logout button
$("#addreview").show(); //show the add a review button
$("#adminpanel").show();//show the admin panel page
$("#editreview").show();
//here is the code
if(data.text=='show')
$('#deletereview').show();
else
$('#deletereview').hide();
$("#loginusername").val(''); //clear the name box
$.mobile.changePage("#home" ); //show the menu
},
error: function (response) {
var r = jQuery.parseJSON(response.responseText);
alert("Error:" + r.error.text);
}
});
/*rough code*/
}
You can also use json(specify dataType if you use).

Related

How to fix error between JSON, jQuery, AJAX and PHP

I'm having problems figuring out what is wrong with my json. I used php's json_encode.So, on every page I have the some form which need be sent on each page to different email address. However, if I comment jQuery file, then the form is submitted correctly, all data inserted into database correctly, and in place of jQuery AJAX response I get valid JSON, like
{"response":"success","content":{"3":"Thanks John Doe! Your message is successfully sent to owner of property Hotel Milano!"}}
If I want to read and process this data with jQuery instead of get valid response I get just empty [] I was try a lot of options and so if I add JSON_FORCE_OBJECT instead of get empty [] I get empty {}. However if I write json data which need to encode after closing tag for if (is_array($emails) && count($emails) > 0) { just then json data it's encoded correctly and when a form is submitted I get valid response, but in this case form isn't sent and data isn't inserted into db. Bellow is my PHP code:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// define variables and set to empty values
$fname = $tel = $email_address_id = "";
$error = false;
$response = [];
//Load the config file
$dbHost = "localhost";
$dbUser = "secret";
$dbPassword = "secret";
$dbName = "booking";
$dbCharset = "utf8";
try {
$dsn = "mysql:host=" . $dbHost . ";dbName=" . $dbName . ";charset=" . $dbCharset;
$pdo = new PDO($dsn, $dbUser, $dbPassword);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
$response['response'] = 'error';
$response['errors'][] = $e->getMessage();
echo json_encode($response);
die();
}
use PHPMailer\PHPMailer\PHPMailer;
require 'PHPMailer/PHPMailer.php';
require 'PHPMailer/SMTP.php';
require 'PHPMailer/Exception.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['submit'])) {
//print_r($_POST);
$fname = $_POST['fname'];
$tel = $_POST['tel'];
if (empty($fname)) {
$response['response'] = 'error';
$error = true;
$response['errors'][] = 'Name can not be empty!';
} else {
if (!preg_match("/^[a-zšđčćžA-ZŠĐČĆŽ\s]*$/", $fname)) {
$response['response'] = 'error';
$error = true;
$response['errors'][] = 'Name can contain just letters and white space!';
}
}
if (empty($tel)) {
$response['response'] = 'error';
$error = true;
$response['errors'][] = "Phone can not be empty!";
} else {
if (!preg_match('/^[\+]?[0-9]{9,15}$/', $tel)) {
$response['response'] = 'error';
$error = true;
$response['errors'][] = "Phone can contain from 9 to 15 numbers!";
}
}
if (!$error) {
// Instantiate a NEW email
$mail = new PHPMailer(true);
$mail->CharSet = "UTF-8";
$mail->isSMTP();
$mail->Host = 'secret.com';
$mail->SMTPAuth = true;
//$mail->SMTPDebug = 2;
$mail->Username = 'booking#secret.com';
$mail->Password = 'secret';
$mail->Port = 465; // 587
$mail->SMTPSecure = 'ssl'; // tls
$mail->WordWrap = 50;
$mail->isHTML(true);
$mail->setFrom('booking#secret.com');
$mail->clearAddresses();
$mail->Subject = "New message from secret.com";
$query = "SELECT owners_email.email_address_id, email_address, owner_name, owner_property, owner_sex, owner_type FROM booking.owners_email INNER JOIN booking.pages ON (pages.email_address_id = owners_email.email_address_id) WHERE `owner_sex`='M' AND `owner_type`='other' AND `pages_id` = ?";
$dbstmt = $pdo->prepare($query);
$dbstmt->bindParam(1, $pages_id);
$dbstmt->execute();
//var_dump($dbstmt);
$emails = $dbstmt->fetchAll(PDO::FETCH_ASSOC);
if (is_array($emails) && count($emails) > 0) {
foreach ($emails as $email) {
//var_dump($email['email_address']);
$mail->addAddress($email['email_address']);
$body = "<p>Dear {$email['owner_name']}, <br>" . "You just received a message from <a href='https://www.secret-booking.com'>secret-booking.com</a><br>The details of your message are below:</p><p><strong>From: </strong>" . ucwords($fname) . "<br><strong>Phone: </strong>" . $tel . "</p>";
$mail->Body = $body;
if ($mail->send()) {
$mail = "INSERT INTO booking.contact_owner (fname, tel, email_address_id) VALUES (:fname, :tel, :email_address_id)";
$stmt = $pdo->prepare($mail);
$stmt->execute(['fname' => $fname, 'tel' => $tel, 'email_address_id' => $email['email_address_id']]);
$response['response'] = "success";
$response['content'][$email['email_address_id']] = "Thanks " . ucwords($fname) . "! Your message is successfully sent to owner of property {$email['owner_property']}!";
}//end if mail send
else {
$response['response'] = "error";
$response['content'][$email['email_address_id']] = "Something went wrong! Try again..." . $mail->ErrorInfo;
}
}//end foreach for email addresses
} //end if for array of emails
/* If use this else for response I allways get this response. Even, if I write JSON for success hier I get it but data isn't sent and isn't inserted into db
else {
$response['response'] = 'error';
$response['error'][] = '$emails is either not an array or is empty'; // jQuery just read this
}//end if else for array of emails
*/
}//end if validation
}//end submit
echo json_encode($response);
}//end REQUEST METHOD = POST
And this is jQuery for submitHanfdler
submitHandler: function (form) {
//Your code for AJAX starts
var formData = jQuery("#contactOwner").serialize();
console.log(formData); //this work
jQuery.ajax({
url: '/classes/Form_process.class.php',
type: 'post',
data: formData,
dataType: 'json',
cache: false,
success: function (response) {
jQuery("#response").text(response['content']);
// debbuger;
console.log(response);
//console.log(response.hasOwnProperty('content'));
},
error: function (response) {
// alert("error");
jQuery("#responseOwner").text("An error occurred");
console.dir("Response: " + response);
}
}); //Code for AJAX Ends
// Clear all data after submit
var resetForm = document.getElementById('contactOwner').reset();
return false;
} //submitHandler
Thanks in advance for any kind of your help, any help will be highly appreciated!
I suspect the issue is the dataType: 'json' attribute. This is because the serialize function does not provide json data. See if this works:
jQuery.ajax({
url: '/classes/Form_process.class.php',
method: 'POST',
data: jQuery("#contactOwner").serialize()
}).done(function (response) {
console.log(response);
}).fail(function (error) {
console.log(error);
});
Alternatively, if you want to use dataType: 'json', you will need to send in json data:
jQuery.ajax({
url: '/classes/Form_process.class.php',
method: 'POST',
data: {
firstName: jQuery("#contactOwner .first-name").val(),
lastName: jQuery("#contactOwner .last-name").val(),
...
}
dataType: 'json',
cache: false,
}).done(function (response) {
console.log(response);
}).fail(function (error) {
console.log(error);
});
If you add you data using an object as shown above this should work with dataType: 'json'.

PHP code works when called with form action but not with ajax

The PHP code for login validation works properly when run from the html page by using form action but when run using ajax script it fails to load.
PHP code not involving database seems to run fine though.
JavaScript
< script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" > < /script> <
script >
$(document).ready(function() {
$("#login").submit(function(event) { //Trigger on form submit
$('#name + .throw_error').empty(); //Clear the messages first
$('#success').empty();
var postForm = { //Fetch form data
'name': $('input[name=name]').val(),
'password': $('input[name=password]').val() //Store name fields value
};
$.ajax({ //Process the form using $.ajax()
type: 'POST', //Method type
url: '.php', //Your form processing file url
data: postForm, //Forms name
dataType: 'json',
success: function(data) {
if (!data.success) { //If fails
if (data.errors.name) { //Returned if any error from process.php
$('.throw_error').fadeIn(1000).html(data.errors.name).append('<p>' + data.error + '</p>'); //Throw relevant error
alert("Nope");
}
} else {
$('#success').fadeIn(1000).append('<p>' + data.name + '</p>'); //If successful, than throw a success message
alert("yes");
}
}
});
event.preventDefault(); //Prevent the default submit
});
}); < /script>
PHP Code
<?php
$errors = array();
$form_data = array();
include("config.php");
if (session_status() == PHP_SESSION_NONE) {
session_start();}
else{
$_SESSION['ses']="Already in session":
/* Write already in session code */
}
if($_SERVER["REQUEST_METHOD"] == "POST") {
// username and password sent from form
$myusername = mysqli_real_escape_string($db,$_POST['username']);
$mypassword = mysqli_real_escape_string($db,$_POST['password']);
$sql = "SELECT * FROM users WHERE user_name = '$myusername' and password = '$mypassword'";
$result = mysqli_query($db,$sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$count = mysqli_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if (empty($_POST['name'])) { //Name cannot be empty
$errors['name'] = 'Name cannot be blank';
}
if (!empty($errors)) { //If errors in validation
$form_data['success'] = false;
$form_data['errors'] = $errors;
}
else{
if($count == 1) {
$_SESSION['login_user'] = $myusername;
}else {
$error = "Your Login Name or Password is invalid";
$_SESSION["error"] = $error;
}
}
}
echo json_encode($form_data);
?>

Returning variables PHP, MySQL and JS

I'm developing an PHP-MySQL-JS platorm. I'm doing now the profile page and there the user can update his info.
My code is:
HTML
<form>
//rest of the form.
//The submit button.
<button id="profile_submit" style="margin-left: 500px; margin-top: 10px;" class="logout" type="submit"><b>Guardar cambios</b></button>
</form>
JavaScript
$( document ).ready(function() {
$('#profile_submit').click(function(){
var name1 = $('#name1').val();
var name2 = $('#name2').val();
var user = $('#user').val();
var email = $('#email').val();
if(name1 != '' && name2 != '' && user != '' && email != '' ){
$.ajax({
url: '../controller/updateuser.php',
method: 'POST',
data: {name1: name1, name2: name2, user: user, email: email},
success: function(msg){
if (msg == '1'){
//Error
alert("Another user is using this email already");
} else {
//Se registro
alert("Updated");
setTimeout(function(){location.href= "workspace.php"} , 1000);
}
}
});
}
});
});
PHP - general
public function update_user($name1, $name2, $user, $email){
$res = $this->conexion->query("select USR_EMAIL from usr_usuario where USR_EMAIL = '".$email."' and USR_DELETE = '0' and USR_ID <> '".$_COOKIE['USR_ID']."' ");
if(mysqli_num_rows($res)>0)
{
//Email used
echo '1';
}else{
//Update user
$this->conexion->query("UPDATE usr_usuario SET USR_USERNAME = '".$user."', USR_NAME = '".$name1."', USR_NAME2 = '".$name2."', USR_EMAIL = '".$email."' WHERE USR_ID = '".$_COOKIE['USR_ID']."' ");
}
}
PHP - update.php
<?php
require("../modelo/conexion.php");
$name1 = $_POST['name1'];
$name2 = $_POST['name2'];
$user = $_POST['user'];
$email = $_POST['email'];
$object = new conexion();
$object -> actualizar_usuario($name1, $name2, $user, $email);
$object -> cerrar();
?>
Well, when the user clicks on the button with id="profile_submit", the JS read the info in the inputs and sends it to update.php and it calls the update_user in general php file.
When the user insert an email used already it works perfectly, but, when all is okay, the sql UPDATE works but the rest of the code(PHP and JS) don't sends nothing to the user.
I don't know why this happens...
Help please.

parsererrorDetails : SyntaxError: Unexpected end of input

I've been trying to do an ajax form for my web page.
Form sending informations into register.php for check process.
If its OK they are adding into database.
Problem is :
First record is always working properly. But if i try to add another record into database it gives parsererrorDetails : SyntaxError: Unexpected end of input error.
If the current information already exist in database i put the error message to the screen. But if i try to send another record it gives the same error.
I think i can't get the second data after submitting the first one is not coming back as a JSON.
Here is my code . Any help much appricated.
Server Side / register.php
I've got header('Content-type: application/json'); on the top.
try {
// local db connection
$conn = new PDO('mysql:host=localhost;dbname=db_trop#Dubai;charset=utf8','root','mysql');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if (isset($_POST)) {
// CHECK IF PASSWORD ALREADY IN USE
$objP = clear(strtoupper($_POST['objPass'])); // Get Ajax Data
// $stmt = $conn->prepare('SELECT Id,PassNumber FROM tblRecords WHERE PassNumber = ?');
// $stmt->execute(array($objP));
$stmt = $conn->prepare('SELECT Id,PassNumber FROM tblRecords WHERE PassNumber = :passnum');
$stmt->bindParam(':passnum', $objP);
$stmt->execute();
$PassResult = $stmt->fetchAll();
// (PDO::FETCH_ASSOC)
if($PassResult) {
// IF THE PASSWORD FAILS
$response_array['status'] = 'fail';
$response_array['message'] = 'Parola Kullanılıyor';
echo json_encode($response_array);
die();
} else {
// ADD DATA TO DATABASE
$fTerms = intval($_POST['objTerms']);
$fNameSurname = clear(strtoupper($_POST['objNameSurname']));
$fMail = clear($_POST['objEmail']);
$fGsm = clear(intval($_POST['objGsm']));
$fAddress = clear(strtoupper($_POST['objAdres']));
$DateTime = date('d-m-Y h:i:s');
if($fTerms==1) {
// SQL
$SqlQuery = "INSERT INTO tblRecords(NameSurname, Email, Gsm, Address, PassNumber,DateAdded, IsChecked)
VALUES (:fNameSurname, :fMail, :fGsm, :fAddress,:objP, :DateTime,:fTerms)";
// RECORDS
$addRecords = $conn->prepare($SqlQuery);
$addRecords->bindParam(':fNameSurname', $fNameSurname, PDO::PARAM_STR);
$addRecords->bindParam(':fMail', $fMail, PDO::PARAM_STR);
$addRecords->bindParam(':fGsm', $fGsm, PDO::PARAM_INT);
$addRecords->bindParam(':objP', $objP, PDO::PARAM_STR);
$addRecords->bindParam(':fAddress', $fAddress, PDO::PARAM_STR);
$addRecords->bindParam(':DateTime', $DateTime, PDO::PARAM_STR);
$addRecords->bindParam(':fTerms', $fTerms, PDO::PARAM_STR);
$addRecords->execute();
// END OF RECORD PROCESS
if ($addRecords) {
$response_array['status'] = 'success';
$response_array['message'] = 'BRAVO';
$conn = null;
} else {
$response_array['status'] = 'fail';
$response_array['message'] = 'OLMADI';
$conn = null;
}
} else {
die();
}
}
}
and Client Side / main.js
$("#register").submit(function (event, request) {
var password = $(this).find('input[name="objPassword"]').val();
var namesurname = $(this).find('input[name="objNameSurname"]').val();
var email = $(this).find('input[name="objEmail"]').val();
var gsm = $(this).find('input[name="objGsm"]').val();
var adres = $(this).find('input[name="objAddress"]').val();
var termsOk = $(this).find('input[name="objAcceptTerms"]').val();
var formURL = $(this).attr("action");
var postMessage;
if (postMessage) {
postMessage.abort();
}
var postData = {"objPass": password, "objNameSurname": namesurname, "objEmail": email, "objGsm": parseInt(gsm), "objAdres": adres, "objTerms": termsOk };
postMessage = $.post(formURL, postData, function (data) {
$('#register').trigger("reset");
})
.done(function(data) {
var defaultText = '';
if(data.status == 'success'){
$( ".info-row span" ).html(data.message);
$("#register").find('input[name="objPassword"]').val('');
$("#register").find('input[name="objNameSurname"]').val('');
$("#register").find('input[name="objEmail"]').val('');
$("#register").find('input[name="objGsm"]').val('');
$("#register").find('input[name="objAddress"]').val('');
$("#register").find('input[name="objAcceptTerms"]').val('');
$('input:checkbox').removeAttr('checked');
$('input').removeClass("error");
$('input[type=text]').focus(function() {
defaultText = $(this).val();
$(this).val('');
$( ".info-row span" ).html("");
});
// $('#register').trigger("reset");
console.log(data);
} else if(data.status == 'fail'){
$( ".info-row span" ).html(data.message);
$("#register").find('input[name="objPassword"]').val('');
$("#register").find('input[name="objNameSurname"]').val('');
$("#register").find('input[name="objEmail"]').val('');
$("#register").find('input[name="objGsm"]').val('');
$("#register").find('input[name="objAddress"]').val('');
$("#register").find('input[name="objAcceptTerms"]').val('');
$('input:checkbox').removeAttr('checked');
$('input').removeClass("error");
$('input[type=text]').focus(function() {
defaultText = $(this).val();
$(this).val('');
$( ".info-row span" ).html("");
});
console.log(data);
// $('#register').trigger("reset");
}
}) .fail(function (jqXHR, textStatus, errorThrown) {
alert(JSON.stringify(textStatus));
// $( ".info-row span" ).html(textStatus);
console.error("Error: " + textStatus + "Details : " + errorThrown);
// console.error("Error: " + textStatus + "Details : " + errorThrown);
}) .always(function(data) {
$('#register').trigger("reset");
});
event.preventDefault();
});
What i want to do is that:
Users can enter their informations consecutively and after each form has submitted i want to put error message on the screen (which is working right now but not working after first submit.)
Thanks

If statement not working in javascript/ajax

Ok so this is driving me mad. I've got 2 modal forms - login and register. Javascript does the client side validation and then an ajax call runs either a registration php file or a login php file which returns OK if successful or a specific error message indicating what was wrong (incorrect password, username already taken,etc). There is an If Then statement that checks if the return message is OK and if it is then a success message is displayed and the other fields hidden.
The register form works perfectly. I get my OK back and fields get hidden and the success message displays.
The login form however doesn't work. A successful login returns an OK but the if statement fails and instead of a nicely formatted success message I just get the OK displayed without the username and password fields being hidden which is what makes me think the IF is failing although I cannot see why it would.
I've been staring at this code for hours now and all I can see is the same code for both and no idea why one is working and one is not ....
On to the code...Here is the Login javascript:
$("#ajax-login-form").submit(function(){
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "php/login.php",
data: str,
success: function(msg) {
$("#logNote").ajaxComplete(function(event, request, settings) {
if(msg == 'OK') {
// Display the Success Message
result = '<div class="alertMsg success">You have succesfully logged in.</div>';
$("#ajax-login-form").hide();
$("#swaptoreg").hide();
$("#resetpassword").hide();
} else {
result = msg;
}
// On success, hide the form
$(this).hide();
$(this).html(result).slideDown("fast");
$(this).html(result);
});
}
});
return false;
});
and here is the register javascript:
$("#ajax-register-form").submit(function(){
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "php/register.php",
data: str,
success: function(msg) {
$("#regNote").ajaxComplete(function(event, request, settings) {
if(msg == 'OK') {
// Display the Success Message
result = '<div class="alertMsg success">Thank you! Your account has been created.</div>';
$("#ajax-register-form").hide();
} else {
result = msg;
}
// On success, hide the form
$(this).hide();
$(this).html(result).slideDown("fast");
$(this).html(result);
});
}
});
return false;
});
I don't think I need to add the php here since both just end with an echo 'OK'; if successful and since I'm seeing the OK instead of the nicely formatted success message I'm confident that it is working.
Any suggestions?
EDIT: Here's the login php:
<?php
require("common.php");
$submitted_username = '';
$user = stripslashes($_POST['logUser']);
$pass = stripslashes($_POST['logPass']);
if(!empty($_POST))
{
$query = "
SELECT
id,
username,
password,
salt,
email
FROM users
WHERE
username = :username
";
$query_params = array(
':username' => $user
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query ");
}
$login_ok = false;
$row = $stmt->fetch();
if($row)
{
$check_password = hash('sha256', $pass . $row['salt']);
for($round = 0; $round < 65536; $round++)
{
$check_password = hash('sha256', $check_password . $row['salt']);
}
if($check_password === $row['password'])
{
$login_ok = true;
}
}
if($login_ok)
{
unset($row['salt']);
unset($row['password']);
$_SESSION['user'] = $row;
echo 'OK';
}
else
{
echo '<div class="alertMsg error">Incorrect username or password</div>';
$submitted_username = htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8');
}
}
?>
if($login_ok)
{
unset($row['salt']);
unset($row['password']);
$_SESSION['user'] = $row;
echo 'OK';
}
else
{
echo '<div class="alertMsg error">Incorrect username or password</div>';
$submitted_username = htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8');
}
}
?> <!------- There is a space here! -->
There is a space after the closing ?> which is being sent to the user. The closing ?> is optional, and it is highly recommended to NOT include it, for just this reason. Get rid of that ?>.

Categories

Resources