0

I can't understand why I get always a null or undefined response while trying to pass an php error from registration form into ajax script. I work in a custom plugin to add login, registration and dashboard with the folder.

History : I create an ajax registration form , for each field I want create an error (if there are errors) and display it below the field.

I tried with basic var ($_POST), json_encode and wp_send_json_error. Each time I get a null or undefined response in console.log.

I know that my ajax script work because data $_POST are well pass. But I can't solve my issue or I don't understand what I do with Json !

I have read ajax doc and followed lot of docs about the same issue without results.

Currently basic thing doesn't work , could you help me ?

I use the same js/ajax file for login, registration and dashboard . Can there be a conflict ?

For now I want to test only the username

phpforajax.php:

wp_localize_script('ajax', 'wpAjax', array('ajaxUrl' => admin_url('admin-ajax.php')));
wp_enqueue_script('data-login', plugins_url('', LQUSER) . '/data/ajaxdata.js', array('jquery'), '1.0', true);

add_action('wp_ajax_add_new_user','add_new_user');
add_action('wp_ajax_nopriv_add_new_user','add_new_user');
function add_new_user(){
        

    if (isset($_POST['registr_submit']) && wp_verify_nonce($_POST['csrf'], 'csrf')) {
        
    // User data registration
    $username       = $_POST['username'];
    /*
    $firstname      = $_POST['firstname'];
    $lastname       = $_POST['lastname'];
    $email          = $_POST['email'];
    $newpassword    = $_POST['newpassword'];
    $confirmpassword= $_POST['confirmpassword'];
    $roleuser       = 'subscriber';
    verify only username
    */
if(empty($username)){
    $data = [];
    $data['success'] = false;
    $data['message'] = 'Username is required';

    echo json_encode($return);
}
// before to use wp_send_json_error I must find my mistake or my forgetting
//if i use wp_die(); the form isn't pass to ajax
}

my_registration_form.php

    <form class="registr-form" action="" method="POST" id="my_registration_form">
                <input type="text" name="username" id="username" placeholder="Votre nom d'utilisateur" autocomplete="username"/>
                <span id="error-emp-name"></span>
    <input type="hidden" name="csrf" value="<?php echo wp_create_nonce('csrf'); ?>"/>
    <input type="submit" id="registr_submit" name="registr_submit" class="submit-registr-btn" value="Je valide">   
    </form>

ajaxdata.js:

$(function(){
            $('#registr_submit').on('click', function(e){
                e.preventDefault();
                $.ajax({ 
                    url     : wpAjax.ajaxUrl,
                    data    : {action:'add_new_user'},
                    type    : 'POST',
                    dataType: 'json',
                    success : function(response){
                        var data = $.parseJSON(response);
                        // below work and display input 
                        console.log(username);
                        // below doesn't work 
                        if(data.success == false){
                            console.log(response.message); //must display : Username is required.
                        
                  
                        }
                    }
                });
    
            });
5
  • When you say "because data $_POST are well pass" what do you mean? Can you rephrase/translate using different words? All the official jQuery docs at jquery.com use method: "POST", yet you have type: "POST" what's the reason for this? I also see you used the old admin ajax api, instead of making AJAX requests to the newer REST API – Tom J Nowell Feb 25 at 18:28
  • 2
    I also see that your ajax handler checks if registr_submit is set, yet in your JS you never send registr_submit, the only thing that's being sent is the action with the value add_new_user. The data is not passed because there is no code to pass it! Your data object does not have any of the information you are trying to use. Can you fix the indentation of your code? – Tom J Nowell Feb 25 at 18:32
  • You should call wp_die() at the end of your AJAX callback. Otherwise, the JSON body will become invalid. And in that callback, $return is not defined? Also, you already set the dataType to json, so jQuery will automatically evaluate the response as JSON and pass an object to your success callback, so no need for that parseJSON() which won't work on objects, anyway. – Sally CJ Feb 26 at 1:06
  • Tom : I reread again Wordpress Ajax doc and I don't see that i used old ajax api. Also I understand the good reason to use method:'POST' but then why type:'POST' works ? Sally : You were right for wp_die() ,but finally I delete it beacause I use wp_send_json_ (error and success) that add automatically wp_die at the end. – imagIne Feb 26 at 14:35
  • @imagIne you should actually tag the users you're replying to so they get notified of your replies.. :) And yes, I would also use the wp_send_json_ functions, but I was just saying, you need to stop the script execution to prevent WordPress (and other code) from echoing something after your AJAX callback is called. – Sally CJ Feb 26 at 17:56
0

thank you so much Tom and Sally. My issue was indeed to not send registr_submit to. In reallity I didn't well understand ajax, now it's good. I thought that serialize string of inputs form was enough to get the submit value. Mainly I convinced that php send to jquery/ajax while it is obviously the opposite. So, in order :

ajaxdata.js:

$(function(){
      $('#registr_submit').on('click', function(e){
                e.preventDefault();
                var userdata = $('#my_registration_form').serialize();
            userdata += '&action=add_new_user&regsubmit=registr_submit';
        
            var username = $('#username').val();
                $.ajax({ 
                    url     : wpAjax.ajaxUrl,
                    data    : userdata,
                    type    : 'POST',
                    dataType: 'json',
                    success : function(response){
                        if(username == ''){
                           if(response.success == false) {
                            
                              $('#error-emp-name').html(response.data);
                           }
                        }
                        else{
                            if(response.success == true) {
                                $('#error-emp-name').html('Correcte');
                            }
                        }
                        
                  
                   }
               }
          });
    
      });

phpforajax.php:

wp_localize_script('ajax', 'wpAjax', array('ajaxUrl' => admin_url('admin-ajax.php')));
wp_enqueue_script('data-login', plugins_url('', LQUSER) . '/data/ajaxdata.js', array('jquery'), '1.0', true);

add_action('wp_ajax_add_new_user','add_new_user');
add_action('wp_ajax_nopriv_add_new_user','add_new_user');
function add_new_user(){
        

    function add_new_user(){
    global $wpdb;       

    if (isset($_POST['regsubmit']) && wp_verify_nonce($_POST['csrf'], 'csrf')) {
        
    $username       = $_POST['username'];
    $firstname      = $_POST['firstname'];
    $lastname       = $_POST['lastname'];
    $email          = $_POST['email'];
    $newpassword    = $_POST['newpassword'];
    $confirmpassword= $_POST['confirmpassword'];
    $roleuser       = 'subscriber';
    
    if (empty($username)) {     
        wp_send_json_error('Username is required'); 
    }else{
        wp_send_json_success('Ok');
    }
    
}
2
  • In your $.ajax() args, you forgot to use data: userdata.. :) – Sally CJ Feb 26 at 18:02
  • 1
    you are right, bad copy and paste, I correct. – imagIne Feb 27 at 9:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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