1

I have this form where I'm sending a mail (via Post method) :

<form method="POST" action="sendmail.php">
  <input type="text" name="sender_name" placeholder="Name" required="">
  <input type="text" name="sender_email" placeholder="Email" required="">
  <input type="text" name="subject" placeholder="Subject" required="">
  <textarea placeholder="Message" name="message" required=""></textarea>
  <input type="submit" name="send" value="SEND">
</form>

and here's my sendmail.php :

<?php
  if($_POST['send'] == 'SEND'){    
    $to      = 'queries@mydomain.com';
    $subject = $_POST['subject']; 
    $message = $_POST['message']; 
    $headers = "From: ".$_POST['sender_nam‌​e​']." <".$_POST['sender_em‌​ail‌​'].">\r\n"; $headers = "Reply-To: ".$_POST['sender_ema‌​il‌​']."\r\n"; 
    $headers = "Content-type: text/html; charset=iso-8859-1\r\n";
    'X-Mailer: PHP/' . phpversion();

    mail($to, $subject, $message, $headers);
  }
?>

As you can see that in above code I'm sending a mail which is working fine, but the above action is executing by leaving current page

e.g before posting my url is mydomain.com after posting it becomes mydomain.com/sendmail.php.

So how can i execute above function without leaving current page?

remy boys
  • 2,928
  • 5
  • 36
  • 65

3 Answers3

1

Do you know about Ajax and jQuery? Read more, here.

Your ajax call can look like this.

    $.ajax({
      url: "yourApplication/methodWhichSendsEmail",
      type: "post",
      data:JSON.stringify({
           to : $to,
           subject: $subject,
           message: $message,
           headers: $headers
})

}).done(function() {
  //Whatever you want to do once the request is succeed. As you don't want to reload. i.e.
  alert("Email Sent");
});
Zeshan Munir
  • 1,058
  • 1
  • 14
  • 23
1

Either by AJAX or you can do the following:

  1. You specify action="" in the <form>
  2. You include the code from sendmail.php to index.php (or whatever your homepage is)
Jirka Hrazdil
  • 3,983
  • 1
  • 14
  • 17
0

You need to set your form action empty.

Then in PHP code you need to check if form is posted or not. SO need to check it first by php function isset then you can do whatever you want, This will only send email if a form is posted

  if(isset ($_POST['send']) && $_POST['send'] == 'SEND'){    
    $to      = 'queries@mydomain.com';
    $subject = $_POST['subject']; 
    $message = $_POST['message']; 
    $headers = "From: ".$_POST['sender_nam‌​e​']." <".$_POST['sender_em‌​ail‌​'].">\r\n"; $headers = "Reply-To: ".$_POST['sender_ema‌​il‌​']."\r\n"; 
    $headers = "Content-type: text/html; charset=iso-8859-1\r\n";
    'X-Mailer: PHP/' . phpversion();

    mail($to, $subject, $message, $headers);
  }
Faisal Ijaz
  • 1,812
  • 2
  • 12
  • 23