Change PHP session variables using Javascript (AJAX) - javascript

I need to set PHP session variable or change is to "" or get it via javascript . for some reason the variables are not set and not get . Can the javascript there are any restrictions on this? Here is the sample code:
JS (get variable):
function getSessionVariable(variable){
if(typeof variable=="string"){
var xhttpSession = new XMLHttpRequest();
xhttpSession.open('POST','session.php',false);
xhttpSession.onreadystatechange= function(){
if(xhttpSession.readyState==4 && xhttpSession.status==200){
return xhttpSession.responseText;
}
}
xhttpSession.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xhttpSession.send("sessionValue="+variable+"&command=get");
}
JavaScript code above gets a normal result, which shows by the debugger, but for some reason the variables which are assigned for example function getSessionVariable('userName') is undefined (despite the fact that the debugger shows such as "return = 'Bob' ")
session.php
if(isset($_REQUEST['command']) && $_REQUEST['command']=='get' &&
isset($_REQUEST['sessionValue'])){
$value = $_REQUEST['sessionValue'];
$res = $_SESSION[$value];
echo ($res);
}
Same thing when changing values:
function logInCheck(){
var userName = getSessionVariable('userName');
if(document.getElementById('name').value!= userName && userName!=undefined){
if(getCookie('logined')=="true"){
var xhttpSession = new XMLHttpRequest();
xhttpSession.open('POST','session.php',true);
xhttpSession.onreadystatechange = function(){
if(xhttpSession.readyState==4 && xhttpSession.status==200){
xhttpSession.abort();
}
}
xhttpSession.send("command=end")}
}
session.php
if(isset($_REQUEST['command']) && $_REQUEST['command']=="end" && isset($_REQUEST['userName'])){
$userName = $_REQUEST['userName'];
$result = mysql_query('SELECT user_id FROM users WHERE userName="{$userName}"');
$row = mysql_fetch_array($result);
$user_id =$row['user_id'];
mysql_query("DELETE FROM userlist WHERE user_id= '{$user_id}'");
$_SESSION['userName']="";
$_COOKIE['logined']="";
}
Thanks in advance for any help.

Related

Ampersand being sent as & rather than & when attempting to update MySQL database

I am currently building an "admin" section where the information shown on the main site can be added to, updated and deleted using this one page.
All of my scripts function as intended, information is added to the database, rows are updated and deleted with no errors in 99.9% of cases.
The database is set up with 3 columns TITLE, DESCRIPTION and Image and when updating any of the rows I use the value in TITLE as my reference for WHERE statements.
However, any title containing an '&' symbol are downloaded fine and insert into my HTML as intended, however when being sent to my update script they are sent as &. This then doesn't register correctly with the update script and then it fails to update. I know '&' is converted to '&' when escaped but cannot understand why there is a second 'amp;' being sent?
Can anyone shed some light on this / point me to appropriate documentation to solve this issue?
Javscript Function(dbtable and titler are variables that decide the table to insert into )
function updating(indexno) {
var current = document.getElementById('title'+indexno).innerHTML;
var newtitle = document.getElementById('titlelink'+indexno).value;
var newdesc = document.getElementById('desclink'+indexno).value;
var newimage = document.getElementById('imagelink'+indexno).value;
if(newtitle == ""){
newtitle = document.getElementById('title'+indexno).innerHTML;
};
if(newdesc == ""){
newdesc = document.getElementById('description'+indexno).innerHTML;
};
if(newimage == ""){
newimage = document.getElementById('image'+indexno).innerHTML;
}
var request = "updatingdb.php?newtitle="+escape(newtitle)+"&newdesc="+escape(newdesc)+"&newimage="+escape(newimage)+"&currenttitle="+escape(current)+"&thetable="+escape(dbtable);
var xhr = new XMLHttpRequest();
xhr.open("GET", request);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText);
}
};
xhr.send(null);
thetester(dbtable,titler);
}
PHP Script
$thetable = htmlentities($_GET['thetable']);
$currenttitle = htmlentities($_GET['currenttitle']);
$newtitle = htmlentities($_GET['newtitle']);
$newdesc = htmlentities($_GET['newdesc']);
$newimage = htmlentities($_GET['newimage']);
$db = mysqli_connect($servername, $user, $password);
if (!$db)
{
echo"NO CONNECTION AVAILABLE";
exit();
}
mysqli_select_db ($db, "testing");
$query ="UPDATE `$thetable` SET `TITLE`= '$newtitle', `DESCRIPTION` ='$newdesc', `IMAGE` = '$newimage' WHERE `TITLE` = '$currenttitle'";
echo$query;
$results = mysqli_query($db, $query);
if(!$results)
{
echo"not working";
exit();
}
echo"updated";
This happens because you use htmlentities(), which will just see the & character and therefore makes an entity out of it. You could either remove htmlentities from the desired input field or do something like this:
$value = str_replace('&', '&', htmlentities($value));
or (better imo)
$value = htmlentities(html_entity_decode($value));

