Help in swiftmailer + Some extra PHP help needed

I am dealing with wordpress theme.

This is the code:

<?php
       include get_template_directory().'lib/swift_required.php';
       $valid = true;
       $errors = array();
        $contact = array(
            'first_name' => null,
            'last_name' => null,
            'email' => null,
            'telephone' => null,
            'postcode' => null,
            'message' => null
        );
         $contact = filter_input_array(INPUT_POST, array(
        'first_name'   => FILTER_SANITIZE_STRING,
        'last_name'   => FILTER_SANITIZE_STRING,
        'email'   => FILTER_SANITIZE_STRING,
        'telephone'   => FILTER_SANITIZE_STRING,
        'postcode'   => FILTER_SANITIZE_STRING,
        'message'   => FILTER_SANITIZE_STRING,
        ), true);
        ?>

But there is select HTML also. How can I take input from select options just like we did for telephone name etc?

<select name="wherefrom">
<option value="">How did you hear about us?</option><option value="Friend / Family">Friend / Family</option>
<option value="TV">TV</option>
<option value="Local Radio">Local Radio</option>
<option value="Talksport">Talksport</option>
<option value="Google Search">Google Search</option>
<option value="Online">Online</option>
<option value="Rightmove / Zoopla">Rightmove / Zoopla</option>
<option value="Email">Email</option>
<option value="Newspaper">Newspaper</option>
<option value="Other">Other</option>
</select>

When someone chooses an option from the select, its value will come through the POST under the value of the “name” attribute of the select. In your example that would be “wherefrom”. So you can filter it like any other field.

$contact = filter_input_array(INPUT_POST, array(
        'first_name'   => FILTER_SANITIZE_STRING,
        'last_name'   => FILTER_SANITIZE_STRING,
        'email'   => FILTER_SANITIZE_STRING,
        'telephone'   => FILTER_SANITIZE_STRING,
        'postcode'   => FILTER_SANITIZE_STRING,
        'message'   => FILTER_SANITIZE_STRING,
        'wherefrom' => FILTER_SANITIZE_STRING
        ), true);

Notice how we can filter it just like all the others because the value will be a string from whatever option is selected. This works with single selects, multiple selection select boxes will result in an array that will need to be handled differently. But for your example the single select is all you need.

2 Likes

I am new here. My only 1 question actually belonged to wordpress rest all are from PHP. Please help me to move this post to PHP again so that I can ask my question and get attention that is needed.

The question you have asked here seems to be entirely WordPress-related, @Novice.

If you have other PHP questions, then please open a new thread in the PHP section for those.

1 Like

i have deleted that question. please move to php where originally i posted.

Thank you so much for respecting my request.

3 Likes

Hasn’t the question already been answered by @Martyr2?

Yes, and No. More questions coming. writing them.

OK. If they’re unrelated to this, it might be best to start a separate thread for them - for example I know nothing about Swiftmailer so probably wouldn’t come in here usually.

Completed realted to swiftmailer.

Its been 5 days since I was struggling to send my emails.

I was following this Tutorial

I also used this JS/Jquery/AJAX from this tutorial:


<script type="text/javascript">
(function($) {
    $(document).ready(function(){
$('#userform').submit(function(){

// show that something is loading
$('#response').html("<b>Loading response...</b>");

// Call ajax for pass data to other place
$.ajax({
type: 'POST',
url: 'page-sixpages.php',
data: $(this).serialize() // getting filed value in serialize form
})
.done(function(data){ // if getting done then call.

// show the response
$('#response').html(data);

})
.fail(function() { // if fail then getting message

// just in case posting your form failed
alert( "Posting failed." );

});

// to prevent refreshing the whole page page
return false;

});
});
})(jQuery);

</script>

It appears that the script is working, because once you click the submit button something changes in the URL and page refreshes.

But the issue is that the emails are either not sending or I am unable to receive. Here is the code that I have written in the config.php file:

"mail" => array(
    "type" => "smtp",
    "server" => "smtp.gmail.com",
    "port" => 587,
    "auth" => true,
    "username" => "richacrunch2@gmail.com",
    "password" => "###########"
)

page–sixpages.php is actually a WordPress page template.

What steps should I take to troubleshoot that why this form is unable to send the email either the emails are not sending or I am not receiving. I

n the tutorial link that I gave above it is mentioned TO EMAIL id is the username that we have given in the config.php file – which is a Gmail ID that means I should receive email on that particular email ID, but that is not happening.

Either the PHP code or Swift Mailer script has some bug or error or may be JS/AJAX has some issue.

Please guide me what steps should I take to trouble shoot?

page–sixpages.php has swiftmailer code:

<?php
        include get_template_directory().'lib/swift_required.php';
        include get_template_directory().'lib/config.php';
        $valid = true;
        $errors = array();
        $contact = array(
            'first_name' => null,
            'last_name' => null,
            'email' => null,
            'telephone' => null,
            'postcode' => null,
            'message' => null,
            'wherefrom' => null,
            'wherefrom2' => null
        );
         $contact = filter_input_array(INPUT_POST, array(
        'first_name'   => FILTER_SANITIZE_STRING,
        'last_name'   => FILTER_SANITIZE_STRING,
        'email'   => FILTER_SANITIZE_STRING,
        'telephone'   => FILTER_SANITIZE_STRING,
        'postcode'   => FILTER_SANITIZE_STRING,
        'message'   => FILTER_SANITIZE_STRING,
        'wherefrom' => FILTER_SANITIZE_STRING,
        'wherefrom2' => FILTER_SANITIZE_STRING,
        ), true);
        if (empty($contact['first_name'])) {
        $valid = false;
        $errors['first_name'] = "You must enter your name.";
        }
        if (empty($contact['last_name'])) {
        $valid = false;
        $errors['last_name'] = "You must enter your name.";
        }
        if (empty($contact['telephone'])) {
        $valid = false;
        $errors['telephone'] = "You must enter your name.";
        }
        if (empty($contact['postcode'])) {
        $valid = false;
        $errors['postcode'] = "You must enter your name.";
        }
        if (empty($contact['wherefrom'])) {
        $valid = false;
        $errors['wherefrom'] = "You must enter your name.";
        }
        if (empty($contact['wherefrom2'])) {
        $valid = false;
        $errors['wherefrom2'] = "You must enter your name.";
        }
        if (empty($contact['email'])) {
            $valid = false;
            $errors['email'] = "You must enter your email address.";
        } elseif (!filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL)) {
            $valid = false;
            $errors['email'] = "You must enter a valid email address.";
        }
        if (empty($contact['message'])) {
            $valid = false;
            $errors['message'] = "You must enter a message.";
        }
        if ($valid) {
                    // The email address the email will be sent to
                $to = $config['contact']['to'];
                // Set the from address for the email
                $from = $config['contact']['from'];
                // The email subject
                $subject = "Contact Form Submission";
                // Build the body of the email
                $mailbody = "The contact form has been filled out.\n\n"
                          . "Name: " . $contact['first_name'] . "\n"
                          . "Email: " . $contact['email'] . "\n"
                          . "Message:\n" . $contact['message'];
                // Create the mail
                $mail = Swift_Message::newInstance();
                $mail->setSubject($subject);
                $mail->setFrom(array($from));
                $mail->setTo(array($to));
                $mail->setReplyTo(array($contact['email'] => $contact['name']));
                $mail->setBody($mailbody);
                // Create the mail transport
                if ($config['mail']['type'] == 'smtp') {
                    // Use smtp account
                    $transport = Swift_SmtpTransport::newInstance($config['mail']['server'], $config['mail']['port']);
                    if ($config['mail']['auth']) {
                        $transport->setUsername($config['mail']['username']);
                        $transport->setPassword($config['mail']['password']);
                    }
                } else {
                    // Use mail function as fallback
                    $transport = Swift_MailTransport::newInstance();
                }
                // Create a mailer
                $mailer = Swift_Mailer::newInstance($transport);
                // Send the mail
                $result = $mailer->send($mail);

                // Go to the thank you page
                header("location: thankyou.html");
                exit;
            // }
        }

        ?>

HTML

