4

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.

M it
  • 120
  • 1
  • 9
  • You need to consider on what action your script will fire. Is it some form submitting? – jaro1989 Aug 25 '16 at 23:44
  • It's data based on the most recent job assigned. The majority of this data is gained from a few MySQL queries. – M it Aug 25 '16 at 23:46
  • So when do you want to send your email? I mean, what is the exact action of user (button click, data submit, external change of db, once per day etc) – jaro1989 Aug 25 '16 at 23:49
  • Ah, the data is sent from one page via post on a form. This is sent to the script to add the job to the database. The email is meant to be sent at the end of this script to inform the user that a job has been assigned/scheduled. – M it Aug 25 '16 at 23:50
  • ok, could you provide your form? The answer below is also correct, but isn't full for you – jaro1989 Aug 25 '16 at 23:52
  • I shall edit my question with the form I am using. – M it Aug 25 '16 at 23:53
  • 1
    To summarize. At this moment you're submitting your form to jobAssigner.php - script, it consists of sql-execution script and your ajax try which is sending email on load of jobAssigner.php. It would be better to move sql -execution to job_email.php as it depends on results of script. I'll try to show you. – jaro1989 Aug 26 '16 at 00:06
  • "The AJAX function returns with an error POST http://******.com/home/job_email.php 500 (Internal Server Error)" Unless you've also updated your PHP snippet to look for `$_POST` variables rather than `$_GET`, the data isn't being properly stored in `$setBy`. You might also check PHP error log if you have access (you might not if use shared hosting from your school) for a more detailed explanation. If you can't check the error log, you might [try a post request another way](http://stackoverflow.com/questions/4797534/how-do-i-manually-fire-http-post-requests-with-firefox-or-chrome) to see errors. – HPierce Aug 26 '16 at 00:25
  • I updated the job_email.php to take POST variables. I've checked the apache log and it seems to be from SwiftMailer, I shall take a look and get back to you! :) – M it Aug 26 '16 at 00:30

1 Answers1

2

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 ?>
HPierce
  • 7,249
  • 7
  • 33
  • 49
  • After checking the page source it seems one of my variables is not giving an output. This, in turn, has caused the entire AJAX function to fail. – M it Aug 25 '16 at 23:54
  • I have updated the question with a new error. Thank you for your support so far! :) – M it Aug 26 '16 at 00:17