Wordpress, Javascript and Php : Am I placing authenticate-user.php in the right folder?

I am new to PHP and WordPress development.
On my WordPress page I want to check whether the aff_id in my page's query string is present as a user in my WordPress DB using AJAX.
Below is the JavaScript which I have placed on my WP page using "Scripts and styles" plugin:
var affId = '';
affId = GetParameterValues('aff_id');
if (affId == undefined || affId == '')
affId = 'AKotawala';
const xhr = new XMLHttpRequest();
xhr.onload = function () {
alert(this.responseText);
};
xhr.open("POST", "../wp-includes/authenticate-user.php");
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("username=" + affId);
function GetParameterValues(param) {
var url = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < url.length; i++) {
var urlparam = url[i].split('=');
if (urlparam[0] == param) {
return urlparam[1];
}
}
}
And here's my PHP code
authenticate-user.php
<?php
$username = $_POST['username'];
if (my_username_exists($username))
echo "Exist";
else
echo "NotExist";
function my_username_exists($username) {
global $wpdb;
$count = $wpdb->get_var($wpdb->prepare("SELECT COUNT(user_login) FROM $wpdb->users WHERE user_login = %s", $username));
return empty( $count ) || 1 > $count ? false : true;
}
?>
When the page loads my alert box is empty.
What am I doing wrong?
When I hard code the $username variable in my PHP and run the file as mydomain.com/wp-includes/authenticate-user.php it returns a blank page.
Am I placing authenticate-user.php in the right folder?
If yes what should be the url I should pass to my AJAX function in JS?
try including this in your authenticate-user.php file and place the file in the root directory.
require_once(dirname(__FILE__) . '/wp-config.php');
or give the relative path from the current directory
require_once(dirname(__FILE__) . '../wp-config.php');

How to build a Username Validator

