php echo string cannot be checked in javascript by innerHTML - javascript

I'm quite new to php and javascript and I come up with some problems.
In my php file(i.e. a.php), I type code like this:
<?php
...(checking sth in database)...
if($found == 0)
echo "Valid";
else echo "Not Valid";
?>
Then, in my another php file, I pass form data to a.php for checking whether there are duplicate of records in the database, if no, it will print "Valid" in the label through AJAX:
function ajax(str){
var xhttp = new XMLHttpRequest;
xhttp.onreadystatechange=function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("e").innerHTML = xhttp.responseText;
}
};
var data = 'Email='+ str;
xhttp.open("POST", "a.php" , true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(data);
}
This is my label:
<label style="color: red;" id="e"></label>
I want to check whether the label value is "Valid" or not, then i wrote code like this:
var email = document.getElementById("e").innerHTML;
if (email == "Valid")
test.innerHTML = "it works!"; //test is another paragragh tag with id="test"
However I can't print "it works!", I've tried to echo another value (i.e. echo "1";), and when I type
if (email == 1)
it can print out "it works!".
Do anyone know why is this happening and what should I do if I want to print "Valid"?

If alerting email variable dislays "Valid" but if (email=='Valid') returns false, it means you have some additional characters in returned AJAX data.
So, try removing them with
Closing ?> tag in a.php (or removing spaces after ?> tag)
Making sure that database checking section doesn't print anything.
And you can also use alternative way to check that condition.
For example, you can do it so:
//var email = document.getElementById("e").innerHTML;
//if (email == "Valid")
var email = document.getElementById("e").innerHTML;
if (email.indexOf("Not")==-1)
test.innerHTML = "it works!";

Related

php doesn't receive string value from ajax

I'm trying to send the id of a clicked element via ajax to php. But it isn't working. The value is being sent from php file (contacts.php) to the javascript function callMessage(id) (which does return the right id when clicked), it is then calling the php file (get_message.php) which is supposed to query the result which has the right id. But when I echo the id it returns "Undefined variable".
Here's my code:
contacts.php
<div id="<?php echo $row['id']; ?>" onclick="callMessage(this.id)">
</div>
<div id="createMsg"></div>
contacts.js
function callMessage(id) {
var http = new XMLHttpRequest();
var url = 'includes/get_message.php';
http.open('GET', url, true);
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
document.getElementById("createMsg").innerHTML = this.responseText;
}
}
console.log(id);
http.send('id='+id);
}
here console.log(id) does return the id of the element that was clicked.
get_message.php
if(isset($_GET['id'])) {
$msg_id = $_GET['id'];
}
echo $msg_id;
The echo here returns "Undefined variable: msg_id". I've also tried using POST request to send the id value but that hasn't worked either.
A couple of issues:
echo $msg_id; should be inside the if in the PHP. Logically you don't want to echo that if it isn't populated, I would expect.
As per https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send, the 'id='+id will be added to the request body, whereas $_GET in PHP tries to retrieve values from the querystring. Therefore you need to attach the value to your url variable, and url-encode it.
So
if(isset($_GET['id'])) {
$msg_id = $_GET['id'];
echo $msg_id;
}
else echo "No ID supplied";
and
var url = 'includes/get_message.php?id=' + encodeURIComponent(id);
...
http.send();
is the correct solution here.
You are placing the data in a GET request with the 'send' function.
Submitting data via send is relevant for POST & PUT.
Data under send() for GET & HEAD will be replaced with NULL.
If you're using GET method use the URL parameter:
var url = 'includes/get_message.php?id=' + encodeURIComponent(id);

AJAX validating correct user

