There are quite a few similar problems I could find, but nothing helped, so have to post my own version of this question.
I have 2 php files:
- playing.php (contains the web form and sends the ajax call)
- plug_search.php (has the form processing code)
Before I started trying to use ajax, the form processing worked perfectly, the query worked as expected and the proper result was returned, based on the search parameters. Now, I want to use ajax, so the results are returned to the same page and it always returns ‘0’. I tried (seems like) everything I could, ruled out the most probable reasons (incorrect function/call name) – no luck. Feels like something very simple is missing, I suspect the problem is in the declaration of the function, but can’t see what’s wrong (it seems like the call never reaches processing function in plug_search.php). I stripped all the query code and just trying to return a simple string – still same ‘0’.
If you could help, I’d appreciate that a lot!
playing.php
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
function search(){
var plug=$("#autocomplete-dynamic").val();
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
if(plug!==""){
$("#result").html();
$.ajax({
type: "GET",
url: ajaxurl,
data: {
action: 'ajax_return_search_results',
plug: 'country'
},
success:function(data){
alert(data);
}
});
}
}
$("#button").click(function(){
search();
});
$('#search').keyup(function(e) {
if(e.keyCode == 13) {
search();
}
});
});
</script>
plug_search.php
<?php
add_action( 'wp_ajax_ajax_return_search_results', 'myajax_return_search_results' );
add_action( 'wp_ajax_nopriv_ajax_return_search_results', 'myajax_return_search_results' );
function myajax_return_search_results() {
echo "Success";
die();
}
?>
plug_search.php – Full version
function myajax_return_search_results() {
$value = $_GET['plug'];
$value2 = $_GET['country'];
$sql = "SELECT name, image_url, amazon_url, plug_type FROM adapters_list WHERE plug_type = '$value' AND country LIKE '%$value2%'" or die("Error in the consult.." . mysqli_error($link));
$result = $link->query($sql);
while($row = mysqli_fetch_array($result)) { ?>
<div id="output-product" style="border: 1px solid #333; font-family: Helvetica, sans-serif; font-size: 20px;"><?php echo $row["name"] . "<br />";?>
<?php echo "</div>";
die();
}
Add this code in your
functions.php
data is returning an error code because you are using .success instead of .done
You are missing datatype in ajax
Try adding it