为什么Wordpress AJAX请求返回整个HTML页面而不是json结果? [英] Why Wordpress AJAX request returns the entire HTML page instead of json result?

查看:60
本文介绍了为什么Wordpress AJAX请求返回整个HTML页面而不是json结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试检查html表单,如果用户提供的电子邮件已经存在于数据库中.因此,如果get_user_by函数正常工作,我的PHP文件必须返回true.

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.

对于 AJAX请求,我已遵循所有 Wordpress指南,并测试了两种AJAX方法( jQuery和Vanilla JS ).

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

jQuery方法在错误回调中完成(xhr.responseText对应于整个当前HTML页面),而香草JS方法在成功回调中返回,但始终返回0.

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.

首先,我注册我的ajax js文件并将其本地化以具有良好的admin-ajax.php网址.然后,我得到了自定义的AJAX挂钩:wp_ajax_nopriv_get_user_by_email,其中get_user_by_email是请求的操作数据.

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();
        }
    }

} ?>

现在我放ajax_user_call.js:

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);
       }
    });
  });
})

jQuery(#identificationEmailInput").value返回一个好的电子邮件字符串.网址参数myAjax.ajaxurl返回正确的路径:" http://mysite.fr/wp-admin/admin-ajax.php ".

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 );
  }
);

然后,我也尝试使用Vanilla JS:

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.');
      });
    });
  })

但是数据值总是返回0.

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.

推荐答案

将其添加到您的插件php文件中并进行检查.

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();
    }

这篇关于为什么Wordpress AJAX请求返回整个HTML页面而不是json结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