javascript - 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?

Answer

Solution:

well your main problem is that none of the data you are sending via ajax is named "searchstring". You have a property named "data" that holds the value of a variable named "searchstring". so you'd want to test $_POST['data'] in your PHP instead.

I am also a little worroed about you trying to use PHP in your javascript code. It's usually a red flag, and there is likely a better way of doing what you are trying to accomplish there.

Source