0

I want to check my database from inside a JavaScript function. I have never done this before, and I can't seem to figure it out. I don't know if this is the right way, but it's the one I found. This is my simple HTML :

<!doctype html>
<html>
<head>
    <script src="Test.js"></script>
</head>
<body >
<p><a href="#" onClick="start();">Click me</a></p>
</body>

The JavaScript:

function start(){
    $.ajax({
        type: "POST",
        url: "checkDatet.php",
        datatype: "html",
        data: {functionname: 'Name', arguments: ['John']},
        success: function(data) {
            alert(data);
        }
    });
}

And the PHP :

<?php
function familyName($name1) {
    $username = "user";
    $password = "pass";
    $hostname = "localhost";
    $output ="AAA";
    $dbhandle = mysql_connect($hostname, $username, $password)
        or die("Unable to connect to MySQL");
    $selected = mysql_select_db("databasee", $dbhandle)
        or die("Could not select database 'databasee'");
    $names = mysql_query("SELECT name WHERE name1 = '$name'");
    if($row = mysql_fetch_assoc($names)){
        $data = $row{'name'};
        if($data <> null)
            $output= "found it";
        else
            $output= "havent found it";
    }
    echo $output;
}
?>
Leventix
  • 3,789
  • 1
  • 32
  • 41
Ann
  • 377
  • 5
  • 16

2 Answers2

2

Nothing is actually calling your function ! Do this:

function start(){
    $.get('checkDatet.php?name=John', function(data) {
        alert(data);
    }
});

Then in "checkDatet.php" you need to call your function:

<?php
familyName($_GET['name']);

function familyName($name1) {
$username = "user";
$password = "pass";
$hostname = "localhost";
$output ="AAA";
$dbhandle = mysql_connect($hostname, $username, $password)
    or die("Unable to connect to MySQL");
$selected = mysql_select_db("databasee", $dbhandle)
    or die("Could not select database 'databasee'");
$names = mysql_query("SELECT name WHERE name1 = '$name'");
if($row = mysql_fetch_assoc($names)){
    $data = $row{'name'};
    if($data <> null)
        $output= "found it";
    else
        $output= "havent found it";
}
echo $output;
}
?>
minychillo
  • 395
  • 4
  • 17
2

You call calling a file, and in that you are not calling the function, so just change your php code like this

<?php
    $username = "user";
    $password = "pass";
    $hostname = "localhost";
    $output ="AAA";
    $name = $_POST['name'];
    $dbhandle = mysql_connect($hostname, $username, $password)
        or die("Unable to connect to MySQL");
    $selected = mysql_select_db("databasee", $dbhandle)
        or die("Could not select database 'databasee'");
    $names = mysql_query("SELECT name WHERE name1 = '$name'");
    if($row = mysql_fetch_assoc($names)){
        $data = $row{'name'};
        if($data <> null)
            $output= "found it";
        else
            $output= "havent found it";
    }
    echo $output;

?>
Niranjan N Raju
  • 12,047
  • 4
  • 22
  • 41