I'm using AJAX to delete posts from a forum.
The code does it so that the delete icon only shows if the session variable "user" equals the one in the database. This works perfectly so no need to include the code for that here i believe.
However, in theory, couldn't anyone just read the javascript code, go to the file where everything is processed and delete whatever they want?
My idea to fix this is to send over an additional variable with the username and check it once more on the processing page.
Ajax code:
$('#deletePost').click(function() {
var xhttp = new XMLHttpRequest();
var getId = <?php echo $_GET['id']?>
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var replace = confirm("Your post was successfully deleted. Click OK to return to the homepage.");
if (replace == true) {
location.replace('index');
} else {
location.reload();
}
}
}
xhttp.open('GET', 'deletepost.php?id=' + getId, true);
xhttp.send();
return false;
});
To explain my concern more deeply: Anyone can see the file where the information is processed, so they could just go to
http://www.website.com/deletepost.php
Then just apply any id they want so the url becomes something like
http://www.website.com/deletepost.php?id=22
And because there is no validation on the second page this would work.
<?php
if (!isset($_GET['id'])) {
echo 'e';
} else {
$id = intval($GET['id']);
$sql = 'DELETE FROM posts WHERE post_id=' . mysqli_real_escape_string($conn, $id);
$result = mysqli_query($conn, $sql);
if (!$result) {
echo 'Failed to delete your post. Please try again or contact administration.';
}
}
?>
So if anyone has any idea on how to validate this it would be very much appreciated. If anything is unclear please comment and I'll fill in.

selection the value of an option on a dropdown list

