Having Trouble using AJAX with jquery in WordPress FrontEnd

Hello I am developing a plugin for Word Press,
Admin area is all ok but i want to use AJAX in front end to send some data to my server.
I am using AJAX in jquery like

jQuery.AJAX({
My code…..
})

Read More

But its not working, As the same code approach working well at admin side.
the file where I post my data is in my plugin directory
I am attaching the code please check what am i doing wrong thanks

This is the front end file

jQuery(document).ready(function(){
         
           var url= jQuery('#url').val();
            jQuery.ajax({
                type:"POST",
                URL:url,
                data:{
                    data:'azam'
                },
                success:function(data)
                {
 
                }
 
            })
 
        });

Here is my php file

function hello($a)
{
    $a = $_POST['data'];
    echo $a;

}
add_action('wp_ajax_hello', 'hello');
add_action('wp_ajax_nopriv_hello', 'hello');

Please dont give me online links caz i search whole internet already but i cant understand how it works. please help

Related posts

2 comments

  1. If u use wp_enqueue_script, i suggest u to add this function in your main php file.

    function plugin_ajax_articles()
    {
       wp_enqueue_script( "your_js_file", get_stylesheet_directory_uri() . '/your_js_file.js', array('jquery'), "1.0.0", true );
    
       wp_localize_script( 'your_js_file', 'url', admin_url( 'admin-ajax.php' ) );
    }
    add_action("init", "plugin_ajax_articles");
    

    Then in ur js file, URl will work.
    Don’t forget to add a “die();” at the end of your php function.

    If u have time, read this article => Tuto Ajax WordPress

    I hope that help u 🙂

  2. Your code looks mostly correct but here are my findings:

    1. In the end of your hello function add die();

    2. Are you using correct admin ajax url?

    add this to your functions.php to output admin ajax url.

    function ajaxurl() {
    ?>
    <script type="text/javascript">
    var AjaxUrl = "<?php echo admin_url('admin-ajax.php'); ?>";
    </script>
    <?php
    }
    
    add_action('wp_head','ajaxurl');
    
    1. you need to add action parameter into your data

          .ajax({
              type:"POST",
              URL:AjaxUrl, // is this url correct? it should be admin ajax url
              data:{
                  action:'hello',
                  data:'azam'
              },
      

Comments are closed.