AbeDupa
AbeDupa

Reputation: 11

wordpress ajax - fetch information from a database with AJAX via wordpress

I found the script below at http://www.w3schools.com/php/php_ajax_database.asp. But I find hard to implement this via wordpress, this works perfectly at localhost but failed at wordpress. I've already done searching w/ same process but still unable to figure out. May I ask a step by step process on how to call ajax script via wordpress?

**The My Custom FrontPage**

<?php
/*
Template Name: Custom Template
*/
?>
<?php
/**
 * The template for displaying all pages.
 *
 * This is the template that displays all pages by default.
 * Please note that this is the WordPress construct of pages
 * and that other 'pages' on your WordPress site will use a
 * different template.
 *
 * @package WordPress
 * @subpackage Twenty_Eleven
 * @since Twenty Eleven 1.0
 */

get_header(); ?>
<script>
function showUser(str)
{
if (str=="")
  {
  document.getElementById("txtHint").innerHTML="";
  return;
  }
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
        <div id="primary">
            <div id="content" role="main">

<form>
<select name = "users" onChange = "showUser(this.value)">
                        <?php
                            include 'dbconfig.php';
                            $result=mysql_query("SELECT DISTINCT lastname FROM people ORDER BY lastname ASC;");
                            echo '<option value="">' . 'Select an Agent' . '</option>';

                            while ($row=mysql_fetch_array($result))
                                {
                                echo '<option value="' . $row['lastname'] . '">' . $row['lastname'] . '</option>';
                                }
                        ?>
                        </select>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here.</b></div>

            </div><!-- #content -->
        </div><!-- #primary -->

<?php get_footer(); ?>

The PHP File (getuser.php)

<?php
$q = intval($_GET['q']);

include 'dbconfig.php'; // PHP File to login credentials
$sql="SELECT * FROM people WHERE id = '".$q."'";

$result = mysql_query($sql);

echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";

while($row = mysql_fetch_array($result))
  {
  echo "<tr>";
  echo "<td>" . $row['FirstName'] . "</td>";
  echo "<td>" . $row['LastName'] . "</td>";
  echo "<td>" . $row['Age'] . "</td>";
  echo "<td>" . $row['Hometown'] . "</td>";
  echo "<td>" . $row['Job'] . "</td>";
  echo "</tr>";
  }
echo "</table>";

mysql_close($con);
?>

<?php
$q = intval($_GET['q']);

include 'dbconfig.php'; // PHP File to login credentials
$sql="SELECT * FROM people WHERE id = '".$q."'";

$result = mysql_query($sql);

echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";

while($row = mysql_fetch_array($result))
  {
  echo "<tr>";
  echo "<td>" . $row['firstname'] . "</td>";
  echo "<td>" . $row['lastname'] . "</td>";
  echo "<td>" . $row['age'] . "</td>";
  echo "<td>" . $row['hometown'] . "</td>";
  echo "<td>" . $row['job'] . "</td>";
  echo "</tr>";
  }
echo "</table>";

mysql_close($con);
?>

action taken: converted (getuser.php) as function then add to themes functions.php. then call wp add_action hook.please see below

function getuser(){
  //get the data from ajax() call
  //copied script from getuser.php
    }
  // creating Ajax call for WordPress
   add_action( 'wp_ajax_nopriv_getuser', 'getuser' );
   add_action( 'wp_ajax_getuser', 'getuser' );

Your help is much appreciated.Thank you .

Upvotes: 0

Views: 2832

Answers (1)

Andrew Plummer
Andrew Plummer

Reputation: 1170

First problem to address:

Those add_action's go in admin-ajax.php, which can then trigger functions in functions.php, it appears as if you have written those in functions.php? This is even for client facing ajax, even though that doesn't necessarily make sense.

A couple other points:

Consider using jquery or an ajax library at least at first to simplify things, on the client side.

Consider using the excellent JSON api here: http://wordpress.org/plugins/json-api/ , I wrote a huge amount of wp ajax functions manually then found that library addressed everything I wanted to do for far less work.

Edit:

Here is an example method from my website using Angular's $http method and the above json-api library. This example gets the latest 3 posts with the custom attribute and values specified, only returning some data (to save bandwidth).

var baseUrl = http://localhost:3000 // Your Site Url Here

$http({
        method:'GET',
        url:baseUrl,
        params:{
            json:'get_posts',
            count:3,
            include:'excerpt,thumbnail,title,slug,date,categories',
            meta_key: 'featured',
            meta_value: 'projects_yes'
        }
    })
        .success(function(data, status, headers, config){
            console.log(data);
        })
        .error(function(data,status,headers,config){
            console.log(data,',\n', status, headers, config);
        });

Upvotes: 1

Related Questions