night-gold night-gold - 3 months ago 8
Ajax Question

Can't make ajax work in wordpress

I'm starting with

wordpress
and did not have a lot of problem with it until now.

I want to look into my
database
using
ajax
when a user change the value of a
SELECT
aming to update form input. Easy with
ajax
and
php
using
php
and
jquery
, but I can't seem to grasp the concept behind it in wordpress.

All the php that will be posted is directly in the file where I have my form in my plugin. For the purpose of testing I'm currently only trying to have something from the
js
in the navigator console.

The php (wordpress):

add_action( "wp_enqueue_fetch_guide", "fetch_guide" );
function fetch_guide(){
wp_enqueue_script( 'guide', plugins_url( '/js/jquery.guide.js', __FILE__ ));

wp_localize_script('guide', 'fetchGuide', admin_url( 'admin-ajax.php' ) );
}

add_action("wp_ajax_nopriv_fetch_guide_return","fetch_guide_return");
add_action("wp_ajax_fetch_guide_return","fetch_guide_return");

function fetch_guide_return(){
global $wpdb;
if(isset($_POST["id"])){
$id = $_POST["id"];
$table = $wpdb->prefix."guide";

$guide = $wpdb->get_row("SELECT * FROM ".$table." WHERE id_guide LIKE ".$id.";");

print json_encode($guide);
}
}


The js:

$(function(){
jQuery("#chooseGuide").on("change", function(){
jQuery.ajax({
url : fetchGuide.ajax_url,
type : "post",
data : {"id":guide.value},
dataType: "json"
}).success(function(data){
if(data != 0){
console.log(data);
}
});
});
});

Answer

The problem here is that you are not pointing the ajax_url properly to your js.

Update these line

 wp_localize_script('guide', 'fetchGuide', admin_url( 'admin-ajax.php' ) );

to

 wp_localize_script('guide', 'fetchGuide', array('ajax_url' => admin_url( 'admin-ajax.php' ) ));

These will point the ajax_url properly and your function should work well

Comments