Problem with custom plugin using AJAX to pull info from php file

Question

I’m extremely frustrated over what I expected to be an easy task.

I have a wordpress plugin that I’m looking to do the following (with woocommerce) —

  • Customer adds a product to cart.
  • Javascript was added to footer on load using the plugin (wp_footer) to run a simple ajax request to myfile.php once this happens.
  • I get the response from myfile.php, then i could manipulate that data as needed.

When i do this my normal way, i get a file not found, but i can access it directly.

I’ve done this many times in the past, without wordpress, with no issue. Now i’m seeing things about needing to use admin-ajax as some sort of intemediary?? compounding that, all examples have things about adding in add’l JS files, which I’m not looking to do. I just want the JS added to the footer to look at a php file, then use that php files content elsewhere.

I’ve stripped down my code below. It’s not exactly my original intent, i just plan on moving the sccrirpt in myfile.php to the my_action function. It returns a 400 error after many different attempts. can anyone point me in the right direction?

thanks

add_action( 'wp_footer', 'my_action_javascript' ); 
function my_action_javascript() { ?>
    <script type="text/javascript" >
    jQuery(document).ready(function($) {
        var data = {
            'action': 'my_action'
        };
        jQuery.post('/wp-admin/admin-ajax.php', data, function(response) {
            alert('Got this from the server: ' + response);
        });
    });
    </script> 
<?php }

add_action( 'wp_ajax_nopriv_my_action', 'my_action' );
function my_action() {
    echo "ok";
    wp_die();
}
?>'''

This was my original code. Straightforward, I would very much like to know why something so simple doesn't work. Returned 404 a number of methods.

```function action_woocommerce_cart_updated(  ) { ?>
    <script type="text/javascript">
        (function($){ 
            $( document.body ).on( 'added_to_cart', function(){
                alert('updated');
                $.ajax({
                    url : '<?php echo get_site_url();?>/wp-content/plugins/handle-multiple-items/return-items.php',
                    type : 'POST',
                    data : {},
                    success : function(data) {              
                        console.log(data); // 'data' used for additional things.
                    },
                    error : function(request,error)
                    {
                        alert('An error occurred.');
                    }
                });
                
            });
        })(jQuery);
    </script>
<?php }; 

add_action('wp_footer', 'action_woocommerce_cart_updated'); ?>'''
0
bm5050 3 months 0 Answers 19 views 0

Leave an answer