Receiving data in php via AJAX (inside Wordpress) - Hack The Tech - Latest News related to Computer and Technology

Hack The Tech - Latest News related to Computer and Technology

Get Daily Latest News related to Computer and Technology and hack the world.

Wednesday, September 28, 2022

Receiving data in php via AJAX (inside Wordpress)

I have a php function that needs to receive data via AJAX.

This is my code:

Javascript

<script type='text/javascript'>

    jQuery(document).ready(function() {

        jQuery("#fetch_data_button").click(function() {

            searchstring =  "My search text";
                                    
            jQuery.ajax({
                type: "POST",
                url: "admin-ajax.php",
                data: {         
                    action: 'fetch_data', 
                    _ajax_nonce: '<?php echo $nonce; ?>',
                    data: searchstring
                }
            });
            return false;                   
        });                                         
    });
    
</script>

php

add_action( 'wp_ajax_fetch_data', 'fetch_data_fn' );

function fetch_data_fn() {

    $searchstring = $_POST['searchstring'];
    // why is $searchstring empty ... ?

    die(); 
}

The issue is that the searchstring from the AJAX call is not received inside the php function (the received string is empty). Can anybody help me?



source https://stackoverflow.com/questions/73872046/receiving-data-in-php-via-ajax-inside-wordpress

No comments:

Post a Comment