'Execute script after email send in php
Hello I am sending email with smtp. Email is sending schusses fully but the script after email send script is not working. can anyone help me with this ?
Emails are sending successfully but in return the script is not executing.
Also email take like 2 seconds to send but it does not matter the mail issue is script is not working
Here's code
<?php
require 'include/dbconfig.php';
require_once "vendor/autoload.php";
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
//PHPMailer Object
$mail = new PHPMailer(); //Argument true in constructor enables exceptions
// SMTP configuration
$mail->SMTPDebug = 1;
$mail->isSMTP();
$mail->Mailer = "smtp";
$mail->Host = "smtp.gmail.com";
$mail->SMTPAuth = true;
$mail->Username = "[email protected]";
$mail->Password = "emailpassword";
$mail->SMTPSecure = "tls";
$mail->Port = 587;
$mail->isHTML(true);
$mail->setFrom('[email protected]', 'Sabir');
$mail->addAddress("[email protected]");
$mail->Subject = "Test";
$mail->Body = "Test Email";
$email_sent=$mail->send();
if(!$email_sent) { ?>
<script language="javascript" type="text/javascript">
alert('Something went wrong');
</script><?php
} else { ?>
<script language="javascript" type="text/javascript">
alert('Thank you for the message');
</script>
<?php
}
?>
Solution 1:[1]
Good morning,
you can cut your statements a bit down:
$email_sent=$mail->send();
if(!$email_sent) { ?>
<script language="javascript" type="text/javascript">
alert('Something went wrong');
</script><?php
} else { ?>
<script language="javascript" type="text/javascript">
alert('Thank you for the message');
</script>
<?php
}
It should look and work like that:
$email_sent = $mail->send();
if(!$email_sent) {}else {}
Also you don´t need to make all this breaks, just put your js in a echo and remove that:
language="javascript"
instead go for:
echo "<script>alert('Something went wrong');</script>";
So it would look like that:
$email_sent = $mail->send();
if(!$email_sent) {
echo "<script>alert('Something went wrong');</script>";
} else {
echo "<script>alert('Thank you for the message');</script>";
}
Edit
Nearly forgot!
Now we have cleared the code a bit, but it won´t work like that.
You will need to adjust your form aswell with:
onclick or onsubmit
Or go for an ajax call:
$('#mailform').on('submit', function(e)
{
e.preventDefault();
$.ajax({
data: {data_field: 'value'},
type: 'post',
url: '/script.php',
success: function(r) {$('#thepoup').removeClass('hidden')},
error: function(r) {alert('error'); console.log(r)}
});
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
