Rayza Rayza - 1 year ago 66
PHP Question

JS $.post not loading PHP file

I copied the code from a YouTube tutorial, modified the database connection and SELECT items to connect to my existing DB, but I can't seem to get the JS to load the PHP file. In Chrome using the "inspect" tool, I can see that the JS file is loading, but when I click on GRAB on my HTML page, it doesn't do anything. Almost like the JS file is loading but not running.

Webserver folder structure:

-AJAX (folder)
-JS (folder)


<!doctype html>
<title>AJAX Database</title>
Name: <input type="text" id="name">
<input type="submit" id=name-submit" value="Grab">
<div id="name-data"></div>

<script src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
<script src="js/global.js"></script>

Javascript File

$('input#name-submit').on('click', function() {
var name = $('input#name').val();
if ($trim(name) != '') {
$.post('ajax/name.php', {name: name}, function(data) {

PHP File

Answer Source

I'm not sure why my PHP code was edited and removed from here, but I've ended up re-writing the whole PHP page. I added or die(mysql_error()); to my SELECT statement and found that it needed me to specify my database in the FROM. I have multiple databases on my server and even though the DB is specified in the connection string it needed it again in the SQL Statement. The next problem I resolved was removing the mysql_num_rows as this was just not working like the demo did.


    if (isset($_POST['name']) === true && empty ($POST['name']) === false) {
           require '../db/connect.php';

    $query =mysql_query("
           SELECT 'names'.'location'
           FROM 'names'
           WHERE 'names'.'name' = '" . mysql_real-escape_string(trim($_POST['name'])) . "'

    echo (mysql_num_rows($query) !== 0) ? mysql_result($query, 0, 'location') : 'Name not found';

The original was far too complicated for what I wanted and also for me to problem solve it so I re-wrote it:



    //I've intentionally left out the connection data..

    $sql_select = mysql_query("
          SELECT names.location
          FROM database_name.names
          WHERE names.name = '" . $_POST['name'] . "'
          or die(mysql_error());

    $sql_fetch = mysql_fetch_assoc($sql_select);

    echo $sql_fetch['name'];


Thanks to those that assisted. Appreciated...

I am aware of the deprecated tags in the PHP file, but when I was copying from a demo so I wanted to get it working before updating it with new tags.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download