I want to make a ambassador ID validator (LIKE USERNAME VALIDATOR) using php and xmlHttp request in javascript.
I wanted to send a xmlHttp request to a php file and that php file should return a integer value like "1" or "0". By reading that with javascript, it should change the message and disable or enable the submit button. So I've written the below code, but the javascript is not functional. the php seems to work perfectly, but having a line-break before the integer. is the line brake is responsible to Ineffectiveness of the javascript?
Here is the javascript,
<script>
function checkambassadorid(str){
if (str=="") {
document.getElementById("availability").innerHTML="";
return;
}
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
if(parseInt(this.responseText) === "0"){
document.getElementById("availability").innerHTML='<span class="text-success">Username Available</span>';
document.getElementById("submitter").disabled = false;
} else {
document.getElementById("availability").innerHTML='<span class="text-success">Username Not Available</span>';
document.getElementById("submitter").disabled = true;
}
xmlhttp.open("GET","ajax.php?data=checkambassadorid&ambassadorid="+str,true);
xmlhttp.send();
}
}
</script>
Here is the HTML,
Ambassador ID:
<input type="number" onkeyup="checkambassadorid(this.value)" id="ambassadorid" name="ambassadorid"> <span id="availability"></span>
And the PHP,
if($_GET['data'] == 'checkambassadorid'){
mysqli_set_charset($con,"utf8");
if(isset($_GET["ambassadorid"])){
$ambassadorid = mysqli_real_escape_string($con, $_GET["ambassadorid"]);
$query = "SELECT * FROM ambassadordb WHERE ambassadorID = '".$ambassadorid."'";
$result = mysqli_query($con, $query);
echo intval(mysqli_num_rows($result));
}
}
I think #dave nailed your issue on the head, but I'd like to propose a different approach.
Instead of responding with a binary value you could instead return a JSON payload indicating that the username is available (as well as any other pertinent data like suggested names if the requested one is taken)
if($_GET['data'] == 'checkambassadorid'){
mysqli_set_charset($con,"utf8");
if(isset($_GET["ambassadorid"])){
$ambassadorid = mysqli_real_escape_string($con, $_GET["ambassadorid"]);
$query = "SELECT * FROM ambassadordb WHERE ambassadorID = '".$ambassadorid."'";
$result = mysqli_query($con, $query);
$usernameIsAvailable = !(bool)intval(mysqli_num_rows($result));
$obj = new class{};
$obj->username = '$_GET["ambassadorid"]';
$obj->isAvailable = $usernameIsAvailable;
if(!$usernameIsAvailable) {
$obj->suggestions = ['generated', 'list', 'of', 'suggested', 'names'];
}
print json_encode($obj);
}
}
Then in your JS
const o = JSON.parse(this.responseText);
if(o.isAvailable) {
document.getElementById("availability").innerHTML='<span class="text-success">Username Available</span>';
} else {
document.getElementById("availability").innerHTML='<span class="text-success">Username Not Available</span>';
}
document.getElementById("submitter").disabled = !o.isAvailable;
You could even include a message with the response to eliminate the if(o.isAvailable) altogether.
I think the main issue, is that you have:
parseInt(this.responseText) === "0"
an integer 0 will never be equal to the string "0", and since you used ===, it is checking type as well as value. I would do:
if(this.responseText.trim() === "0"){

Debugging MySQL query in PHP when called from other page

Page1 has an input form. I validate the input field with a JavaScript:
<input type="text" name="frmBrand" size="50" onkeyup="BrandCheck();" maxlength="100" id="frmBrand" />
<span id="frmBrand_Status">Enter existing or new brand</span>
In the JavaScript I then call a PHP script:
function BrandCheck()
{
var jsBrandName = document.forms["AddPolish"]["frmBrand"].value;
if (jsBrandName !==null || jsBrandName !== "")
{
document.getElementById("frmBrand_Status").textContent = jsBrandName
// alert(jsBrandName);
var xmlhttp = new XMLHttpRequest();
var url = "CheckBrand.php";
var vars = "jsBrandName="+jsBrandName;
xmlhttp.open("POST",url,true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var return_data = xmlhttp.responseText;
document.getElementById("frmBrand_Status").innerHTML = return_data;
}
}
xmlhttp.send(vars);
document.getElementById("frmBrand_Status").innerHTML = "processing.....";
}
}
So far so good. I do get results from the CheckBrand.php because it changes the frmBrand_Status. But I can't get any database results from the PHP page.
<?php
if(mysqli_connect_errno()) { //if connection database fails
echo("Connection not established ");
}
//by now we have connection to the database
else
{
if(isset($_POST['jsBrandName']))
{ //if we get the name succesfully
$jsBrandName = $_POST['jsBrandName'];
$dbBrandName = mysql_real_escape_string($jsBrandName);
if (!empty($dbBrandName))
{
$dbBrandName = $dbBrandName . "%";
$sqlQuery = "SELECT `BrandName` FROM `Brand` WHERE `BrandName` like '$dbBrandName' ORDER BY `BrandName`";
$result = mysqli_query($con, $sqlQuery);
$NumRows = mysqli_num_rows($result);
// $BrandName_result = mysql_fetch_row($BrandName_query);
echo "Result " . $dbBrandName . " ----- ". $jsBrandName . "Number rows " .$NumRows. " BrandName = " .$result. " SQL " .$sqlQuery;
if( $BrandName_result = mysql_fetch_row($BrandName_query))
{
While ($BrandName_result = mysql_fetch_row($BrandName_query))
{
echo "Brand = " .$BrandName_result[0];
}
}
}
else
{
echo "dbBrandName = empty" . $dbBrandName;
}
}
}
?>
When doing this, the html page shows the constant change of the normal variables. For example when the input field holds "Clu" I get the following output the span ID frmBrand_Status:
Result Clu% ----- CluNumber rows BrandName = SQL SELECT `BrandName` FROM `Brand` WHERE `BrandName` like 'Clu%' ORDER BY `BrandName`
Which looks good as the brandname gets the % appended, but the Number of rows is not shown (empty field?), the SQL Query is shown and looks good, but I don't get any results.
And the if( $BrandName_result = mysql_fetch_row($BrandName_query)) section will not be reached, so there definitely is something going wrong in calling the query.
When I run that same query through PHPMyAdmin, i do get the result I expect, which is 1 row with a brandname.
I'm using firebug to try and troubleshoot the SQL Query, but I can't find where I can check this and I probably can't since PHP is serverside. correct? But how should I then trouble shoot this?
Found what was wrong.
The $con string I was using to open the database was no longer available. On other pages in the site, the $con is available, I load the database using an include script on my index page. But it seems that the variable gets lost when it is called through the XMLHttpRequest(). Which is logical now I think of it, since this can also be a call to a remote server. So my CheckBrand.php page was just missing the $con var to connect to the database.

