I want to send a ajax request in wordpress which tracks my clicks. For now i have added this in my functions file :

add_action('init', 'my_script_enqueuer');

  function my_script_enqueuer() {
    wp_register_script("history_script", get_template_directory_uri() . '/js/history_script.js', array('jquery'));
    wp_localize_script('history_script', 'myAjax', array('ajaxurl' => get_template_directory_uri().'/functions.php'));
    wp_enqueue_script('jquery');
    wp_enqueue_script('history_script');
  }

  add_action("wp_ajax_history_trace", "history_trace");

  function history_trace() {
      echo 'fasfasgasgas'; die;
}

and in my js file :

jQuery(document).ready( function() {

   jQuery("#searchsubmit").click( function() { 
      jQuery.ajax({
         type : "post",
         dataType : "json",
         url : myAjax.ajaxurl,
         data : {action: "history_trace"},
         success: function(response) {
            if(response.type == "success") {
               alert('success')
            }
            else {
               alert("false")
            }
         }
      })   

   })

})

But when i see my console the rquest appears in red color and there is no response. Please Help!!

your ajax url is wrong i think. ajax link should be admin_url( 'admin-ajax.php' ). That means

wp_localize_script('history_script', 'myAjax', array('ajaxurl' => get_template_directory_uri().'/functions.php'));

will be this

wp_localize_script('history_script', 'myAjax', array('ajaxurl' => admin_url( 'admin-ajax.php' ));

Your Answer

 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.