Submit contact form with success/fail alert on same page

I have contact form with html, php, js and ajax as you see in codes. After form fill successfully and click submit, the email was sent successfully. But the success message can’t seen on the same page. The alert is seen to redirected page in one line. I don’t want to redirect to show alert. The alert must be on the same page with contact form. Here is the codes. Could you help me what I miss or do wrongly. Thank you for your help.

– HTML CODE –

<div class="container">
 <div class="row">
  <div class="col-xl-8 offset-xl-2">
   <h1>CONTACT FORM</h1><hr>
   <p class="lead">By filling out the contact form; You may have information about us and current news.</p>
   <form id="contact-form" method="post" action="contact.php" role="form" novalidate="true">
   <div class="messages"></div>
   <div class="controls">
    <div class="row">
     <div class="col-lg-6">
      <div class="form-group">
        <label for="form_name">Full Name *</label>
        <input id="form_name" type="text" name="name" class="form-control" placeholder="Please fill the name field *" required="required" data-error="You must fill the name field">
        <div class="help-block with-errors alert-danger"></div>
       </div>
      </div>
      <div class="col-lg-6"></div>
    </div>
    <div class="row">
     <div class="col-lg-6">
      <div class="form-group">
       <label for="form_email">E-mail *</label>
       <input id="form_email" type="email" name="email" class="form-control" placeholder="Please fill the email field *" required="required" data-error="You must fill the email field">
        <div class="help-block with-errors alert-danger"></div>
       </div>
      </div>
      <div class="col-lg-6"></div>
    </div>
    <div class="row">
     <div class="col-lg-6">
      <div class="form-group">
       <label for="form_subject">Subject *</label>
       <input id="form_subject" type="text" name="subject" class="form-control" placeholder="Please fill the subject field *" required="required" data-error="You must fill the subject field">
        <div class="help-block with-errors alert-danger"></div>
       </div>
      </div>
      <div class="col-lg-6"></div>
     </div>
     <div class="form-group">
      <label for="form_message">Message *</label>
      <textarea id="form_message" name="message" class="form-control" placeholder="Please fill the message field *" rows="4" required="required" data-error="You must fill the message field"></textarea>
       <div class="help-block with-errors alert-danger"></div>
      </div>
      <input type="submit" class="btn btn-success btn-send" value="Submit">
      <p class="text-muted" style="padding-top: 5px;"><strong>*</strong>This field must be fill.</p>
      </div><!-- controls all end -->
     </form><!-- form all end -->
    </div><!-- col-xl-8 offset-xl-2 end -->
   </div><!-- row all end -->
 </div><!-- container all end -->

– JAVA and AJAX CODE –

$(function () {
  $('#contact-form').on('submit', function (e) {
   if (!e.isDefaultPrevented()) {
    var url = "contact.php";

    $.ajax({
     type: "POST",
     url: url,
     data: $(this).serialize(),
     success: function (data) {
      var messageAlert = 'alert-' + data.type;
      var messageText = data.message;
      var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>' + messageText + '</div>';
      if (messageAlert && messageText) {
       $('#contact-form').find('.messages').html(alertBox);
       $('#contact-form')[0].reset();
      }
     }
    });
    return false;

   }
  })
});

– PHP CODE –

$from = '';
$sendTo = 'email@email.com';
$subject = 'New message from contact form';
$fields = array('name' => 'Name', 'email' => 'Email', 'subject' => 'Subject', 'message' => 'Message');

$okMessage = 'Thank you for your message. I will write back soon.';
$errorMessage = 'There is an error while sending message. Please try again later.';

try {if (!empty($_POST)) {
    $emailText = "You have a new message from your contact form\n=====\n";
    foreach ($_POST as $key => $value) {
       if (isset($fields[$key])) {
         $emailText .= "$fields[$key]: $value\n";
       }
    }
    $headers = array('Content-Type: text/plain; charset="UTF-8";',
     'From: ' . $from,
     'Reply-To: ' . $from,
     'Return-Path: ' . $from,
    );
    mail($sendTo, $subject, $emailText, implode("\n", $headers));
    $responseArray = array('type' => 'success', 'message' => $okMessage);
    }
}
catch (\Exception $e) {
  $responseArray = array('type' => 'danger', 'message' => $e->getMessage());
}
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
 $encoded = json_encode($responseArray);
 header('Content-Type: application/json');
 echo $encoded;
} else {
echo $responseArray['message'];
}

– SCREEN SHOT –

You should remove method and post attributes with their respective values from this line. Since you already using ajax these are superfluous and since they have presedence your form is submitted by using html form and not by ajax request.

