Search code examples
phpjqueryajaxphpmailersummernote

Can't get value from Summernote textarea using Javascript AJAX send post data


I've been checking summernote API, and there is my code

<form id="mail">
  <input type="text" id="email">
  <textarea id="summernote"></textarea>
  <input type="submit">
</form>
$('#summernote').summernote({
  placeholder: 'your Message',
  tabsize: 2,
  height: 300
});

$('document').ready(function() {
  var messageData = $('#summernote').summernote('code');
  var email = $('#email').val();
  $(function() {
    $('#mail').submit(function(event) {
      event.preventDefault();
      $.ajax({
        url: 'sendmail.php',
        type: 'post',
        data: {
          'send_mail': 1,
          'to': email,
          'message': messageData,
        },
        success: function(response) {
          if (response == 'success') {
            //my success response
          } else if (response == 'error') {
            //my error response
          }
        }
      });
    });
  });
});

My problem is the message was successfully sent, but I didn't get that text area value, just an empty email. Please help.

Note: that I'm using phpMailer for sending email.


Solution

  • Change the code as below:

    1. Initialize the "summernote" inside the ready function.
    2. Fetch the summer note value inside the mail submit event

    Code as follows:

    $('document').ready(function(){
    
        $('#summernote').summernote({
           placeholder: 'your Message',
           tabsize: 2,
           height: 300
        });
    
    
         $(function(){
             $('#mail').submit(function(event){
    
               var messageData = $('#summernote').summernote('code');
               var email = $('#email').val();
    
              event.preventDefault();
              $.ajax({ 
               url: 'sendmail.php',
               type: 'post',
               data: { 
                'send_mail' : 1, 
                'to' : email,
                'message' : messageData, 
               }, 
               success: function(response){ 
                if(response == 'success'){ 
                //my success response
                 } else if (response == 'error'){
                //my error response
                 }
                }
               });
              });
         });
    });