i'm working on this site that allows to students to book seats for training sessions by selectiong theme on a drop down list and clincking on a button. i created a javascript(ajax) script that contains a function which calls a php script that reduces the number of seats on my database.
But unfortunately it's not working... i need your help guys :
here's my javascript :
<select name="Branche" name="clock" id="clock" onchange="count()"></select>
<a onclick="count()" class="button">
<span class="user">Réserver une place</span>
</a>
<script>
function count(){
var place = document.getElementByTagName(clock);
var option = place.options[place.selectedIndex].id;
alert(option);
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "count.php?place=" + place,true);
xmlhttp.send(null);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var reponse = xmlhttp.responseText;
if(reponse == "yes") {
alert("Votre place a été réservé");
} else {
alert("Vous êtes arrivé trop tard !");
}
}
}
}
</script>
and here's my php script :
try {
$db = new PDO('mysql:host=localhost;dbname=projet','root','',array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
} catch(Exception $e){
echo $e->getMessage();
die();
}
$nom = $_GET['place'];
$sq="SELECT place FROM formation WHERE nom='$nom'";
$re = $db->query($sq);
$i = $re->fetch(PDO::FETCH_ASSOC);
if($i > 0){
$sqq="UPDATE formation SET place = place - 1 WHERE nom='$nom'";
$res = $db->query($sqq);
echo 'yes';
} else {
echo 'no';
}
The first errors are in this line:
var place=document.getElementTagName(clock);
You need to find the element by it's id, not its tag name. Also click is an non-existing variable; you should use "clock" with quotes:
var place=document.getElementById("clock");
That way place will be the select element. But then later you use this in building the URL parameter:
xmlhttp.open("GET","count.php?place="+place,true);
But place is not the selected value; it is the select element, so that will not work right. Instead you should send the value you have in the option variable:
xmlhttp.open("GET","count.php?place="+option,true);
This is assuming that the value of option is correct. Without seeing the HTML and your database table content, this is impossible to say at this moment.
The PHP script has an error here:
$i = $re->fetch(PDO::FETCH_ASSOC);
if($i>0){
You use $i as if it is the selected value, but that is not true. fetch() returns an array with values, in this case an array with one value. The comparison as you have it will always return true, even if the selected place value is 0.
Furthermore you should alter your PHP script so you do not concatenate values into an SQL string, as it makes you vulnerable to SQL injection. Instead use prepared statements.
Also, your PHP script is not working well when there is a lot of concurrency. Imagine that there is one seat left and two make the PHP call at the same time, then both will see there is one place left before the other one has decreased the count, and both will get a "yes".
Instead you should first perform the update and check for availability within the update statement. Then check if the statement updated a record. If not, then there were no places left. As an update statement locks the record during the update, only one process can do it at a time.
Suggested PHP code after database connection is established:
$stmt = $db->prepare("UPDATE formation
SET place = place - 1
WHERE nom = ?
AND place > 0");
$stmt->execute(array($_GET['place']));
echo $stmt->rowCount() ? 'yes' : 'no';

loop through JSON file using ajax, PHP & Javascript

I'm creating a small game where users must register or login before playing. I have a separate json file that stores already registered users.
Once a user enters their username and password into a field I make an AJAX call to retrieve the data using PHP with the intent of checking whether their details are on file. Firstly I tried sending back a JSON encoded object to parse through in Javascript. This is the code I have so far:
JSON:
{"LogIns":[
{
"Username":"mikehene",
"password":"123"
},
{
"Username":"mike",
"password":"123"
}
]
}
HTML:
<fieldset>
<legend>Please log in before playing</legend>
<form>
Username: <br>
<input type="text" placeholder="Enter a Username" id="username1" name="username"><br>
Password: <br>
<input type="password" placeholder="Enter a password" id="password" name="password"><br>
<input type="submit" value="Submit" onclick="return checkLogin();">
</form>
</fieldset>
PHP:
<?php
$username = $_POST['username'];
$str = file_get_contents('logins.json'); // Save contents of file into a variable
$json = json_decode($str, true); // decode the data and set it to recieve data asynchronosly - store in $json
echo json_encode($json);
?>
Javascript & AJAX call:
var usernamePassed = '';
function checkLogin(){
usernamePassed = document.getElementById("username1").value;
callAJAX();
return false;
}
function callAJAX(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange=function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
myFunction(xhttp.responseText);
}
}
xhttp.open("POST", "LogInReg.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("username=" + usernamePassed);
}
function myFunction(response) {
var arr = response;
var objJSON = JSON.parse(arr);
var len = objJSON.length;
for(var key in objJSON){
console.log(key);
}
}
But it only prints out "LogIns". I also tried this:
for (var i = 0; i < objJSON.length; ++i) {
if(objJSON[0].Username == usernamePassed){
console.log("found it");
}
else{
console.log("didn't find it!");
}
}
Therefore I tried another approach (parse the data in the PHP file) like so:
foreach ($json['LogIns'][0] as $field => $value) {
if($json['LogIns'][0]['Username'] == $username){
echo "Logged In";
break;
}
else{
echo "No user found";
break;
}
}
But when I enter "mike" as a user name it is echoing "No user found". So I'm lost! I'm new to coding and trying to learn myself. I would love to learn how to do it both methods (i.e. PHP and Javascript).
Everything I've found online seems to push toward JQuery but I'm not quite comfortable/good enough at JQuery yet so would like to gradually work my way up to that.
I haven't even got to the register a user yet where I'm going to have to append another username and password on registration.
Any help would be GREATLY appreciated.
Thanks in advance
Try this
$json = json_decode($str, true);
$password = $_POST['password'];
foreach($json['LogIns'] as $res)
{
if($res['Username']==$username && $res['password']==$password)
{
echo json_encode($res['Username']);
//echo 'user found';
}
}

Passing variable to php MySQL script with Javascript

I borrowed this code from another source.
Now, I am attempting to modify it.
I need to pass the contents of $q to my php page and use this as a where clause in my SQL statement.
My Javascript:
<script>
function subject(str) {
if (str == "") {
document.getElementById("subject").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("subject").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","form_get.php?q="+str,true);
xmlhttp.send();
}
}
</script>
Inside the html select code I am using:
onchange="subject(this.value)"
My PHP
$q = intval($_GET['subject']);
//if (!empty($_GET['q'])){
//$q = $_GET['q'];
//}
include('../conn/conn.php');
$sql = "select DISTINCT grade FROM primary_skills where subject= $q ";
As you can see, I am passing the $q into my SQL statement.
I understand that intval returns a number, but when I try other types, such as strval, it breaks the script. It als breaks the script when I tried the commented out section above.
When I change the php to: $q=$_GET["q"]; I get the error: form_get.php?q=Reading 500 (Internal Server Error).
This tells me that $q is indeed pulling from the options list, but something else is going on...
the problem is with your php you suppose to get the q and not subject
$q = intval($_GET['q']);
include('../conn/conn.php');
$sql = "select DISTINCT grade FROM primary_skills where subject= $q ";
$q = intval($_GET['subject']);
This looks wrong - should that not be $q = intval($_GET['q']);?

Categories

Resources