First please excuse my English. So I built my own WordPress theme and want to use ajax in it, I'm using ajax for change post category in my post loop inside functions.php, so when a person clicked the button in index.php ajax will send the data and functions.php will change the category, the problem is i can't reach admin-ajax.php
SO IN HERE MY CODE IS JUST FOR TESTING IF THE AJAX WORK OR NOT, IT WONT ECHO THE POST THAT HAD BEEN SENT
This is my .js file that contains ajax
function kategori(kategori2){
//alert(kategori2);
jQuery.ajax({
url: MyAjax.ajax_url,
type: "POST",
data: { action: "berubah", kategori: "berita"},
success : function(data) {
}
});
}
This is my function.php
<?php
// Support Featured Images
add_theme_support( 'post-thumbnails' );
add_action( 'wp_enqueue_scripts', 'my_script_enqueuer' );
function my_script_enqueuer() {
wp_register_script( 'add-order-front', get_template_directory_uri() . '/js/programku.js' );
wp_localize_script( 'add-order-front', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
wp_enqueue_script( 'add-order-front' );
}
add_action( 'wp_ajax_berubah', 'berubah' );
add_action( 'wp_ajax_nopriv_berubah', 'berubah' );
function berubah()
{
$kategori = isset( $_POST['kategori'] ) ? $_POST['kategori'] : '';
echo $kategori;
wp_die();
}
I new to javascript too, I use Mozilla console and got this
'ReferenceError: ajax_object is not defined'
EDIT #1 -
i can reach admin-ajax.php now, my fault was i didn't have header.php on my theme, sorry i new in wordpress
now my problem is, function.php can't get the data sent by AJAX from programku.js and response in console is an HTML code
in my theme i just have 5 files
- index.php
- programku.js inside the js folder
- header.php
- footer.php
- and last functions.php
Is there is a files that important in wordpress theme developing that i left?
functions.php
file of your custom theme? And in the source code (HTML of the page), find the variableajax_object
- if it's nowhere, then your script may not be loaded/registered on that page.console.log(data)
to your ajax success function so you can see what you're getting back