Home > Mobile >  How do I get a message in a div box instead of the alert box with ajax success?
How do I get a message in a div box instead of the alert box with ajax success?

Time:09-11

I'm trying to create error validation handling for my custom form. What I want to do is get the error messages in a div instead of the browser alert box but I'm new to all of this and have no idea how to do it. I tried to do some research but found nothing useful for my case.

Basically my form works and shows error or success messages correctly, but I don't want to display them in the alert box, but in a dedicated div. Thanks for any answers, I appreciate any help.

So here's what I have:

My section which contains all the various messages error

<div >
   <!-- Here are all my error messages that are printed with the wc_print_notices(); function -->
</div>

My Script

jQuery(document).ready(function($) {
    
    $('.mts-edit-account').on('submit', function(e) { 
        e.preventDefault(); 

    //Ajax function
    jQuery.ajax({
      
      type: "post",
      data: jQuery(".mts-edit-account").serialize(),
      url: "wp-admin/admin-ajax.php",
      success : function( response ) {
        alert( response );
      }

    });
    });
});

My function

function save_account_details() {

  if (trim($_POST['account_first_name']) == '') {
    $msg = wc_print_notices();
    $response = $msg;
  } else {
    $response = "Settings Saved!";
  }

  // Don't forget to exit at the end of processing
  echo json_encode($response);
  exit();

}

CodePudding user response:

If u wanna show in exist class then choose element by document.querySelector(".className").innerHtml = response.textFromResponse or u can do like below

 Query(document).ready(function($) {
    $('.mts-edit-account').on('submit', function(e) { 
        e.preventDefault(); 

    //Ajax function
    jQuery.ajax({
      
      type: "post",
      data: jQuery(".mts-edit-account").serialize(),
      url: "wp-admin/admin-ajax.php",
      success : function( response ) {
        alert( response );
        const uiDivElement = document.createElement("DIV");
        uiDivElement.innerHTML = response.textFromResponse
        document.appendChild(uiDivElement)
      }

    });
    });
    });
  • Related