Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading