0

Im trying to open Wordpress posts in a modal popup by following this guide : https://premium.wpmudev.org/blog/load-posts-ajax/

However when I try I get an error saying : Uncaught ReferenceError: modalpost is not defined

I have this code in my functions file so far :

wp_localize_script( 'modal-post', 'modalpost', array(
    'ajaxurl' => admin_url( 'modal-post.php' )
));

And this code in my js file :

(function($) {
$(document).on( 'click', '.itemtoshow', function( event ) {
event.preventDefault();
$.ajax({
    url: modalpost.ajaxurl,
    type: 'post',
    data: {
        action: 'modal-post'
    },
    success: function( result ) {
        alert( result );
    }
})
});
})(jQuery);

Any ideas what Im doing wrong ?

Many thanks in advance,

Scott

1 Answer 1

2

You have make some changes in your code like

wp_localize_script( 'modal_post', 'modalpost', array(
'ajaxurl' => admin_url( 'modal-post.php' )
));

to

wp_localize_script( 'modal-post', 'modalpost', array(
 'ajaxurl' => admin_url( 'admin-ajax.php' )
));

Then in your jQuery

(function($) {
  $(document).on( 'click', '.itemtoshow', function( event ) {
    event.preventDefault();
    $.ajax({
      url: modalpost.ajaxurl,
      type: 'post',
      data: {
        //action: 'modal-post' change function name here
        action: 'modal_post'
      },
     success: function( result ) {
     alert( result );
   }
 })
});
})(jQuery);

Now code response function in your plugin or functions.php file like

// Add hooks for handle ajax request
add_action( 'wp_ajax_nopriv_modal_post', 'model_post' );
add_action( 'wp_ajax_ajax_modal_post', 'model_post' );

function model_post(){
  // Your modal code goes here
  // echo your modal code and then exit / die
  die();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.