How to get Json data in ajax after a mysql query

For my bookshop, I started to built a cashdesk script. This is a very simple form, with an ajax dynamic search. This is a script for a local PC, so the script will not be publish on the web.
When I scan the EAN code, I've my form fill with title, author, editor and price. The book is ready to add in the basket.
Now I'm trying to introduce Json in this script : but I don't understand how to get the values of the mysql query in the script, and put them in the correct fields of my cashdesk form.
I've tested the Mysql query and the Json.
The query
<?php
header('Content-Type: text/html; charset=ISO-8859-1');
include('connexion.php');
$connect_db = connect();
$i = 0;
$tmp = array();
$fetch = mysql_query("SELECT jos_vm_product.product_id,product_name,product_author,product_editor,jos_vm_product_price.product_price FROM jos_vm_product INNER JOIN jos_vm_product_price ON (jos_vm_product.product_id = jos_vm_product_price.product_id) WHERE product_EAN = '$_POST[EAN]'");
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
$tmp[$i] = $row;
}
echo json_encode($tmp);
close();
?>
A json exemple :
[{"product_id":"7097","product_name":"Paix pour tous - Livre audio","product_author":"Wayne W. Dyer","product_editor":"Ada","product_price":"20.28"}]
The ajax script
var xhr = null;
function getXhr()
{
if(window.XMLHttpRequest) xhr = new XMLHttpRequest();
else if(window.ActiveXObject)
{
try
{
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
}
else
{
alert("Not Working");
xhr = false;
}
}
function ajaxEAN()
{
getXhr();
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4 && xhr.status == 200)
{
var data = '{"product_id": "product_id", "product_name":"product_name", "product_author":"product_author", "product_editor":"product_editor", "product_price":"product_price"}';
oData = JSON.parse( data);
for( var i in oData){
document.getElementById( i).value = oData[i];
}
}
}
xhr.open("POST",'ajaxrecupaddr.php',true);
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
EAN = document.getElementById("EAN").value;
xhr.send("EAN="+EAN);
}
Thanks for any help !
As far as understand, you simply can't take a JSON from response. If so, than you simply should do:
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4 && xhr.status == 200) {
oData = JSON.parse(xhr.responseText);
for(var i = 0; i < oData.length; i++) {
for( var key in oData[i]){
document.getElementById(key).value = oData[i][key];
}
}
}
There, xhr.responseText will return a string with JSON received from server.
Also, few notes:
Instead of
header('Content-Type: text/html; charset=ISO-8859-1');
you should better use:
header('Content-Type: application/json;');
Also, in line below you are opened to SQL Injections:
$fetch = mysql_query("SELECT jos_vm_product.product_id,product_name,product_author,product_editor,jos_vm_product_price.product_price FROM jos_vm_product INNER JOIN jos_vm_product_price ON (jos_vm_product.product_id = jos_vm_product_price.product_id) WHERE product_EAN = '$_POST[EAN]'");
instead of simply doing WHERE product_EAN = '$_POST[EAN]' you should do, at least, WHERE product_EAN = '".mysql_real_esape_string($_POST["EAN"]) . "':
$fetch = mysql_query("SELECT jos_vm_product.product_id,product_name,product_author,product_editor,jos_vm_product_price.product_price FROM jos_vm_product INNER JOIN jos_vm_product_price ON (jos_vm_product.product_id = jos_vm_product_price.product_id) WHERE product_EAN = '".mysql_real_esape_string($_POST["EAN"]) . "'");
See more about mysql_real_escape_string. It will correctly escape all potentially dangerous symbols and will save you from errors when you have ' symbol in EAN. Also, read warning shown on a page linked above. You should better change your database extension as MySQL extension is deprecated.

Categories