简体   繁体   中英

Why isn't my PHP code returning json data to my Ajax call?

I'm testing using AJAX to login to Wordpress. But my PHP code is not returning data to my ajax script.

I'm wondering if I'm missing something.

My template looks like this

// This code is at the top of my template

function authenticate($username, $password) {
    global $user;

    $data = array();
    $data['user_login'] = $username;
    $data['user_password'] =  $password;
    $data['remember'] = false;

    $user = wp_signon( $data, false );

    if ( is_wp_error($user) ) {
        $result = array('login' => false, 'error' => $user->get_error_message());
    }
    if ( !is_wp_error($user) ) {
        $result = array('login' => true);
    }

    echo json_encode($result);
}

if (isset($_REQUEST['user_login'])) {
    authenticate($_REQUEST['user_login'], $_REQUEST['user_password']);
}

(...) // My HTML starts here

<form name="loginform" action="<?= $_SERVER['REQUEST_URI'] ?>" method="post">
(...)
</form>

And this is my JS code

$('.login-button').on('click', function(e){
    e.preventDefault();

    var $form       = $('form');
    var form_action = $form.attr('action');
    var form_data   = {
        'user_login': $form.find('.user_login').val(),
        'user_password': $form.find('.user_psw').val(),
    };

    $.ajax({
        type: "POST",
        url: form_action,
        data: form_data,
        dataType : 'json',
        success: function(result){
            cl(result); // <-- This is not outputting anything
        }
    });
});

I'm probably just missing something fundamental here, but not sure what.

 if (isset($_REQUEST['user_login'])) { authenticate($_REQUEST['user_login'], $_REQUEST['user_password']); } (...) // My HTML starts here 

You are outputting your JSON, but you are also outputting your HTML immediately afterwards. That makes the JSON invalid. This should have been warned about by one of the arguments that would have been passed to the error function, had you had one.

You need to output the HTML only if you aren't outputting the JSON.

Putting exit() inside the if statement would do the job (although I'd refactor things to have two distinct files to handle the different kinds of output and include different ones based on the if … or go a step further and use a full MVC framework).

You have also forgotten to set header("Content-Type: application/json"); when you are outputting JSON.

You should be adding AJAX callbacks to functions.php , not a page template.

function so_34356392_ajax_auth() {
    if (isset($_REQUEST['user_login'])) {
        authenticate($_REQUEST['user_login'], $_REQUEST['user_password']);
    }
}
add_action( 'wp_ajax_so_34356392_auth', 'so_34356392_ajax_auth' );
add_action( 'wp_ajax_nopriv_so_34356392_auth', 'so_34356392_ajax_auth' );


function authenticate($username, $password) {
    global $user;

    $data = array();
    $data['user_login'] = $username;
    $data['user_password'] =  $password;
    $data['remember'] = false;

    $user = wp_signon( $data, false );

    if ( is_wp_error($user) ) {
        $result = array('login' => false, 'error' => $user->get_error_message());
    }
    if ( !is_wp_error($user) ) {
        $result = array('login' => true);
    }

    echo json_encode($result);
    wp_die();  // this is required to terminate immediately and return a proper response
}

And then your AJAX function would change to:

var form_data   = {
    'action': 'so_34356392_auth',  // Target the callback in functions.php
    'user_login': $form.find('.user_login').val(),
    'user_password': $form.find('.user_psw').val(),
};

$.ajax({
    type: "POST",
    url: form_action,
    data: form_data,
    dataType : 'json',
    success: function(result){
        cl(result);
    },
    error: function() {
        cl('Cannot retrieve data.');
    }
});

Read more about using AJAX in WordPress, in the Codex .

if (isset($_REQUEST['user_login'])) {
    // |-- you need an echo
    echo authenticate($_REQUEST['user_login'], $_REQUEST['user_password']);
    exit();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM