Why Wordpress AJAX request returns the entire HTML

2019-08-30 02:38发布

I'm currently trying to check on a html form if the email given by the user is already in the database. So my PHP file have to return true if the get_user_by function works.

I have followed all Wordpress guidelines for AJAX request, and tested both AJAX methods (jQuery and vanilla JS).

The jQuery method finished in the error callback (with xhr.responseText corresponding to the entire current HTML page) whereas the vanilla JS method is returning in the success callback but always return 0.

First, I register my ajax js file and localize it to have the good admin-ajax.php url. Then I got my custom AJAX hook : wp_ajax_nopriv_get_user_by_email where get_user_by_email is the action data of the request.

<?php 
/* Security access : Hacker can't access php files here */
defined( 'ABSPATH' ) or die( 'No script kiddies please!' );

add_action( 'init', 'my_script_enqueuer' );
function my_script_enqueuer() {
   wp_register_script( "ajax_user_call", MY_PLUGIN_URL.'js/ajax_user_call.js', array('jquery'));
   wp_localize_script( 'ajax_user_call', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));        

   wp_enqueue_script( 'jquery' );
   wp_enqueue_script( 'ajax_user_call' );
}

if ( is_admin() ) {
    add_action( 'wp_ajax_nopriv_get_user_by_email', 'my_plugin_ajax_get_user_by_email' );

    function my_plugin_ajax_get_user_by_email() {
        my_plugin_log_me("Is there somebody ?");
        // get the mail parameter from URL
        $mail = $_REQUEST["mail"];
        if ( isset($_REQUEST["mail"]) && !empty($_REQUEST["mail"]) ) {
            $user = get_user_by('email', $_REQUEST["mail"]);
            if ($user == false) {
                echo -2;
                wp_die();
            }
            else {
                $response['first_name'] = $user->first_name;
                $response['last_name'] = $user->last_name;

                wp_send_json($response);
            }
        }
        else {
            echo -3;
            wp_die();
        }
    }

} ?>

Now I put the ajax_user_call.js :

jQuery(document).ready( function() {
  jQuery("#identificationEmailInput").blur( function() {
    jQuery.ajax({
       type: "post",
       dataType: "json",
       cache: false,
       url: myAjax.ajaxurl,
       data: { action: "get_user_by_email", mail: this.value },
       success: function(response, statut) {
          if(response == 0) {
            console.log("Veuillez rentrer une adresse mail du Club Savignac");
          }
          else {
            user = response;
            console.log("USER : " + user);
          }
       },
       error: function(xhr, textStatus, errorThrown) {
          console.log("AJAX Request failed");
          console.log(textStatus);
          console.log(errorThrown);
          console.log(xhr.responseText);
       }
    });
  });
})

The jQuery("#identificationEmailInput").value return a good email string. The url parameter myAjax.ajaxurl return the good path : "http://mysite.fr/wp-admin/admin-ajax.php".

I also tried to hardcode those parameters like this :

jQuery.post(
  "../wp-admin/admin-ajax.php",
  {
    action: 'get_user_by_email',
    mail: 'myprivate@mail.com'
  },
  function( response ) {
    console.log( response );
  }
);

And then, I also tried with Vanilla JS like it :

  var getJSON = function(url, param1, param2, successHandler, errorHandler) {
    var xhr = new XMLHttpRequest();
    xhr.open('post', url, true);
    var params = "action=" + param1 + "&mail=" + param2;
    console.log(params);
    xhr.responseType = 'json';

    xhr.onload = function() {
      var status = xhr.status;
      if (status == 200) {
        successHandler && successHandler(xhr.response);
      } else {
        errorHandler && errorHandler(status);
      }
    };
    xhr.send(params);
  };

  jQuery(document).ready( function() {
    jQuery("#identificationEmailInput").blur( function() {

      getJSON(myAjax.ajaxurl, 'get_user_by_email', jQuery("#identificationEmailInput").val(), function(data) {
          console.log('user object: ' + data);
        }, function(status) {
          console.log('Something went wrong.');
      });
    });
  })

But the data value always return 0.

Anyone have an idea about this tricky issue ? The most surprising thing is that it was working two days ago, and now it doesn’t anymore whereas I didn’t make any changes.

1条回答
Evening l夕情丶
2楼-- · 2019-08-30 02:48

Add this your plugin php file and check it .

 add_action('wp_ajax_nopriv_get_user_by_email', 'get_user_by_email');
    add_action('wp_ajax_get_user_by_email', 'get_user_by_email');

    function get_user_by_email(){

    $user_email  = $_POST['email'];
    //do some thing with the email

    die();
    }
查看更多
登录 后发表回答