<div class="phpcontactform">
            <h3>Guaranteed Rent Enquiry</h3>
            <?php if (!$valid): ?>
                <div class="error">
                    <?php foreach($errors as $message):?>
                        <div><?php echo htmlspecialchars($message); ?></div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
            <form id="userform" class="phpmailform validate-form">
                <div class="phpmailformone">
                    <input type="text" name="first_name" id="first_name" placeholder="First Name" required="" aria-required="true">

                    <input type="text" name="last_name" id="last_name" placeholder="Last Name" required="" aria-required="true">
                    <input type="text" name="email" id="email" placeholder="Email" required="" aria-required="true">
                    <input type="text" name="telephone" id="telephone" placeholder="Telephone" required="" aria-required="true">

                    <select name="wherefrom">
                        <option value="">How did you hear about us?</option><option value="Friend / Family">Friend / Family</option>
                        <option value="TV">TV</option>
                        <option value="Local Radio">Local Radio</option>
                        <option value="Talksport">Talksport</option>
                        <option value="Google Search">Google Search</option>
                        <option value="Online">Online</option>
                        <option value="Rightmove / Zoopla">Rightmove / Zoopla</option>
                        <option value="Email">Email</option>
                        <option value="Newspaper">Newspaper</option>
                        <option value="Other">Other</option>
                    </select>
                        <label ><input> Get emails with the latest news and information on the local property market, our products and services. You can unsubscribe at any time.</label>

                        <input id="guaranteedRentSubmitButton" class="btn std-button-red no-margin-right" style="width: 100%;" type="submit" value="Send" style="margin-top: 30px;" name="SubmitBtn">
                </div>
                <div class="phpmailformtwo">
                    <div class="input-holder">
                        <select name="wherefrom2]">
                		<option value="">Select a branch</option>
                		<option value="10537">Aberdeen</option>
                		<option value="29771">Ashford</option>
                		<option value="29078">Banbury</option>
                		<option value="28442">Barnstaple</option>
                		<option value="24877">Basildon</option>
                		<option value="15412">Basingstoke</option>
                		<option value="28449">Bedford</option>
                		<option value="28450">Beverley and Hull</option>
                		<option value="8903">Birmingham</option>
                		<option value="28451">Bolton</option>
                		<option value="5091">Bournemouth</option>
                		<option value="28766">Brentwood</option>
                		<option value="7908">Bristol</option>
                		<option value="5090">Bromley</option>
                		<option value="33895">Byfleet</option>
                		<option value="9617">Cambridge</option>
                		<option value="9738">Cardiff and Newport</option>
                		<option value="9556">Carlisle</option>
                		<option value="28453">Central Scotland</option>
                		<option value="9988">Chelmsford</option>
                		<option value="11712">Cheltenham</option>
                		<option value="9842">Chester</option>
                		<option value="28765">Coventry</option>
                		<option value="28456">Crawley</option>
                		<option value="10495">Crewe &amp; Sandbach</option>
                		<option value="23221">Derby</option>
                		<option value="10938">Doncaster</option>
                		<option value="33608">Dulwich</option>
                		<option value="23220">Dundee</option>
                		<option value="28458">Eastbourne</option>
                		<option value="11167">Edinburgh</option>
                		<option value="16245">Epsom</option>
                		<option value="6503">Exeter</option>
                		<option value="11494">Glasgow</option>
                		<option value="34077">Glossop</option>
                		<option value="11888">Harrow</option>
                		<option value="28460">Hastings</option>
                		<option value="28461">Hereford</option>
                		<option value="12056">High Wycombe</option>
                		<option value="33599">Horwich &amp; Blackrod</option>
                		<option value="12464">Ipswich</option>
                		<option value="12880">Lancaster</option>
                		<option value="13365">Leeds</option>
                		<option value="13041">Leicester</option>
                		<option value="23179">Lincoln</option>
                		<option value="12753">Liverpool</option>
                		<option value="13406">Luton</option>
                		<option value="16076">Macclesfield</option>
                		<option value="28623">Maidenhead</option>
                		<option value="28462">Milton Keynes</option>
                		<option value="14005">Newcastle</option>
                		<option value="28463">Northampton</option>
                		<option value="28464">Norwich</option>
                		<option value="14213">Nottingham</option>
                		<option value="28465">Oldham &amp; East Manchester</option>
                		<option value="28624">Oxford</option>
                		<option value="14796">Peterborough</option>
                		<option value="24307">Plymouth</option>
                		<option value="15246">Portsmouth </option>
                		<option value="15276">Preston</option>
                		<option value="28466">Reading &amp; Newbury</option>
                		<option value="29185">Retford</option>
                		<option value="15638">Romford</option>
                		<option value="28467">Salisbury</option>
                		<option value="28468">Sheffield &amp; Rotherham</option>
                		<option value="9005">Solihull</option>
                		<option value="28470">South Manchester</option>
                		<option value="1121">Southampton</option>
                		<option value="20537">Southend on Sea</option>
                		<option value="28471">Southport and Ormskirk</option>
                		<option value="10543">St Albans</option>
                		<option value="28472">Stoke on Trent</option>
                		<option value="8989">Tamworth</option>
                		<option value="34102">Taunton &amp; Bridgwater</option>
                		<option value="28473">Telford</option>
                		<option value="28474">Thorne</option>
                		<option value="34202">Torquay</option>
                		<option value="28455">Truro</option>
                		<option value="9087">Warminster</option>
                		<option value="25066">Warrington</option>
                		<option value="33097">Waterlooville</option>
                		<option value="17750">Watford</option>
                		<option value="28457">West Norwood</option>
                		<option value="17835">Wigan</option>
                		<option value="28476">Wirral</option>
                		<option value="15516">Wokingham</option>
                		<option value="17873">Worcester</option>
                		<option value="28477">Worthing &amp; Littlehampton</option>
                		<option value="13107">Wrexham</option>
                		<option value="18056">York</option></select>
                    </div>
                     or

                    <div class="input-holder">
                        <input type="text" class="validate" name="postcode" id="postcode" placeholder="Postcode">
                    </div>

                    <div class="input-holder">
                        <textarea name="message" placeholder="Question"></textarea>
                    </div>
                </div>
            </form>
            <div class="response">

            </div>
        </div>
    </div>

