Ajax变量在php中不起作用

时间:2013-08-22 05:36:33

标签: php javascript ajax

这里我通过JavaScript从HTML页面获取值,从ajax访问该值并将该值传递给PHP页面。

PHP页面应该使用该ajax值从表中删除,但PHP没有获得该ajax值...

以下是我的尝试:

的JavaScript

var str;
function getResults(a) 
{
       str = a;
}

function showUser() {

    if(str=="") {
        document.getElementById("txtHint").innerHTML="";
        return;
    }

    if(window.XMLHttpRequest) {
        xmlhttp=new XMLHttpRequest();
    } else {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange = function() {
        if(xmlhttp.readyState==4 && xmlhttp.status==200) {
            document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET","getmovie.php?q="+str,true);
    alert(str);
    xmlhttp.send();
}

PHP

<?php
$q = strtolower(trim($_GET["q"]));
try 
{
$dbh = new PDO('mysql:dbname=theaterdb;host=localhost','tiger','tiger');
}
catch (PDOException $e) 
{
echo 'Connection failed: ' . $e->getMessage();
}
$sql = 'DELETE FROM movie WHERE LOWER(movie_name) = :q';
$sth = $dbh->prepare($sql);
$sth->bindValue(':q', $q);
$sth->execute();
$dbh = null;
?>

2 个答案:

答案 0 :(得分:1)

此代码看起来很好,在echo之后尝试delete operation

    .......
    ......
    if(!$q)  {// check the movie name,  if empty then return;
       echo 'Movie name is empty';
       return;
    }
    $sql = 'DELETE FROM movie WHERE LOWER(movie_name) = :q';
    $sth = $dbh->prepare($sql);
    $sth->bindValue(':q', $q);
    if($sth->execute())  $msg=$q.' deleted successfully.';
    else $msg=$q.' not deleted.';
    $dbh = null;
    echo $msg;
    return;
?>

答案 1 :(得分:1)

您是否已将Rohan在catch子句

之后发给您的代码放置好了
$q = strtolower(trim($_GET["q"]));
$q = strtolower(trim($_GET["q"]));
try 
{
$dbh = new PDO('mysql:dbname=your_database;host=localhost','your_user','your_password');
}
catch (PDOException $e) 
{
echo 'Connection failed: ' . $e->getMessage();
}
if(!$q)  {// check the movie name,  if empty then return;
   echo 'Movie name is empty';
   return;
}
$sql = 'DELETE FROM movie WHERE LOWER(movie_name) = :q';
$sth = $dbh->prepare($sql);
$sth->bindValue(':q', $q);
if($sth->execute())  $msg=$q.' deleted successfully.';
else $msg=$q.' not deleted.';
$dbh = null;
echo $msg;
return;
?>