I'm quite new with PHP/Jquery and I am trying to do an update password script for my web site. So far the passwords update but I'm struggling to think of how I would validate this to check against the old password.
Also, how would it be possible to display the error messages in an alert box (like java alert window). The reason I ask is because I would need to create an alert box if the old password doesn't match the password that exists in the database.
Any help on this would be much appreciated. If you need any additional code I will post this ASAP.
// *Update Profile Password* //
$("#btn-profile-update2").bind('click', function(){
// Get info from text boxes
/* var profile_oldpassword = $('#txt-prof-oldp').val(); */
var profile_newpassword = $('#txt-prof-newp').val();
var profile_confirmpassword = $('#txt-prof-confp').val();
new_password = $('#txt-prof-newp').val();
old_password = $('#txt-prof-oldp').val();
if (profile_newpassword !== profile_confirmpassword) {
response = "Passwords entered do not match"
alert(response);
return;
}
// An array of field names to be updated
var arr_field_names = Array();
// Add the field name to index of array
arr_field_names[0] = "Password";
// An array of field values that correspond with our field names...
var arr_field_values = Array();
arr_field_values[0] = profile_newpassword;
// Send to updateProfDetails function
updatePassword(arr_field_names,arr_field_values,new_password,old_password);
});
});
Which sends to this function:
function updatePassword(arr_field_names,arr_field_values,new_password,old_password) {
// Ajax parameters...
$.ajax({
// Request sent from control panel, so send to cp.request.php (which is the handler)
url: 'scripts/php/bootstrp/cp.request.php',
type: 'GET',
data: {
ft: "password",
table: "tblusers",
oldpassword: old_password,
newpassword: new_password,
field_names: arr_field_names,
field_values: arr_field_values,
// Either pass a row id as the 'id' OR a where clause as the 'condition' never both
id: null,
condition: null
},
dataType: 'text',
timeout: 20000,
error: function(){
$('#cp-div-error').html('');
$('#cp-div-error').append('<p>There was an error updating the data, please try again later.</p>');
$('#cp-div-error').dialog('open');
},
success: function(response){
// Refresh page
// location.reload(true);
}
});
}
and finally the PHP update:
public function password($tableName)
{
$PDO = new SQL();
$dbh = $PDO->connect(Database::$serverIP, Database::$serverPort, Database::$dbName, Database::$user, Database::$pass);
$username = UserAccount::get_useremail();
$password = hash('sha256',trim($_GET['newpassword']));
$oldpassword = hash('sha256',trim($_GET['oldpassword']));
// Does the password given match the password held?
$this->sql = "UPDATE $tableName SET password = '$password' WHERE UserName = '$username'";
try {
// Query
$stmt = $dbh->prepare($this->sql);
$stmt->execute();
$count = $stmt->rowCount();
echo $count.' row(s) updated by SQL: '.$stmt->queryString;
$stmt->closeCursor();
}
catch (PDOException $pe) {
echo 'Error: ' .$pe->getMessage(). 'SQL: '.$stmt->queryString;
die();
}
// Close connection
$dbh = null;
}
You almost got it.. key is here:
success: function(response) { .. }
just play with response maybe something like this:
success: function(response) {
if (response == "wrong password") alert ("don't guess");
else if (response == "password changed") alert ('you got it! congrats!');
}
I think Vytautas makes a good point, i havn't read it all trough but i just want to give you a important hint
put $PDO->connect in a try{}catch(){}
If the PDO connect function gets an error it prints your database information including password.
Related
I wrote some code that enters data into my sql database using JQuery and PHP and it works.
However, I need the error block of the Ajax request to be executed when the database server is offline, sql throws an error, or whenever there should be an error.
The problem is, that the error-block of the ajax request never is executed. Always just the success block. No matter if the sql query is wrong or the database server is offline.
I have tried it with a fail-block and with jQuery.$.get() but that doesn't work either. But I prefer an ajax request anyway.
I have written the following code so far:
//JavaScript-function to insert data into a database. The parameter is an SQL-INSERT statement.
function insertIntoDatabase(sqlQuery)
{
var result;
$.ajax({
type: "POST",
url: "../../general/clientHelper.php",
data: {sql: sqlQuery},
async: false,
error: function()
{
if(sqlQuery.split(" ")[0] != "INSERT") console.log("SQL-Query is not an INSERT statement");
result = false;
},
success: function()
{
result = true;
}
});
return result;
}
<?php
//clientHelper.php - Insert data into the database.
if(isset($_POST['sql'])) insertIntoDatabase($_POST['sql']);
function insertIntoDatabase($sqlQuery)
{
$ip = "10.10.10.1";
$port = 3306;
$username = "candidate";
$password = "candidate";
$dbname = "cqtsdb";
$connection = new mysqli($ip, $username, $password, $dbname, $port);
$connection->query($sqlQuery);
$connection->close();
exit();
}
?>
I don't know what to do now :/ Please help <3
UPDATE:
I found out that if I add one parameter to the success function it gets filled with the text of an error if one has occurred. If everything is right the text is just "". So I didn't have to do anything else than check for it :)
success: function(data)
{
if(data == "") result = true;
else result = false;
}
Check the query result, if it was successful then return a certain value to ajax like 1, if it wasn't, return 0.
Then in ajax success function check that value and show a message accordingly or whatever you want to do.
I use procedural PHP and I do it this way
function leave($msg, $conn, $type){
//$msg is the message I want to display to the user.
//$type is the query result type I explained above.
//$conn is to close the connection.
echo json_encode(array(
"msg" => $msg,
"type" => $type
));
mysqli_close($conn);
exit();
}
call this function that way
$result = mysqli_query($conn, $query);
if ($result) {
leave('done', $conn, 1);
} else {
leave('something went wrong', $conn, 0);
}
check the value like that:
...
success: function (response) {
if(response.type == 1){
// do smth
}
else if(repsonse.type == 0){
// do another thing
}
},
...
I have a favourites button calling an ajax request to update a MySQL database.
I would like to have a alert if there are duplicate additions or too many additions.
Can anybody see a way that I could show an alert if there is a duplicate addition? My code is below:
AJAX REQUEST
$.ajax({
type: 'post',
url: 'favaddDB.php',
data: $('#addfaveform').serialize(),
success: function () {
alert('Added To Favourites');
}
});
PHP
$db = new PDO("mysql:host=localhost;dbname=favourites", 'root', '');
$query1="SELECT * FROM `$email` ";
$stat1=$db->prepare($query1);
$stat1->execute();// IMPORTANT add PDO variables here to make safe
//Check if fave adds >9
$count = $stat1->rowCount();
$fave=$count;
if ($fave>9) {die(); exit();} // HERE I WISH TO RUN AN ALERT OR SEND BACK A MESSAGE TO DISPLAY
else {$fave=$fave+1;}
Just return the text to alert to your javascript:
$db = new PDO("mysql:host=localhost;dbname=favourites", 'root', '');
$query1="Query here ($email/similar should NOT BE HERE! Add them via execute/prepare.";
$stat1=$db->prepare($query1);
$stat1->execute();// IMPORTANT add PDO variables here to make safe
//Check if fave adds >9
$count = $stat1->rowCount();
$fave=$count;
if ($fave>9) {die("Here is a message");} // HERE I WISH TO RUN AN ALERT OR SEND BACK A MESSAGE TO DISPLAY
else {$fave=$fave+1; die("Here is another message"); }
Ajax request:
$.ajax({
type: 'post',
url: 'favaddDB.php',
data: $('#addfaveform').serialize(),
success: function (message) {
alert(message);
}
});
Additionally, you should consider using JSON, to pass back entire objects to your javascript, and parse it there:
$db = new PDO("mysql:host=localhost;dbname=favourites", 'root', '');
$query1 = "Query here ($email/similar should NOT BE HERE! Add them via execute/prepare.";
$stat1 = $db->prepare($query1);
$result = $stat1->execute();// IMPORTANT add PDO variables here to make safe
// Tell javascript we're giving json.
header('Content-Type: application/json');
if (!$result) {
echo json_encode(['error' => true, 'message' => 'A database error has occurred. Please try again later']);
exit;
}
//Check if fave adds >9
$count = $stat1->rowCount();
$fave = $count;
if ($fave > 9) {
echo json_encode(['error' => false, 'fave' => $fave, 'message' => 'Fave > 9!']);
} // HERE I WISH TO RUN AN ALERT OR SEND BACK A MESSAGE TO DISPLAY
else {
$fave = $fave+1;
echo json_encode([
'error' => false,
'fave' => $fave,
'message' => 'Current fave count: ' . $fave
]);
}
And in your ajax, make sure you set dataType: 'json', which will automatically parse it into an object:
$.ajax({
type: 'post',
url: 'favaddDB.php',
data: $('#addfaveform').serialize(),
dataType: 'JSON',
success: function (res) {
if (res.error) {
//Display an alert or edit a div with an error message
alert(res.message);
} else {
//Maybe update a div with the fave count
document.getElementById('#favcount').value = res.fave;
alert(res.message);
}
}
});
Simple is better, in most cases.
By returning messages, you can do whatever you want on the frontend side, depending on the message.
PHP:
<?php
$db = new PDO("mysql:host=localhost;dbname=favourites", 'root', '');
$query1 = "SELECT * FROM " . $email;
$stat1 = $db->prepare($query1);
$stat1->execute();
$count = $stat1->rowCount();
$fave = $count;
if ($fave > 9) {
echo "tooMany"; exit();
} else {
echo "addedFav"; $fave++;
}
JS:
jQuery.post({
url: 'favaddDB.php',
data: jQuery('#addfaveform').serialize()
}).then(function (code) {
switch (code) {
case "addedFav":
alert('Added To Favourites');
break;
case "tooMany":
alert('Too many favourites');
break;
}
}).catch(function (error) {
console.log(error);
});
I have some code that sends a variable (pin) to php via AJAX the database is then queried and if a result is found the php echo's a value of 1. Everything is working fine, except that the Ajax does not recognise the value returned by the php.
Here is my code
$(document).ready(function () {
$("form.submit").submit(function () {
var pin = $(this).find("[name='pin']").val();
// ...
$.ajax({
type: "POST",
url: "http://www.example.com/pin.php",
data: {
pin : pin,
},
success: function (response) {
if (response == "1") {
$("#responsecontainer").html(response);
window.location.href = "home.html?user=" + user;
// Functions
} else { // Login failed
alert("LOGIN FAILED");
}
}
});
this.reset();
return false;
});
});
And here is my PHP code, I know that the code below returns a value of 1. When Ajax is triggered it returns a value that generates a login fail message. Is there a way to see what Ajax is sending, if i swap out the ajax and directly submit the for to the server it also returns a 1 on the php echo.
$pin = $_GET["pin"];
$db = new PDO("mysql:host=localhost;dbname=xxxxx;charset=utf8", "xxxx", "xxxx");
$count = $db->query("SELECT count(1) FROM users WHERE pin='$pin'")->fetchColumn();
echo $count;
It's recommended to return JSON data as result for an ajax request.
So try this :
Edit: I've updated the php code to make the sql query with PDO prepare() method taking into account #Dominik's commentary
$pin = $_POST['pin'];
$db = new PDO('mysql:host=localhost;dbname=xxxxx;charset=utf8', 'xxxx', 'xxxx');
$stmt = $pdo->prepare('SELECT count(1) FROM users WHERE pin = :pin');
$stmt->execute(array('pin' => $pin));
return json_encode([
"count" => $stmt->fetchColumn()
]);
And in your ajax success callback :
...
success: function(response) {
var count = JSON.parse(response).count;
if (count == "1") {
$("#responsecontainer").html(response);
window.location.href = "home.html?user="+ user;
} else {// Login failed
alert("LOGIN FAILED");
}
},
error: function(error) {
...
}
Hope it's helps you :)
I'm new to ajax and this is my first attempt to use it.
What I'm trying to do is create a small system to register an email and password to the database without updating the page and it worked just fine!
However, as you will notice on my 'register.php' file, there is a condition to not allow duplicate emails, as well as PDOException to prevent errors...so, how can I send a message (an alert or whatever) to my index page in case any of them occurs?
This is my .js file:
$(document).ready(function(){
$("#btnRegister").click(function(){
$.ajax({
type: 'post',
url: 'register.php',
data: { txtEmail: $("#frmEmail").val(), txtPassword: $("#frmPassword").val() }
}).done(function(){
$("#frmEmail").val('');
$("#frmPassword").val('');
$("#frmEmail").focus();
});
});
});
My 'register.php' file:
<?php
try
{
$handler = new PDO('mysql:host=127.0.0.1;dbname=register', 'root', '');
$handler -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$email = $_POST['txtEmail'];
$password = $_POST['txtPassword'];
$sql = "SELECT email FROM users WHERE email = ?";
$query = $handler -> prepare($sql);
$query -> bindValue(1, $email);
$query -> execute();
if(($query -> rowCount()) != 0)
die("Error: the inserted email already exists.");
else
{
$sql = "INSERT INTO users (email, pass) VALUES (?, ?)";
$query = $handler -> prepare($sql);
$query -> bindValue(1, $email);
$query -> bindValue(2, $password);
$query -> execute();
}
}
catch(PDOException $ex)
{
die("Error: " . $ex -> getMessage());
}
?>
Usually, your PHP file would return a response indicating the success or failre of the registration.
In your PHP file, instead of dieing when there is an error, you should return a json-encoded array containing the error message, for example:
if(($query -> rowCount()) != 0)
echo json_encode(array('error' => "Error: the inserted email already exists."));
exit;
else
Then in your javascript's done function, you can check for this message:
}).done(function(data){
if (data.error) {
alert(data.error); // or do something else
} else {
// every thing looks ok, do your thing
}
});
I'd recommend always returning something from php, whether it's an error message as above, or simply json_encode(array('success' => true));. That way, you can be sure that the request has actually done what is expected, and not returned a blank page for another (bad) reason.
Note: if you have problems getting this to work, you might need to add dataType: 'json' to your ajax options (under type: 'post')
All you need to do is change all the die(); to echo ""; so instead of killing the PHP part, it returns the messages towards your index file. Next just change your jQuery script to:
$(document).ready(function(){
$("#btnRegister").click(function(){
$.ajax({
type: 'post',
url: 'register.php',
data: { txtEmail: $("#frmEmail").val(), txtPassword: $("#frmPassword").val() }
}).done(function(msg){
if(msg != ''){
alert(msg);
}
$("#frmEmail").val('');
$("#frmPassword").val('');
$("#frmEmail").focus();
});
});
});
i have a login box...
when the user starts typing.. i want to check whether the LOGIN NAME entered exists in the database or not...
if the login name is exist i am going to set the login button active... if it doesnot exist i am going to set the login button deactive...
offcourse i am going to need AJAX to perform my mySQL via PHP tough i don't know how it will be done...
lets say this is my query
<?php
$result = mysql_query("SELECT * FROM accounts WHERE name='mytextboxvalue'");
?>
how to do it
keep it simple:
$(document).ready(function(){
var Form = $('#myForm');
var Input = $('input.username',Form)
Input.change(function(event){
Value = Input.val();
if(Value.length > 5)
{
$.getJSON('/path/to/username_check.php',{username:Value},function(response){
if(response.valid == true)
{
Form.find('input[type*=submit]').attr('disabled','false');
}else
{
Form.find('input[type*=submit]').attr('disabled','true');
}
});
}
});
});
and then PHP side..
<?php
//Load DB Connections etc.
if(!empty($_REQUEST['username']))
{
$username = mysql_real_escape_string($_REQUEST['username']);
if(isset($_SESSION['username_tmp'][$username]))
{
echo json_encode(array('valid' => (bool)$_SESSION['username_tmp'][$username]));
die();
}
//Check the database here... $num_rows being a validation var from mysql_result
$_SESSION['username_tmp'][$username] = ($num_rows == 0) ? true : false;
echo json_encode(array('valid' => (bool)$_SESSION['username_tmp'][$username]));
die();
}
?>
You can use JSON-RPC, here is implementation in php.
and in JQuery you can use this code.
var id = 1;
function check_login(){
var request = JSON.stringify({'jsonrpc': '2.0',
'method': 'login_check',
'params': [$('#login_box').val()],
'id': id++});
$.ajax({url: "json_rpc.php",
data: request,
success: function(data) {
if (data) {
$('#login_button').removeAttr('disabled');
} else {
$('#login_button').attr('disabled', true);
}
},
contentType: 'application/json',
dataType: 'json',
type:"POST"});
}
and in php
<?php
include 'jsonRPCServer.php';
//mysql_connect
//mysql_select_db
class Service {
public function login_check($login) {
$login = mysql_real_escape_string($login);
$id = mysql_query("SELECT * FROM accounts WHERE name='$login'");
return mysql_num_rows($id) != 0;
}
}
$service = new Service();
jsonRPCServer::handle($service);
?>
Look at jQuery AJAX and jQuery TypeWatch
But like #halfdan said, this is a potential security risk. I have never seen a site do this with a username, only with search results.
Your potentially giving away an end point (URL) on your web site which anyone could query to find out if a username is valid. Intranet or not, it is a risk.