Jérémy
Jérémy

Reputation: 405

Empty data return after PHP AJAX

I don't get any data alert after using the following script

$(document).ready(function() {
    $('.autosuggest').keyup(function() {
        var search_term = $(this) .attr('value');
        $.post('search.php', {search_term:search_term}, function(data) {
            alert(data);
        });

    });
});

And using the following PHP code

<?php
include('system/includes/db_connect.php');
if (isset($_POST['search_term']) == true && empty($_POST['search_term']) == false) {

    $search_term = mysql_real_escape_string($_POST['search_term']);
    $query = mysql_query("SELECT username FROM promoties WHERE username LIKE '$search_term%'");
    while (($row = mysql_fetch_assoc($query)) !== false) {
        echo '<li>', $row['username'], '</li>';
    }
}
?>

If I put 'test' in the alert, it just works fine, but if I alert the data, it gives an empty alert box.

I also tested the PHP code on it's own, and it works perfectly..

What's wrong? Thanks!

Upvotes: 2

Views: 213

Answers (2)

Pir Abdul
Pir Abdul

Reputation: 2334

Use simple falsy value check.

if(isset($_POST['search_term']) && !empty($_POST['search_term'])) {
         // code here
}

Or Write some echo before the for loop. this will test with your query is executing or not.

Upvotes: 1

bipen
bipen

Reputation: 36531

if your .autosugest is an input(which i think it is)... you need to get its value by

replace this

var search_term = $(this) .attr('value');    

by

var search_term = $(this) .val();   

attr() is not needed here

Upvotes: 2

Related Questions