wonder if anyone can help; I’m trying to implement some ajax through jquery onto a form in a wordpress template.
The jquery is working, and the I can log a console message in the sucess: section, but the data is 0, when it should be calling the php function (at the moment on the same page, and I can call this directly)
so I guess the jquery is working, the admin-ajax is being called, its just the php function is not being called. Any ideas what I could be doing wrong ? I don’t fully understand hooks, so perhaps that is an issue – that I need to hook something in somewhere?
jquery (domain would replace comments)
<script type="text/javascript">
jQuery(function ($) {
$( "#movies" ).autocomplete({
minLength:2,
delay:500,
source: function( request, response ) {
$.ajax({
type: 'POST',
url: "http://<!--domain here -->/wp-admin/admin-ajax.php",
dataType: 'json',
data: {
action: 'getMoviesForCode',
searchString: $("#movies").val()
},
success: function( data ) {
response(data);
console.log('jjj'+data);
}
});
}
});
});
</script>
php function (on same page)
<?php
function getMoviesForCode(){
echo "
<script type="text/javascript">
alert("hh");
</script>
";
$searchString = $_POST['searchString'];
$results = va_getMoviesForCode($searchString);
$results = json_encode($results);
die($results);
}
?>
Thanks,
You’re doing it wrong. You php function should be in your theme’s
functions.php
file.You should then hook the function to
wp_ajax_[your_action]
andwp_ajax_nopriv_[your_action]
.Example of what should be in your
functions.php
: