1

I have a form with AJAX Submit. I am getting the value of fields as null.

jQuery('#DownloadForm').submit(ajaxSubmit);

 function ajaxSubmit() {
    var DownloadForm = jQuery(this).serialize();
    jQuery.ajax({
      type:    "POST",
      url:     aj_ajax_demo.ajax_url,
       data : {
                action : 'set_lead_cookie_and_mail',  // Note that this is part of the add_action() call.
                nonce : aj_ajax_demo.aj_demo_nonce,  // Note that 'aj_demo_nonce' is from the wp_localize_script() call.
                form_data : DownloadForm
            },
      success: function(response) {
          console.log(response);

      }
    });
    return false;
  }

And this is how I am fetching the data.

add_action( 'wp_ajax_nopriv_set_lead_cookie_and_mail', 'mail_and_cookie_function' );
add_action( 'wp_ajax_set_lead_cookie_and_mail', 'mail_and_cookie_function' ); 

function mail_and_cookie_function() {
    check_ajax_referer( 'aj-demo-nonce', 'nonce' );  // This function will die if nonce is not correct.

    $name =  sanitize_text_field($_POST["wpcf-lead-name"]);
    $email =  sanitize_text_field($_POST["wpcf-lead-email"]);
    $number =  sanitize_text_field($_POST["wpcf-lead-number"]);
    $class =  $_POST["wpcf-class"];
    $category =  sanitize_text_field($_POST["hidden_category"]);

    if(!$_COOKIE[$category]) {      
        setcookie($category, "1", time()+2592000);
        wp_send_json($class);
    }
    wp_die();
}

My response header is sending all the data correctly.

I am getting null as the response. I expect to get the value of the forms submitted.

1

You should rename your function to set_lead_cookie_and_mail and change it in the add_action() as well.
It looks like your action set_lead_cookie_and_mail in your ajax call is never reached, does it even exist?

| improve this answer | |
1

So I found the answer to the question. Using parse_str($_POST['form_data'], $form_data); in my function allows me to call all the field values as $name = $form_data["wpcf-lead-name"];

Now my new function looks like this.

function mail_and_cookie_function() {
    check_ajax_referer( 'aj-demo-nonce', 'nonce' );  
    parse_str($_POST['form_data'], $form_data); // This is the new added line
    $name =  $form_data["wpcf-lead-name"];  // This is how you call the field.
    $email =  $form_data['wpcf-lead-email'];
    $number = $form_data["wpcf-lead-number"];
    $class =  $form_data["wpcf-class"];
    $category =  $form_data["hidden_category"];

    if(!$_COOKIE[$category]) {      
        setcookie($category, "1", time()+2592000);
        wp_send_json("redirecting");
    }
    wp_die();
}

| improve this answer | |

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.