Support » Plugins and Hacks » Hacks » Problems calling AJAX

  • I’m trying to create a page where I will run a search for a custom database table I’ve created and display the results. I’m trying to do it without refreshing the page, therefore I want to try and use AJAX or something similar. I have the form up, but the search seems to do nothing and I fear I’ve done something incorrect where the php file is either not being called, run, or returning data. Below is the code I’m using on the page it self for the search:

    <form action="javascript:void(0);" method="post">
        <input type="text" name="search" placeholder="Search Members" />
        <input type="submit" value="submit" />
    <?php add_action('wp_ajax_my_ajax', 'my_ajax');
    function my_ajax(){?>
    <script type="text/javascript">
            var str = $(this).serialize();
            $.ajax('/searchtest.php', str, function(result){
                alert(result); // the result variable will contain any text echoed by getResult.php
    <?php } ?>

    And the searchtest.php file looks like this:

     global $wpdb, $table_prefix;
     //This is only displayed if they have submitted the form
     if ($searching =="yes")
     echo "<h2>Results</h2><p>"; 
     //If they did not enter a search term we give them an error
     if ($find == "")
     echo "<p>You forgot to enter a search term";
     // Otherwise we connect to our Database 
     // We preform a bit of filtering
     $find = strtoupper($find);
     $find = strip_tags($find);
     $find = trim ($find); 
     //Now we search for our search term, in the field the user specified 
    $searchsql = "SELECT * FROM <code>wp_table</code> WHERE comp_name LIKE '%" . $find . "%' OR own_name LIKE '%" . $find . "%' OR comp_cat LIKE '%" . $find . "%'";
    $searchresult = mysql_query($searchsql) or die(mysql_error());
     //And we display the results
     echo "<table>";
     while($result = mysql_fetch_array( $searchresult ))
       $comp_name=str_replace(" ", "-", $comp_names);
          //display the row
     echo "<tr><td width=50%><div style=\"margin-left:25px\"><div style=\"margin:4px\"><a href=\"http://url/{$comp_name}\">$comp_names</a></td><td>$comp_cat</td><td>$comp_phone</td></tr> </div></div>";
     //This counts the number or results - and if there wasn't any it gives them a little message explaining that
     if ($anymatches == 0)
     echo "Sorry, but we can not find an entry to match your query<br><br>";
     //And we remind them what they searched for
     echo "<b>Searched For:</b> " .$find;
    echo "</table>";

    Basically I want to have a text box, do a quick search, and display all the results in a simple table. Any help or direction would be appreciated. Also let me know if you need clarification or have any questions.

  • The topic ‘Problems calling AJAX’ is closed to new replies.