使用ajax调用时,不会填充MySQL查询数组
I'm using ajax to return the results of a sql query on a WordPress site. Basically, there are two queries and I am displaying the results of the second query. The first query gets a list of posts that contain a certain custom field. The second query looks through those posts and lists out the posts that have another custom field associated with them. Right now, if I don't use ajax and just add this to my page template, everything works.
<?php
$post_ids = $wpdb->get_col( "SELECT DISTINCT post_id FROM $wpdb->postmeta WHERE meta_key = 'Make' AND meta_value='Chevrolet'" );
// now get the food names
$stocktypes = $wpdb->get_col( "SELECT DISTINCT meta_value FROM $wpdb->postmeta WHERE meta_key = 'Model' AND post_id IN (". implode(',', array_map('absint', $post_ids) ) .")" );
if ($stocktypes) {
foreach ($stocktypes as $stocktype) {
echo "<option value=\"" . $stocktype . "\">" . $stocktype . "</option>";
}
}
?>
The problem comes when I add that to a separate file and call it with ajax. Here is the contents of my ajax file:
<?php
$models = $_GET['Make'];
$post_ids = $wpdb->get_col( "SELECT DISTINCT post_id FROM $wpdb->postmeta WHERE meta_key = 'Make' AND meta_value= %s", $models );
$stocktypes = $wpdb->get_col( "SELECT DISTINCT meta_value FROM $wpdb->postmeta WHERE meta_key = 'Model' AND post_id IN (". implode(',', array_map('absint', $post_ids) ) .")" );
if ($stocktypes) {
foreach ($stocktypes as $stocktype) {
echo "<option value=\"" . $stocktype . "\">" . $stocktype . "</option>";
}
}
?>
Here is my ajax call:
<script>
$(document).ready(function(){
$("#make").change(function() {
$.ajax({
url: "<?php bloginfo('template_url'); ?>/getModel.php",
data: { Make: $(this).val() },
dataType: "html",
type: "GET",
success: function(data){
$("#model").html(data);
}
});
});
});
</script>
The ajax call is working fine because I can echo the results of $models = $_GET['Make'];
By using print_r(array_values($post_ids));
, I found that the $post_ids array of the first query isn't being populated in my ajax file. The only thing I could think of is that wp-load.php (which allows for the use of WordPress functions) wasn't being loaded but that's not the problem.
The problem was in the first query. While I was using meta_value= %s
, I should have been using meta_value= $models
Also, as pointed out by Kevin B, I added type: "GET"
to my ajax call.