Trying to call PHP script from Javascript If statement - javascript

I have a form which gets validated by javascript. In one of the if statements, in the final condition (when everything else has been validated) I would like to put my PHP script that updates SQL with one of the passwords.
This is the final validation:
function passwordCheck() {
var password = '<?php echo $password; ?>';
if (document.passwordform.inputedPassword.value == password)
{
if (document.passwordform.Password1.value == document.passwordform.Password2.value)
{
*********************************************************
} else
{
document.getElementById("equalpasswords1").innerHTML = "Passwords should be equal";
document.getElementById("equalpasswords2").innerHTML = "Passwords should be equal";
}
} else
{
text = "Insert a correct password";
document.getElementById("editpassword").innerHTML = text;
}
return true;
}
And I would like to insert a call to my PHP script where the stars are. How could I do this? I read that you can't insert PHP into javascript, so it has to be an external PHP file. My SQL update code is this one:
<?php
$x = $_POST['Password2'];
define('DB_NAME', 'Students');
define('DB_USER', 'Students');
define('DB_PASSWORD', 'Password');
define('DB_HOST','HOST');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db(DB_NAME, $link);
if (!$db_selected) {
die('Can\'t use'. DB_NAME. ': ' . mysql_error());
}
$result = "UPDATE `1956218_students`.`Students` SET `Password` = '$x' WHERE `Students`.`StudEmail` = '$email' ";
if (!mysql_query($result)) {
die('error: ' .mysql_error());
}
?>

You need to realize that JavaScript is being executed at client's side (in browser), while the PHP code is being executed at server's side.
So you need to make another request to the server, so that PHP codes can handle / process it (validate the password, prepare some response - ideally in JSON format etc.).
You might want to do something like:
How to validate a username / password via JQuery / Ajax?

Related

JAVA SCRIPT var with Double Quotes to PHP and back for Auto fill

I have an HTML/PHP form that uses JAVA SCRIPT function to send (POST) an input content to a PHP code which performs a query and gets back to the JAVA SCRIPT function with data to Auto fill additional inputs in the form.
It all works great when the input content i send is plain text, even if there is a single quote in the content it works.
BUT, as soon as double quotes are included in the input content it fails to return the Auto fill results.
Appreciate your help with indicating where do i fail with passing the quotes.
Thanks
Just to make it clearer, the code works if customer name is "Intel" or "Int'el" , but it fails when customer name is "Int"el"
Here is the JAVA SCRIPT function that sends and receive the data from the PHP:
!--Script Auto fill ltd by customer -->
<script type="text/javascript">
function updatefrm() {
setTimeout(function(){
var customer = $('#customer').val();
if ($.trim(customer) !='') {
$.post('customerfill.php', {customer: customer}, function(data) {
$('#customerupdate').val(data['customer']);
$('#ltdupdate').val(data['ltd']);
});
}
}, 10);
}
</script>
Here is the PHP code that gets the POST data , performs the query, and sends back the array for the JAVA SCRIPT auto fill:
<?php
if (!empty($_POST['customer'])) {
$DB_Server = "localhost"; // MySQL Server
$DB_Username = "XXXX"; // MySQL Username
$DB_Password = "XXXX"; // MySQL Password
$DB_DBName = "XXXXXXXX"; // MySQL Database Name
$Connect = #mysql_connect($DB_Server, $DB_Username, $DB_Password) or die("Failed to connect to MySQL:<br />" . mysql_error() . "<br />" . mysql_errno());
// Select database
$Db = #mysql_select_db($DB_DBName, $Connect) or die("Failed to select database:<br />" . mysql_error(). "<br />" . mysql_errno());
mysql_query('SET NAMES utf8');
mysql_query('SET CHARACTER SET utf8');
$safe_name = mysql_real_escape_string(trim($_POST['customer']));
$query = mysql_query(" SELECT * FROM customers WHERE customer = '". $safe_name ."' LIMIT 1 ");
if (mysql_num_rows($query) > 0) {
$row = mysql_fetch_assoc($query);
json($row);
} else {
json(null);
}
}
function json ($array) {
header("Content-Type: application/json");
echo json_encode($array);
}
i think your js code is fine and i think error in your php code and in that line
$query = mysql_query(" SELECT * FROM customers WHERE customer = '". $safe_name ."' LIMIT 1 ");
so you should use PDO Prepared Statements for security and not face problem with double quote
$dsn = "mysql:host=localhost;dbname=your_database;charset=utf8mb4";
try {
$pdo = new PDO($dsn, "database_username", "database_password");
} catch (Exception $e) {
echo "no connection";
exit();
}
$stmt = $pdo->prepare("SELECT * FROM customers WHERE customer = :customer LIMIT 1");
$stmt->execute(array(":customer"=>$safe_name));
$row = $stmt->fetch();

