Hey I have a problem in Javascript-PHP variable passing
heres my php code:
<li id="' . $todo1 . '" class="items">' . $todo1 . '<button onclick="ajaxdelete(' . $todo1 . ')">Delete</button></li>
and heres the javascript function
function ajaxdelete(x){
var hr = new XMLHttpRequest();
var url = "ajaxtododelete.php";
var vars = "todo="+x;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
hr.send(vars); // Actually execute the request
}
and hers my ajax file:
<?php
session_start();
include_once "connect_to_mysql.php";
$todo = $_POST['todo'];
print "$todo";
$sql = mysql_query("DELETE FROM todo WHERE todo='$todo'");
?>
So instead of outputting the value of ‘$todo1′(which is wat i want) it outputs :
object HTMLLIElement.Any way around this?
First, you have a major hole in your application for SQL injection. Second, you need to quote the identifer so you are passing the value of the id in the function call instead of a reference to the element itself. Third, you probably ought to be using a framework for this and applying the handlers unobtrusively.
better (using jQuery)
And fix your PHP to use a parameterized query instead of string concatenation in case someone decides to modify the ids using a browser debugger and change the id in to a SQL command that will drop your entire database — or retrieve its contents for more nefarious purposes.