Mitchell H Mitchell H - 3 months ago 9
Ajax Question

How to execute a PHP email script using AJAX? [Current code is not working]

After browsing stackoverflow and multiple other sites for a solution to my problem I have come up with some AJAX and a PHP email script using SwiftMailer.

As far as I am aware, my AJAX is not running hence the PHP script is never executed.

My question: Am I using AJAX correctly to execute my script? Additionally, is there a way to achieve my desired result?

Context: I am working on a school coursework project based around a schedule/rota site for families. I have pretty much reached the standards for a first build and decided to add a feature to send an email when a job is scheduled.

Email Script (domain has been censored):

<?php

$setBy = $_GET['setBy'];
$jobEmail = $_GET['jobEmail'];
$subject = $_GET['emailSub'];
$content = $_GET['emailContent'];

$headers = 'From: MyRota@*****' . "\r\n" .
'Reply-To: MyRota@*****' . "\r\n" .
'X-Mailer: PHP/' . phpversion();


require_once '../swiftmailer/lib/swift_required.php';
$transport = Swift_MailTransport::newInstance();
// Create the message
$message = Swift_Message::newInstance();
$message->setTo(array(
$jobEmail => "MyFamilyRota User",
));
$message->setSubject($subject);
$message->setBody($emailContent);
$message->setFrom("MyRota@*****", "MyFamilyRota");
$mailer = Swift_Mailer::newInstance($transport);
$mailer->send($message);


The emailing part works perfectly but causes a page to run slowly when it is located on the actually scheduling .php due to email sending taking a long period of time. Hence my desire to push the email features to an alternative script that will handle it without slowing down a user's experience.

My AJAX/PHP (does not include the whole file as the issue is with the following section):

$emailContent = "Assigned Job: $jobName\nJob Description: $jobDesc\nAssigned By: $setBy\nStart Time: $time_start\nEnd Time: $time_end\n";
$emailContent = wordwrap($emailContent, $words = 70);
$subject = "New Job Assigned: $jobName!";
?>
<script type="text/javascript" src="jquery-3.1.0.js"></script>
<script type="text/javascript">
function sendEmail() {
$.ajax({
method: 'get',
url: "job_email.php",
data: {
'setBy': <?php $setBy ?>,
'useremail': <?php $emailRow[0] ?>,
'emailContent': <?php $emailContent ?>,
'emailSub': <?php $subject ?>
},
success: function () {
alert("done");
}});
}
</script>
<?php
echo "<script type='text/javascript'>sendEmail();</script>";


Is this the correct way of executing a php script with AJAX or have I done something completely wrong?

(Please excuse any inefficient code or bad practice. I am relatively new to PHP and web development so I understand that some sections of my code may be sloppy.)

EDIT - form sending the data:

<form id='login' action='jobAssigner.php' method='post' accept-charset='UTF-8'>
<fieldset>
<legend>Assign Job To <?php echo $_SESSION['assignee_name'] ?></legend>
<input type='hidden' name='submitted' id='submitted' value='1'/>
<label for='jobSelect'>Job Selection:</label>
<?php echo $select; ?>
<br />
<label for='time_start'>Job Start:</label>
<input type='datetime-local' name='time_start' id='time_start' value=''/>
<br />
<label for='time_end'>Job End:</label>
<input type='datetime-local' name='time_end' id='time_end' value=''/>
<br />
<input type='submit' name='assign' id='assign' value='Assign!' />
</fieldset>
</form>


This should all be working as jobs are being added to the database and appearing under an upcoming job list.

UPDATE:

After fixing a few errors with my code, I've reached a new error but the AJAX function is running now.

The AJAX function returns with an error: POST http://******.com/home/job_email.php 500 (Internal Server Error)send @ jquery-3.1.0.js:9392ajax @ jquery-3.1.0.js:8999sendEmail @ jobAssigner.php:4(anonymous function) @ jobAssigner.php:18

NEW AJAX:

function sendEmail() {
$.ajax({
method: 'POST',
url: "job_email.php",
data: {
'setBy': '<?php echo $newSetBy ?>',
'useremail': '<?php echo $emailRow[0] ?>',
'emailContent': '<?php echo $emailContent ?>',
'emailSub': '<?php echo $subject ?>'
},
success: function () {
alert("done");
}});
}
</script>
<?php
echo "<script type='text/javascript'>sendEmail();</script>";


UPDATE:

Thank you to everyone for their contributions! :) The 500 error was a result of some variable name changes during the process of the original question. It is all fixed now.

Answer

Take a look at the page source for the AJAX and PHP to see what PHP generated for you.

I'd expect your AJAX function to be rendered like this:

<script type="text/javascript">
        function sendEmail() {
            $.ajax({
                method: 'get',
                url: "job_email.php",
                data: {
                    'setBy': ,
                    'useremail': ,
                    'emailContent': ,
                    'emailSub': 
                },
                success: function () {
                    alert("done");
                }});
        }
    </script>

The issue becomes much more obvious that this isn't actually sending any data. You've attempted to provide that data from PHP to Javascript by using <?php $setBy ?> and such, but doing so doesn't actually output it - to actually output it you must echo it.

<?php echo $setBy ?>