[wp-hackers] Why is this ajax POST failing?

Andrew Bartel andrew.bartel at gmail.com
Mon Nov 11 21:50:36 UTC 2013


Hook it onto wp_enqueue_scripts instead of init.

You don't need to enqueue jquery, you already have it as a dependency.

Localize after enqueueing.

You're not passing a nonce so you're nonce check will fail.

-Andrew


On Mon, Nov 11, 2013 at 1:47 PM, BenderisGreat <greglancaster71 at gmail.com>wrote:

> *Jquery / JS File:*
>
> jQuery( document ).ready( function( $ ) {
>         $( '#post_like').click( function() {
>
>          var like_user_id = $( this ).attr('data-id')
>          var like_post_id = $( this ).attr('data-user')
>
> var data = {
>         'action': 'my_post_like_action',
>         'like_post_id': like_post_id,
>         'like_user_id': like_user_id
> }
>
> $.ajax({
>         type: 'post',
>         url: myAjax.ajaxurl,
>         data: 'data',
>         success: function ( response ) {
>         if(response.type == "success") {
>
>         alert( 'Success!' );
>     }
>             else {
>         alert( 'Fail!' );
>
>         }
>         }
> });
>   });
> });
>
>
> *Enqueue Script:*
>
> add_action( 'init', 'my_script_enqueuer' );
>
> function my_script_enqueuer() {
>    wp_register_script( "my_post_like_action",
> WP_PLUGIN_URL.'/gogonow/js/post_like.js', array('jquery') );
>    wp_localize_script( 'my_post_like_action', 'myAjax', array( 'ajaxurl' =>
> admin_url( 'admin-ajax.php' )));
>
>    wp_enqueue_script( 'jquery' );
>    wp_enqueue_script( 'my_post_like_action' );
>
> }
>
>
> *the php function:*
>
> add_action('wp_ajax_my_post_like_action', 'my_post_like_action');
> add_action('wp_ajax_nopriv_my_post_like_action', 'my_post_like_action');
>
> function my_post_like_action() {
>
> //      if ( ! wp_verify_nonce( $nonce, 'ajax-nonce' ) )
> //        die ( 'Busted!');
>
>                 $post_id = $_POST['like_post_id'];
>                 $user_id = $_POST['like_user_id'];
>
>                 $result = update_user_meta($user_id, 'liked_by', $user_id);
>                 $response = array( 'success' => true );
>
>         wp_send_json_success($response);
>
> }
>
>
> *the button: *
>
>         <button type="button" id="post_like"
> data-id="<?php echo the_ID() ?>"  data-user="<?php echo
> get_current_user_id(); ?>" class="btn btn-success">Like This Post</button>
>
>
>
>
>
>
> --
> View this message in context:
> http://wordpress-hackers.1065353.n5.nabble.com/Why-is-this-ajax-POST-failing-tp42791.html
> Sent from the Wordpress Hackers mailing list archive at Nabble.com.
> _______________________________________________
> wp-hackers mailing list
> wp-hackers at lists.automattic.com
> http://lists.automattic.com/mailman/listinfo/wp-hackers
>


More information about the wp-hackers mailing list