"CLI has stopped working" when trying to select all from an Oracle Database using JQuery?

I am attempting to use JavaScript and Jquery to search a database. I have set up a generic query.php file so that I can pass in the database and query and have it return an array. For some reason, when I try to select all using the *, my PHP server crashes with:
I am using the built in server with PHP 7.0.2. I am attempting to retrieve information from a Oracle database.
Here is the post statement:
$.post(DB1.filename,
{sid: DB1.sid,
username: DB1.username,
password: DB1.password,
host: DB1.host,
port: DB1.port,
sql: query},
function(res){
if(res == -1){
res = errorCode(DATABASE_CONNECTION_ERROR);
} else {
var a = parseObject(res);
var t = parseTable(a);
elements[TABLE].element.innerHTML = t;
}
log(FILE_NAME, "RETRIEVED query ");
}
);
Here is the query.php:
<?php
/* This script will connect to a database and search the given SQL string.
If the connection cannot be established, it will return -1. Otherwise, it will return a JSON array.
*/
//Parameters
$sql = $_POST["sql"];
//Database Information
$user = $_POST["username"];
$pass = $_POST["password"];
$host = $_POST["host"];
$port = $_POST["port"];
$sid = $_POST["sid"];
$connection = "(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = " . $host .")(PORT = " . $port . ")) (CONNECT_DATA = (SID = " . $sid . ")))";
//Establish connection
$conn = oci_connect($user, $pass, $connection);
//Check connection
if(!$conn){
echo -1;
} else {
//Query for the given SQL statement
$stRows = oci_parse($conn, $sql);
oci_execute($stRows);
oci_fetch_all($stRows, $res); //This is where the everything actually crashes
echo json_encode($res);
//Close the connection
oci_close($conn);
}
?>
So if I set the query as:
query = "select TABLE_NAME from ALL_TABLES";
everything works just fine. A table with a single column will be printed to the screen.
However, if I run:
query = "select * from ALL_TABLES";
I get the error above.
This happens regardless of which table I am attempting to connect to. My credentials are correct and I have tried different credentials as well. Any ideas why this is happening?
--UPDATE--
I tried hard coding the column names. I can select up to 8 columns before it crashes.There are 152 rows.
I circumvented the error by swapping the oci_fetch_all for oci_fetch_array as follows:
<?php
...
} else {
//Query for the given SQL statement
$stRows = oci_parse($conn, $sql);
oci_execute($stRows);
$res = array();
while($row = oci_fetch_array($stRows, OCI_NUM)){
$res[] = $row;
}
echo json_encode($res);
//Close the connection
oci_close($conn);
}
?>
This meant drastic changes to the function used to decode the JSON object array, but it does work. I will not mark this answer as correct though because I would very much like to know why my original code wasn't working...

