1

I have created an AJAX function in Wordpress. The function is called on form submission. The function is run, but it is not receiving any of the form data that I have submitted. What am I missing?

PHP Function

I have added the PHP function here, which is called successfully via AJAX. This form creates a new user successfully, but only when I create the variables manually (eg. see $new_user_data['user_login'] = 'This Text Works';). For some reason, the $_POST data isn't coming through to the function.

add_action("wp_ajax_register_user", __NAMESPACE__ . "\\register_user");
add_action("wp_ajax_nopriv_register_user", __NAMESPACE__ . "\\register_user");

function register_user() {

  // NONCE VERIFICATION
  if ( !wp_verify_nonce( $_REQUEST['nonce'], "rtr_register_nonce")) {
  exit("Oops! This is embarassing!");

  }

 // Get all post data for the user.

 $new_user_data = array();
 $new_user_data['first_name'] = sanitize_text_field($_POST['first-name']);
 $new_user_data['last_name'] = sanitize_text_field($_POST['last-name']);
 $new_user_data['user_email'] = $_POST['email'];
 $new_user_data['user_pass'] = sanitize_text_field($_POST['password']);

 $new_user_data['user_login'] = 'This Text Works';
 $new_user_data['role'] = 'subscriber';

 // Create the User
 $registered_user = wp_insert_user( $new_user_data );


 $result['user'] = $registered_user;

 // AJAX CHECK
 if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
  $result = json_encode($result);
  echo $result;

} else {

  header("Location: ".$_SERVER["HTTP_REFERER"]);

}

die();


}

JQuery

function registerUser(){

      var nonce = $('#regForm').attr("data-nonce");
      var formData = $('#regForm').serialize();

      $.ajax({
        url: rtr_register_user.ajaxUrl,
        type: 'post',
        dataType: 'json',
        data : {action: 'register_user', nonce: nonce, formData: formData},
        success: function (response) {
          console.log(response);
          $('#regForm').html('Your form has been submitted successfully');
        },


      });

    }

    function nextPrev(n) {
      // This function will figure out which tab to display
      var x = document.getElementsByClassName("form-tab");
      // Exit the function if any field in the current tab is invalid:
      if (n === 1 && !validateForm()) {
        return false;
      }
      // Hide the current tab:
      x[currentTab].style.display = "none";
      // Increase or decrease the current tab by 1:
      currentTab = currentTab + n;
      // if you have reached the end of the form... :
      if (currentTab >= x.length) {
        //...the form gets submitted:
        //document.getElementById("regForm").submit();
        registerUser();
        return false;
      }
      // Otherwise, display the correct tab:
      showTab(currentTab);
    }

    $('#nextBtn').click(function () {
      nextPrev(1);
    });

    $('#prevBtn').click(function () {
      nextPrev(-1);
    });

Form

<?php

$nonce = wp_create_nonce("rtr_register_nonce");
$link = admin_url('admin-ajax.php?action=register_user&nonce='.$nonce);

?>

<form id="regForm" <?php echo 'data-nonce="' . $nonce . '"'; ?>   action="<?php echo $link; ?>" method="post" enctype="multipart/form-data">>

<div class="my-3 text-center">
<span class="form-step">1</span>
<span class="form-step">2</span>
</div>
<div class="form-tab">
<p><input name="first-name" placeholder="First Name" oninput="this.className = ''"></p>
<p><input name="last-name" placeholder="Last Name" oninput="this.className = ''"></p>
<p><input name="dob" type="date" oninput="this.className = ''"></p>
</div>

<div class="form-tab">
<p><input name="email" type="email" placeholder="Email" oninput="this.className = ''"></p>
<p><input name="password" type="password" placeholder="Password" oninput="this.className = ''"></p>
</div>

<div style="overflow:auto;">
<div style="float:right;">
<button type="button" class="btn btn-brand" id="prevBtn">Previous</button>
<button type="button" class="btn btn-brand" id="nextBtn">Next</button>
</div>
</div>