Why are you using jQuery? Did you get the contact form working before you tried adding the jQuery code?

1 Like

I’m sorry for intervening the post, but actually, I was following this post and I was possibly willing to help @Novice.

As for as I understand the form was unable to send the email before also.

Reason being – For the form to send an email PHP code should be executed and that is why the action url is.

But form action is not that simple as in normal PHP file – WordPress has its own complications.

<form id="userform" class="phpmailform validate-form" action="contact-page.php" method="post">

I searched for many solutions, and I was able to find this one, but this one is not useful. Reason being the part where it is pointing is in the word press core File that is WP – admin, and which team developer will put an executable file here which will be wiped away on the next word press update. So that solution is also

So this is the reason possibly why no office has moved to J query or an Ajax solution.

Sorry for putting my perspective, but this post still belongs to PHP domain as the original poster has deleted that perspective of WordPress, but I was trying to connect the missing.

I am also a beginner so my syntax or not very polished, but if I understand the logic then there is a possibility in that action we can put the current URL of the WordPress page and on pressing the submit button that you are maybe executed, but based on the previous post which was actually deleted by the original poster that may create this challenge so although logically this could be a solution, but again it will create the same issue.

Previously what it was doing was:

www.sample.com/contact-page/

On triggering action this was the issue:

www.sample.com/contact-page/actionpage.php

the solution I am suggesting may create this issue:

www.sample.com/contact-page/www.sample.com/contact-page
1 Like

I dont know any other method. No, the emails were not sending as pointed by codeispoetry that form action needs to be completed.

I think leaving action blank will keep us on the same page:

action="" method="post"

and we may skip JQuery/JS/Ajax.

If you create a copy of your PHP code, stick some test (valid) values into it, and run it directly in the browser, does it work then? If it does, then it points to some issue with how you call it. But running it directly in the browser instead of as an Ajax call means you can insert debugging code and see what’s happening.

1 Like

How can I do it. Please bear with me I have limited knowledge. Thanks.

Copy that PHP code to a new separate file. Change the section where you grab the values from the $_POST array to just assigning them from scratch, then run the code in your browser.

So instead of this bit

$contact = filter_input_array(INPUT_POST, array(
        'first_name'   => FILTER_SANITIZE_STRING,
        'last_name'   => FILTER_SANITIZE_STRING,
        'email'   => FILTER_SANITIZE_STRING,
        'telephone'   => FILTER_SANITIZE_STRING,
        'postcode'   => FILTER_SANITIZE_STRING,
        'message'   => FILTER_SANITIZE_STRING,
        'wherefrom' => FILTER_SANITIZE_STRING,
        'wherefrom2' => FILTER_SANITIZE_STRING,
        ), true);

you’ll need to assign every value separately:

$contact['first_name'] = "Dave";
$contact['last_name'] = "Greenfield";
$contact['email'] = "keywiz@musos.com";
...  do the rest of the fields here
$contact['wherefrom2'] = "Brighton";

and so on for each field.

Also note that a PHP script called from Ajax will just return to the Ajax call, so there’s no point doing a header redirect at the end of it. You should echo a result code, then examine that code when it gets back to the caller in the success() function. But that can wait until you have the PHP code working.

1 Like

sir, Can you please elaborate this?

Where you have your header redirect, you could just have something like

echo "Success";

and where your “else” clauses would be where you do your validation, you’d have something like

echo "Failed";

At the moment you build up an array called $error, but you don’t do anything with it. That would also be a valid thing to send back.

As for what to do with it when it comes back, in your JS code has done() and fail() functions to deal with those situations. You might need to return something different, perhaps a different HTTP status code, I’m not totally sure on that, but it’s well documented. Or you can deal with it all in the done() or success() function, and just look at the data value that comes back - that contains all the stuff that your PHP code outputs via echo().

But, get the PHP working and debugged first, as it’s more difficult once you call it from Ajax.

1 Like

can you tell me what should I do here. i am slightly confused:

// Go to the thank you page
  header("location: thankyou.html");
  exit;

I also read this somewhere that

If you leave the action empty, the form will submit to the same page.

So just do this: <form action='' method='get'>";

Is this correct? If yes, then use of JS will be not needed?

and method will be get?