Popup alert script in a php file [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 7 years ago.
I am trying to let a user log in. If the password and username is wrong, I want a popup to appear alerting the user on the error. When they close the alert, it goes back to index.php which is back to login screen.
But when it is wrong password/username, ends up going back to index.php without any popup messages first. My browser setting is not blocking any popups. Can I know what I'm doing wrong please.
<?php
if($login == true){
//Do login process
//this portion works as long as correct username and password
}
else{
echo '<script language="javascript">alert("Please enter valid username and password");</script>';
header("location:index.php");
}
?>
//login.php
<?php
$username = "exampleuser";
$password = "examplepass";
$host = "localhost";
$dbHandle = mysql_connect($host, $username, $password) or die("Could not connect to database");
$selected = mysql_select_db("database_name", $dbHandle);
$myUserName = $_POST['user'];
$myPassword = $_POST['pass'];
if(ctype_alnum($myUserName) && ctype_alnum($myPassword)){
$query1 = "SELECT * FROM users WHERE username='$myUserName'";
$result1 = mysql_query($query1);
$count1 = mysql_num_rows($result1);
if($count1 == 1){
$query2 = "SELECT password FROM users WHERE username='$myUserName'";
$result2 = mysql_query($query2);
$row = mysql_fetch_array($result2, MYSQL_ASSOC);
$pass = $row['password'];
if(password_verify($myPassword, $pass)){
$seconds = 120 + time();
setcookie(loggedIn, date("F js - g:i a"), $seconds);
header("location:mysite.php");
}
else{
echo '<script language="javascript">
alert("Please enter valid username and password");
window.location.href = "http://index.php";
</script>';
die();
}
}
else{
echo '<script language="javascript">
alert("Please enter valid username and password");
window.location.href = "http://index.php";
</script>';
die();
}
}
else{
echo '<script language="javascript">
alert("Please enter valid username and password");
window.location.href = "http://index.php";
</script>';
die();
}
?>
If you send headers to php it goes directly on index.php after the page goes in your condition.
If you try this code:
<?php
if($login == true){
//Do login process
//this portion works as long as correct username and password
}
else{
echo '<script language="javascript">
alert("Please enter valid username and password");
window.location.href = "http://index.php";
</script>';
die();
}
you will see that your code is correct. You need to track an event on popup closing to redirect to index.php via ajax or via http redirect.
EDIT 1:
Here you have a complete page with pdo. This is not the best way to do the job but it works. As you will see in the comments you have to avoid xss attacks and you should change database structure saving password hashed and salt to hide the users' clear password.
Here's the code.
<?php
//login.php
//connection via PDO
try{
$pdo = new PDO ('mysql:host=localhost; dbname=database_name', 'exampleuser' , 'examplepass', array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
//alert errors and warnings
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
exit('Database Error.');
}
//prepared statements sanitize input binding parameters, for you but you can use some libraries to prevent sql injection
$myUserName = trim(filter_var($_POST['user'], FILTER_SANITIZE_STRING));;
$myPassword = trim(filter_var($_POST['pass'], FILTER_SANITIZE_STRING));;
if(!empty($myUserName) && ctype_alnum($myUserName) && !empty($myPassword) && ctype_alnum($myPassword)){
$query1 = $pdo->prepare("SELECT password FROM users WHERE username = :username_param");
//bind parameter avoiding principal injection (pdo does not cover xss attacks, avoid it with other methods)
$query1->bindParam("username_param", $myUserName);
$result = $query1->fetch();
// or you can do $result = $query1->fetchColumn(); to get directly string instead of array
if($result['password']){
//you should use password_verify() if you have an hash stored in database, you should not save password in database.
//please google about best practice storing password, it's full of beautiful guides
//bad practice but will do the work
if($myPassword == $result){
$seconds = 120 + time();
setcookie('loggedIn', date("F js - g:i a"), $seconds);
header("location:mysite.php");
}else{
printAlert("Password incorrect");
}
}else{
printAlert("Username not valid");
}
}
else{
printAlert("Invalid data");
}
function printAlert($text){
echo "<script language='javascript'>
alert('$text');
window.location.href = 'http://index.php';
</script>";
die();
}
?>

ajax login form doesn't work

I am trying to pass user's info from mysql to the webpage, if the user has logged in but can't get it to work. If I put a wrong email or password it will show the error message but if the credentials are ok it would do anything...
on php file:
$sql = "SELECT * FROM users WHERE email='$l_email' AND password='$l_password'";
$query = mysql_query($sql) or die ('Error: ' . mysql_error());
$num_rows = mysql_num_rows($query);
if($num_rows < 1)
{
echo "You have entered a wrong email or password!";
}
else {
$memberInfo = array();
while( $row = mysql_fetch_array( $query ) )
{
$memberInfo[] = $row;
}
return $memberInfo;
echo json_encode( $memberInfo );
//echo "1";
}
on js file:
$.post("./includes/checkOut.php",{ l_email1: l_email, l_password1: l_password },
function(data) {
if(data=='1')
$("#checkOut_form")[0].reset();
$("#login_returnmessage").html("");
$("#memberInfo").hide("");
var memberInfo = jQuery.parseJSON(memberInfo);
for( var i in memberInfo )
{
var f_name = memberInfo[i].f_name;
var l_name = memberInfo[i].l_name;
var phone = memberInfo[i].phone;
}
$("#loggedinInfo").show("");
$('#_f_name').val(f_name);
$('#_l_name').val(l_name);
$('#_email').val(l_email);
$('#_phone').val(phone);
}
$("#login_returnmessage").html(data);
});
If you use return outside a function then it terminates the script at that point. This is exactly what you're doing here:
return $memberInfo;
echo json_encode( $memberInfo );
//echo "1";
You need to remove the return statement.
You should also add a Content-type: header to the response to tell the browser to expect JSON:
header('Content-type:application/json');
echo json_encode( $memberInfo );
Your Javascript code is checking the response for the value 1, which you're not sending, so the code that updates the display won't execute.
Lastly:
don't store passwords unencrypted - use password_hash()
don't use mysql as it's deprecated - use mysqli or PDO
ensure you escape your inputs before passing them to the database (or better, use prepared statements (not supported by mysql_*()).

How do I insert data from a php file using PDO?

I'm trying to log some data for my website using PDO from a PHP file. I have the following code which is called by by a javascript library, D3. The call works fine, but when I run this code I get an "internal server error".
What am I doing wrong? I have been following a guide on a website and I am basically using the same principles as them. If anyone can help I'd appreciate it. Thanks a lot in advance, my code is pasted below. (Of course the database information is something valid)
$hostname="xxxx";
$username="xxxxxx";
$pw="xxxxxxxx";
$dbname="xxxx";
try {
$pdo = new PDO ("mysql:host=$hostname;dbname=$dbname","$username","$pw");
} catch (PDOException $e) {
echo "Failed to get DB handle: " . $e->getMessage() . "\n";
exit;
}
//Gets IP for client.
$ip = get_client_ip();
//An email, format of string.
$email = "test#test.dk";
//An int, in this case 19.
$prgm_name = $_GET["prgm"];
//Piece of text, format of string of course.
$prgm_options.=$prgm_name;
$prgm_options.= " - ";
$prgm_options.=$_GET["gene"];
$prgm_options.=" - ";
$prgm_options.=$_GET["data"];
//Datasize, int.
$data_size = 0;
//Timestamp.
$now = "NOW()";
//Table name.
$STAT_TABLE = "stat";
$query = $pdo->prepare("INSERT INTO $STAT_TABLE (ip, email, prgm, options, datasize, date) VALUES (:ip, :email, :prgm_name, :prgm_options, :data_size, :now);");
$query->execute(array( ':ip'=>'$ip',
':email'=>'$email',
':prgm_name'=>$prgm_name,
':prgm_options'=>'$prgm_options',
':datasize'=>'$datasize',
':now'=>$now));
Try the following Code to Insert
$count = $pdo->exec("INSERT INTO $STAT_TABLE(ip, email, prgm, options, datasize, date) VALUES ('$ip','$email',$prgm_name,'$prgm_options','$datasize',$now)))");
/*** echo the number of affected rows ***/
echo $count;
I like to bind each parameter individually. I think it gives you more control over data types and sizes.
try {
$sth = $pdo->prepare("INSERT INTO...");
$sth->bindParam(":ip", $ip, PDO::PARAM_STR, 16);
$sth->bindParam(":email", $email, PDO::PARAM_STR, 30);
// etc...
$sth->execute();
} catch (Exception $e) {
print_r($e);
}

Categories

Resources