Could anyone help me to wrap my head around this please? I’m trying to load WordPress post (custom post type) title/content in modal, but struggling to get it right. I’m quite new to php and ajax, so I have picked pieces of code from different tutorials and I try to assemble them all together.
So first I add a path to localize my script:
wp_localize_script( 'darkam_global', 'openpost', array(
'ajaxurl' => admin_url( 'admin-ajax.php' )
));
This is what my php function looks like:
add_action( 'wp_ajax_nopriv_open_post', 'my_open_post' );
add_action( 'wp_ajax_open_post', 'my_open_post' );
function my_open_post() {
$id = $_GET['id'];
$post = get_post($id);
if($post){
wp_send_json(array('post_title' => $post->post_title, 'post_content' => $post->post_content));
} else {
wp_send_json(array('error' => '1'));
}
wp_die();
}
and my jQuery:
( function( $ ) {
var $modalTrigger = $('.js-modal-trigger');
$modalTrigger.click( open_post_js );
function open_post_js(id) {
jQuery.ajax({
url: openpost.ajaxurl,
type: 'POST',
data: {
id: id,
action: 'open_post'
},
success: function( result ) {
alert( result['post_title'] );
}
})
}
} )( jQuery );
When I trigger the modal I get console error: Uncaught TypeError: Cannot read property 'type' of undefined. Also the alert result comes as "undefined".
Any help would be very appreciated :)
console.log(result);return? - cabrerahectoralert()for anything other than simple types (strings/numbers) - always useconsole.log- freedomn-m{error: "1"}- Kai