Thank you for your reply. I delete method=“post” but now the site redirect this site and the site is blank.

websitename.com/contact.php?name=e&email=e%40e.com&subject=e&message=e&g-recaptcha-response=03AEMEkEnswJ4tasZ-tBV0nqtWO27ymSqHnEbOFGQKvdgg_cXCfXDv-RxugVRM25sHexT9On_9rs9Ub72DDzXc1URcng6HlTYsIUhTC7CrXLgyX5x-0R535OcM2S0ytb040j3Bkcd1Z1Qgv3F8qWBJve-Cr6hBhoU8AYcmTKzro3UmXJ_INjsHPQFMdgTjsV8k_OrvUPOkJJEiS-ndJ1AnSZ2PntZgLWNf8Uqan1t0POKPco4lmGAlSCyxf0lGtCg4U5UNQt_6VuMv6VDEfZEC8BPsi6Tld3z_MQ

I should written “method” and “action” attributes. Sorry about that. :slight_smile:

Thank you to help and direction to solve problem.

Fist of all, I changed that line without action="contact.php"

— OLD STYLE —

<form id="contact-form" method="post" action="contact.php" role="form" novalidate="true">

— NEW STYLE —

<form id="contact-form" method="post" role="form" novalidate="true">

The second one, at the of the body I had jquery-3.3.1.slim.min.js library but this library hasn’t AJAX so that I changed it jquery-3.3.1.min.js

Now, everything work fine.

Hello,

I tried what you have written but I think I am doing something wrong. I am a newbie so there is probably something I am missing. I will appreciate if you help.

<form id="contact-form" method="post" role="form" novalidate="true">
                            <div class="messages"></div>
                            <div class="controls">
                                <div class="form-group">
                                    <input id="form_name" type="text" name="name" class="form-control" placeholder="Name *" required="required" data-error="name is required.">
                                    <div class="help-block with-errors alert-danger"></div>
                                </div>
                                <div class="form-group">
                                    <input id="form_email" type="email" name="email" class="form-control" placeholder="E-mail *" required="required" data-error="Valid email is required.">
                                    <div class="help-block with-errors alert-danger"></div>
                                </div>
                                <div class="form-group">
                                    <input id="form_subject" type="text" name="subject" class="form-control" placeholder="Subject">
                                    <div class="help-block with-errors alert-danger"></div>
                                </div>
                                <div class="form-group">
                                    <textarea id="form_message" name="message" class="form-control" placeholder="Message for me *" rows="4" required="required" data-error="send a message."></textarea>
                                    <div class="help-block with-errors alert-danger"></div>
                                </div>
                                <input type="submit" class="btn btn-send float-" value="Send message">
                                <p class="text-muted"><strong>*</strong> These fields are required.</p>
                            </div>
                            <div class="clearfix"></div>
                        </form>
<?php

$from = '';
$sendTo = 'architect@nadirpamuk.com';
$subject = 'New message from contact form';
$fields = array('name' => 'Name', 'email' => 'Email', 'subject' => 'Subject', 'message' => 'Message');

$okMessage = 'Thank you for your message. I will write back soon.';
$errorMessage = 'There is an error while sending message. Please try again later.';

try {if (!empty($_POST)) {
    $emailText = "You have a new message from your contact form\n=====\n";
    foreach ($_POST as $key => $value) {
       if (isset($fields[$key])) {
         $emailText .= "$fields[$key]: $value\n";
       }
    }
    $headers = array('Content-Type: text/plain; charset="UTF-8";',
     'From: ' . $from,
     'Reply-To: ' . $from,
     'Return-Path: ' . $from,
    );
    mail($sendTo, $subject, $emailText, implode("\n", $headers));
    $responseArray = array('type' => 'success', 'message' => $okMessage);
    }
}
catch (\Exception $e) {
  $responseArray = array('type' => 'danger', 'message' => $e->getMessage());
}
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
 $encoded = json_encode($responseArray);
 header('Content-Type: application/json');
 echo $encoded;
} else {
echo $responseArray['message'];
}

?>
$(function () {
  $('#contact-form').on('submit', function (e) {
   if (!e.isDefaultPrevented()) {
    var url = "contact.php";

    $.ajax({
     type: "POST",
     url: url,
     data: $(this).serialize(),
     success: function (data) {
      var messageAlert = 'alert-' + data.type;
      var messageText = data.message;
      var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>' + messageText + '</div>';
      if (messageAlert && messageText) {
       $('#contact-form').find('.messages').html(alertBox);
       $('#contact-form')[0].reset();
      }
     }
    });
    return false;

   }
  })
});