Matthew Matthew - 6 months ago 9
PHP Question

Odd Javascript/PHP behavior with AJAX Post

I have a function that sends a post request to a php website. I get 2 different behaviors by simply changing the capitalization of a variable. The variable in question is the 'action' variable and either being set to "deleteIndexMain" or "deleteIndexmain" If the action variable is set to "deleteIndexmain" I get the popup displaying the html that the php returns. If I set the variable to "deleteIndexMain" I get no popup. (meaning it appears to be a javascript issue?

Here is the java script code:

function deleteMe(v,r)
{
if(confirm("Are you sure"))
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if(xhttp.readyState == 4 && xhttp.status == 200)
{
alert(xhttp.responseText);
document.getElementById("indexmaintable").deleteRow(r);
}
};
xhttp.open("POST", "includes/control.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("action=deleteIndexMain&file="+v);
}

}


and here is the php code:

<?php
//Todo make sure to authenticate!

session_start();
require_once("config.php");


function deleteIndexMain($file)
{
unlink($file);
$query = 'DELETE FROM indexmain WHERE linklocation="'.$file.'"';
$db->query($query);
}

print_r($_POST);
if(isset($_POST) && $_POST['action'] == "deleteIndexMain")
{
echo 'Deleting '.$_POST['file'];
deleteIndexMain($_POST['file']);
}



?>

Answer

String comparison with == is case-sensitive. If you want to perform a case-insensitive comparison, you can use strcasecmp():

if(isset($_POST) && strcasecmp($_POST['action'], "deleteIndexMain") == 0)

Notice that strcasecmp doesn't return a boolean, it returns a number that indicates whether the first string is less than, equal to, or greater than the second. So you have to use == 0 to test if the strings are equal.

Or you can convert everything to a single case with strtolower() before comparing normally.

if(isset($_POST) && strtolower($_POST['action']) == "deleteindexmain")
Comments