Home > Mobile >  How to pass AJAX file data output to html div?
How to pass AJAX file data output to html div?

Time:12-26

How to pass data from admin-ajax.php to #featured-image div?

CodePudding user response:

I've added this to script, and it solved the problem.

$('#featured-image').html(data);

CodePudding user response:

Your simplified version is lacking a few items that should be used in WordPress.

  1. You shouldn't be using the ajaxurl in the script, you should be using wp_localize_script in your functions.php. Also, unless you only want logged in users to experience this ajax script, you need the nopriv action.

Functions.php

Add this in the function that you're enqueueing your jQuery file.

wp_localize_script(
    'your-script-handle', // use the handle of your enqueued script.
    'my_ajax', // object name.
    array(
        'ajaxurl'   => admin_url( 'admin-ajax.php' ),
        'ajaxnonce' => wp_create_nonce( 'ajax_validation' ),
    )
);

Also add to functions.php your ajax php handler. Notice I've added nonce verification to your php so that this function has security. Sanitize your data as well.

function our_tutorial() {
    check_ajax_referer( 'ajax_validation', 'nonce' );
    if ( isset( $_POST['php_test'] ) ) {
        $testing = sanitize_text_field( wp_unslash( $_POST['php_test'] ) );
        $post_id = url_to_postid( $testing );
        echo get_the_post_thumbnail( $post_id );
    }
    die();
}
add_action( 'wp_ajax_php_tutorial', 'our_tutorial' );
add_action( 'wp_ajax_nopriv_php_tutorial', 'our_tutorial' );

Your jQuery - Notice that .ready and .mouseover have been replaced.

To return your data, simply target your DIV.

let hrefValue;
jQuery(
    function($) {
        $( '#bio-box' ).find( 'a' ).on(
            'mouseenter',
            function() {
                hrefValue = ($( this ).attr( 'href' ));
                $.ajax(
                    {
                        url: my_ajax.ajaxurl,
                        type: 'POST',
                        dataType: 'HTML',
                        data: {
                            'action': 'php_tutorial',
                            'php_test': hrefValue,
                            'nonce' : my_ajax.ajaxnonce,
                        },
                        success: function(data){
                            $( '#featured-image' ).html( data );
                        }
                    }
                );
            }
        );
    }
);
  • Related