1

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 same page. It see another page. 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 -->

--- 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'];
}

--- JS 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;

   }
  })
});
ErkanKilic
  • 19
  • 3
  • Have you loaded in the javascript file, and if so can you show us where and how? – Rick Jelier Aug 01 '18 at 13:57
  • Please explain this -> *"But the success message can't seen on same page. It see another page."* Do you mean you go to a different page? If so, what page? – Reinstate Monica Cellio Aug 01 '18 at 14:16
  • @Archer Yes, you are right. It's going to https://websitename.com/contact.php And on that page I see "Thank you for your message. I will write back soon." – ErkanKilic Aug 01 '18 at 14:37
  • I think @RickJelier is correct then - check that you've included the javascript correctly. If in doubt, just put an alert in it somewhere that should show when you go to the page. – Reinstate Monica Cellio Aug 01 '18 at 14:39
  • @Archer JS file added correctly but the alert is seen to redirected page. I don't want to redirect to show alert. The alert must be on the same page with contact form. – ErkanKilic Aug 01 '18 at 14:56
  • If you don't see the alert before the redirect then the javascript is not loaded. That's your problem. – Reinstate Monica Cellio Aug 01 '18 at 14:57
  • @Archer How can I solve this issiue? The javascript code is at the end of body tag before close body tag. Should I change the place in html? – ErkanKilic Aug 01 '18 at 15:03
  • I don't know. The code you've posted will not do what you describe. Try and reproduce the issue without using your own code - just something very basic. – Reinstate Monica Cellio Aug 01 '18 at 15:12
  • @Archer could you suggest me any example to take a look? – ErkanKilic Aug 01 '18 at 15:36
  • No - There's no way to tell what is wrong with your code. It would help if you could rethink your question. Remove the PHP as we don't care about that - it works. Make a simple html page with a form and some Javascript to submit that form using Ajax. If you get that working then use that as a base and build it up to what you're trying to do. If it doesn't work then you'll have a basic example that we can look at. As it stands there's no way to tell where the problem is. – Reinstate Monica Cellio Aug 01 '18 at 16:03

2 Answers2

0

If I understood your question correctly, when you submit the form, are you redirected ?! For that I will suggest you to remove the attribute of the action form. Then try this :

$ ('#contact-form'). On ('submit', function (e) {
e.preventDefault();
e.stopPropagation();
...

You must declare e.preventDefault(); before check if(!event.isDefaultPrevented())

  • Worth a try, but there's `return false;` at the end of the function, so it shouldn't be needed (and `stopPropagation()` isn't necessary). – Reinstate Monica Cellio Aug 01 '18 at 14:05
  • If the javascript isn't loaded in at all, the html will redirect to contact.php If the javascript is loaded in, the html will not use the action attribute – Rick Jelier Aug 01 '18 at 14:16
  • 1
    @RickJelier You're right, but until we know that the OP hasn't included the js file then a downvote is a bit harsh. No upvote is more suitable when you just don't know. – Reinstate Monica Cellio Aug 01 '18 at 14:19
  • 1
    @Archer you are exactly right, I shouldn't make assumptions. removed my downvote – Rick Jelier Aug 01 '18 at 14:22
  • 1
    @RickJelier I'm doing my bit to spread the niceness that Stack Overflow wants to convey! Thanks :D – Reinstate Monica Cellio Aug 01 '18 at 14:24
  • @Yona I tried what you suggest but now it not sending e-mail. I changed it back. – ErkanKilic Aug 01 '18 at 14:46
  • Ok. try to fill $from. It's looks empty until the end ! and take a look on console for errors. Can you send me the parameters of your request when you submit please ? (in console) – Yona Smilevitch Aug 01 '18 at 15:59
  • @YonaSmilevitch here is what you need but now it's not working. The character encoding of the HTML document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the page must be declared in the document or in the transfer protocol. – ErkanKilic Aug 01 '18 at 19:56
  • @YonaSmilevitch and the second part Error loading this URI: Could not load the source for https://tiyatromundus.com/contact.php?name=e&email=e%40e.com&subject=e&message=e&g-recaptcha-response=03AEMEkEkOHot9piYo-GENbTNiT3pVylNARpwlid6QhYroH9o5nBalVvpUym54unwDa-oF-wY9H-WuYeACKOPWcopOi3-s-0MiabZg43imi75j_AefACAMAsAXguVfxnibx1c_jaAXoSQFM_3_LjWeTdG1NrUkC9SpNXDYPF5Ni2wlkBs6f3IQPS5tKB5kPND9Iw0AUYc7s1b-2EkynBzy6Du1iI_j62V8fdk66ZU2cbAiiowcBIpKrIywpqI8NYZK3Fymr48lSfJhKx03qsvMrXPxeLK4iep6sg. – ErkanKilic Aug 01 '18 at 19:58
  • @YonaSmilevitch and the third part [Exception... "Component returned failure code: 0x80470002 (NS_BASE_STREAM_CLOSED) [nsIInputStream.available]" nsresult: "0x80470002 (NS_BASE_STREAM_CLOSED)" location: "JS frame :: resource://devtools/shared/base-loader.js -> resource://devtools/shared/DevToolsUtils.js :: onResponse :: line 569" data: no] Stack: onResponse@resource://devtools/shared/base-loader.js -> resource://devtools/shared/DevToolsUtils.js:569:23 onStopRequest@resource://gre/modules/NetUtil.jsm:126:17 Line: 569, column: 0 – ErkanKilic Aug 01 '18 at 19:59
  • Try clear the cache like: https://stackoverflow.com/questions/45294079/what-is-missing-that-i-get-an-ns-base-stream-closed-error – Yona Smilevitch Aug 02 '18 at 09:17
0

Thank all of 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.

ErkanKilic
  • 19
  • 3