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.
Related
I realize that there are several similar questions that have been asked, but none of those have been able to get me over the top. Maybe what I wnat to do is just not possible?
I have a page on which there is an order form. The admin can create an order for any user in the database by selecting them in the dropdown menu and then fill out the form. But each user may have a PriceLevel that will give them a discount. So I need to be able to make a database call based on the username selected in the dropdown and display their price level and be able to use the username and pricelevel variables in my PHP.
I have the an add_order.php page on which the form resides, and an ajax.php which makes a quick DB call and returns the results in a json format.
The problem I am running into is actually getting the information from jQuery into the PHP. I have tried using the isset method, but it always comes back as false.
Here's what I have:
add_order.php
<?php
// $username = $_POST['orderUser']['Username'];
$username = isset($_POST['orderUser']) ? $_POST['orderUser']['Username'] : 'not here';
echo 'hello, ' . $username;
?>
...
$('#frm_Username').change(function() {
orderUser = $(this).val();
$.post('/admin/orders/ajax.php', {
action: 'fetchUser',
orderUser: orderUser
}
).success(function(data) {
if(data == 'error') {
alert('error');
} else {
console.log(data);
}
})
})
ajax.php
<?php
$action = $_POST['action'];
if($action == "fetchUser"):
$un = $_POST['orderUser'];
/*if($un):
echo $un;
exit;
endif;*/
// SET THE REST UP WITH MYSQL
if($un):
$qid = $DB->query("SELECT u.Username, u.PriceLevel FROM users as u WHERE u.Username = '" . $un . "'");
$row = $DB->fetchObject($qid);
// $row = jason_decode($row);
echo json_encode($row);
exit;
endif;
echo "error";
endif;
?>
I am logging to the console right now and getting this:
{"Username":"dev2","PriceLevel":"Tier 2"}
Any help would be appreciated. Thanks.
After calling $.post('/admin/orders/ajax.php', ...), the PHP code which sees your POSTed variable is ajax.php.
You need to check in there (inside ajax.php), whereas currently your isset check is in add_order.php, which does not see the POST request you send.
You do seem to have some logic in ajax.php, but whatever you've got in add_order.php is not going to see the data in question.
I know this site doesn't like "spot my mistake" code, but I'm desperate. I have a website that needs to access user-specific data from a database (PHP), convert the data into a JSON file, and then change a HTML header to display that specific data. The database table has the user email, password, and class name, among other things. I have a login page that establishes the session variables for the email and the password. When the user logs in, I want their class name to be entered into HTML text. I've used dozens of sources, mostly W3schools, and came up with this code:
PHP:
<?php
session_start();
header("Content-Type: application/json; charset=UTF-8");
$obj = json_decode($_GET["x"], false);
if (!$obj) {
die(mysqli_error());
}
$servername = "localhost";
$username = "id5143969_enviroquest1";
$password = "codeteam1";
$database = "id5143969_enviroquest1";
$link = mysqli_connect($servername, $username, $password, $database);
$result = $link->query("SELECT UserClassName FROM ".$obj->UserInfo1." WHERE ".$obj->UserEmail."= '". mysqli_real_escape_string($link,
$_SESSION['useremail']) . "' and ".$obj->UserPassword." = '" . mysqli_real_escape_string($link, $_SESSION['userpassword']) . "'");
if (!$result) {
die(mysqli_error());
}
$_SESSION['classname'] = $result->fetch_assoc();
if (!$_SESSION['classname']) {
die(mysqli_error());
}
echo json_encode($_SESSION['classname']);
Javascript:
function getclassname() {
var obj, dbParam, xmlhttp, myObj, x, txt = "";
obj = { "UserInfo1":"UserClassName"};
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myObj = JSON.parse(this.responseText);
document.getElementById("UserClassName").innerHTML = myObj;
}
};
xmlhttp.open("GET", "php2.php" + dbParam, true);
xmlhttp.send();
}
HTML:
<h1 class="text-center" id="UserClassName" name="UserClassName" onload=
"getclassname()"> </h1>
I have no idea what's going wrong, and am too new to coding to figure it out by myself.
Try this (I can't test it, but)—
PHP:
Remove the ?> at the end of the file. Pure-PHP files should always leave off the closing tag.
Change (MYSQLI_ASSOC) to just () - per this and the docs, you don't need it.
Javascript:
Remove the session_start() call
Change
for (x in myObj) {
txt += myObj[x].name + "<br>";
}
to
txt = myObj.UserClassName
The fetch_assoc() call in PHP gives you a mapping that uses the database field names ("each key in the array represents the name of one of the result set's columns" per the docs) for a single row. Therefore, if the JSON encode/decode worked OK, you should be able to refer directly to the field.
To test this, in the developer tools, set a breakpoint at the txt = ... line and see what myObj is.
I don't think you need $obj, dbParam, or ?x=, but I would not suggest changing them unless the above doesn't help.
Good luck!
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!";
I've been trying lately to use this sample of AJAX to compare form data to an SQL database from one http://www.example.com domain. My issue is that the readyState is always 1 and my Status is always 0. It is expecting 4 and 200 respectively. It also always returns responseText="" I've looked all over StackOverflow but have unsuccessfully found anything helpful.
I've boggled my mind over what could be the issue, but I just can't seem to get it to work.
*I've also tried to set file permissions on both the JS and PHP, but it functions the same.
*I'm using a dedicated web server to host all this, and I have no problem running most scripts.
//HTML GenerateRep.html
Excuse the lack of < and > tags missing, the code won't appear without them.
form id="formgen" onsubmit="GenRep(this)"
....form stuff....
button id="submit" type="submit">Submit</button
//JAVASCRIPT GenerateRep.js
function GenRep(formgen) {
var email = formgen['repemail'];
var hash = formgen['reppass'];
var first = formgen['firstname'];
var last = formgen['lastname'];
var territory = formgen['territory'];
hash.value = CryptoJS.SHA256(hash.value);
var login = email + ";" + hash.value + ";" + first + ";" + last + ";" + territory;
Login(login);
}
function Login(login) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
if(xhttp.responseText == "VALID") {
window.location.href = "success.html";
} else if (xhttp.responseText == "INVALID") {
$("#login_error").text("Failed! Plese check your info.");
} else {
window.location.href = "error.php";
}
}
};
xhttp.open("GET", "Validate.php?q=" + login, true);
xhttp.send();
}
//PHP Validate.php
<?php
header('Access-Control-Allow-Origin: *');
include ("ConnectDB.php");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//THIS IS A TEST TO SEE IF reponseText FUNCTIONS. IT DOES NOT.
//echo "testecho";
$whole = $_REQUEST['q'];
$userPass = explode (";", $whole);
$sql1 = "SELECT UName FROM Reps WHERE UName = '$userPass[0]'";
$result = $conn->query($sql1);
if ($result->num_rows > 0) {
$conn->close();
echo "INVALID";
} else {
$sql = "INSERT INTO Reps (UName, Pass, FName, LName, Territory) VALUES ('$userPass[0]', '$userPass[1]', '$userPass[2]', '$userPass[3]', $userPass[4])";
if ($conn->query($sql) === FALSE) {
$conn->close();
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
echo "VALID";
}
?>
I previously "commented" instead of creating an "Answer" because I wasn't suggesting a fix, just a debug step to make sure what you thought was happening, was actually happening.
Since my suggestion helped you figure out the problem, I created this "Answer" in case you want to give me "credit". :-)
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']);?