</form>
12
  • Is ajax requested without an error? i doubt your ajax call was not triggerred Commented Jan 2, 2018 at 12:04
  • can you var_dump the content of $_POST and check what data is present there? Commented Jan 2, 2018 at 12:04
  • Ajax doesn't give me any errors @Thamaraiselvam Commented Jan 2, 2018 at 12:05
  • If I var_dump $_POST it gives me a 400 error in the console and nothing runs @flynorc - I'm actually writing that to the console as opposed to var_dump Commented Jan 2, 2018 at 12:05
  • Can you post here the request params of the Ajax? Commented Jan 2, 2018 at 12:06

4 Answers 4

1

Seems you are not triggering registerUser() check following script works fine for me

jQuery(document).ready(function($) {
    jQuery('body').on('click', '#nextBtn', function() {
            registerUser();
        });
});

function registerUser(){

    var nonce = jQuery('#regForm').attr("data-nonce");
    var formData = jQuery('#regForm').serialize();

    jQuery.ajax({
        url: ajaxurl,
        type: 'post',
        dataType: 'json',
        data : {action: 'register_user', nonce: nonce, formData: formData},
        success: function (response) {
          console.log(response);
          $('#regForm').html('Your form has been submitted successfully');
        },

    });
}
Sign up to request clarification or add additional context in comments.

6 Comments

Ok I have it fixed now. Seems it was a combination of things. The AJAX was being called but the form wasn't being submitted. Thanks for helping to troubleshoot this.
you cannot do both at a time. do a form submit or ajax. anyway glad you found the problem.
I have posted a more complete answer below @GerritLuimstra. I'm happy to give credit to Thamaraiselvam for their input, but it is not complete. Although I'm not a big Stack Overflow user, so if this is not the way I should do things, then I'd be happy to mark it as the answer.
@Mando, as you mentioned your answer, seems bit complicated, I took all your code and created a new plugin to check your script. at least do an upvote;), that would motivate me. anyway, you found your way. happy coding.
@Thamaraiselvam I did upvote your answer. Not sure if it worked? The up arrow went orange.
|
0

add method="post" to your 'form' - 'get' is the default https://stackoverflow.com%2Fquestions%2F2314401%2Fwhat-is-the-default-form-http-method&usg=AOvVaw1dKc3hW4K6r5SwQurLztBw

8 Comments

OP is sending request using ajax
not shown in the code. From what is shown, there is not complete flow.
From what is shown, there is not complete flow Ya, we don't have any idea how OP is calling registerUser() method
yet OP IS calling the ajax.php from the form action........ (seems fixing the form method or the JS call is the answer....
but, where does it call nextPrev?
|
0

The "user_login" is a username of the user so probably it doesn't accepts space too.

See also WP Insert Post

Please try passing some username such as "custom_user" and see the result.

Hope this might work.

2 Comments

Sorry, I am actually using a single string there - 'test' for example. The WP Insert Post is working fine. It's the $_POST data that isn't coming through to the function.
Oh then you have to see the Ajax parameters and response. Try debugging through var_dump( $results ) also and look to the response.
0

Ok it was a bit of help from everyone here. But yes, I was calling the AJAX correctly, but not actually submitting the form. I added a .on(submit) to the form and then added a listener to the form to perform the AJAX call on submit. Here's the amendments below.

function nextPrev(n) {

    var x = document.getElementsByClassName("form-tab");

        if (n === 1 && !validateForm()) {
          return false;
        }

        x[currentTab].style.display = "none";

        currentTab = currentTab + n;

        if (currentTab >= x.length) {

        // ADDED THIS SUBMIT() HERE
          document.getElementById("regForm").submit();
          return false;
        }
        // Otherwise, display the correct tab:
        showTab(currentTab);
      }


      // ADDED AN EVENT LISTENER TO TRIGGER THE AJAX CALL HERE
      $('#regForm').on('submit', function () {

          var nonce = $('#regForm').attr("data-nonce");
          var formData = $('#regForm').serialize();

          $.ajax({
            url: rtr_register_user.ajaxUrl,
            type: 'post',
            dataType: 'json',
            data: {
              action: 'register_user',
              nonce: nonce,
              formData: formData
            },
            success: function (response) {
              console.log(response);
              $('#regForm').html('Your form has been submitted successfully');
            },


          });

        });

3 Comments

Actually, this works via the post method, but it actually isn't using AJAX. That is, it's still reloading the page??
Add e.preventDefault(); to your on submit function
And don't forget to add the e parameter to the function on the top as a parameter ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.