0

I have a page where I have this form that sends the data in an email.
I want that when I click the submit button, other than sending the data through email, I want to send the data in a page where I have an INSERT script.

Here's the code of my page:

<!doctype html>
<html lang="en">

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<?php

require_once __DIR__.'/vendor/autoload.php';
require_once __DIR__.'/config.php';

session_start();

if (!empty($_SESSION['_contact_form_error'])) {
    $error = $_SESSION['_contact_form_error'];
    unset($_SESSION['_contact_form_error']);
}

if (!empty($_SESSION['_contact_form_success'])) {
    $success = true;
    unset($_SESSION['_contact_form_success']);
}

?>
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

    <title>Appointmenta</title>

    <!-- reCAPTCHA Javascript -->
    <script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-md-8 offset-md-2">
            <div class="card mt-5">
                <div class="card-body">
                    <h1 class="card-title">
                        Add an Appointment
                    </h1>

                    <?php
                    if (!empty($success)) {
                        ?>
                        <div class="alert alert-success">Message sent successfully.</div>
                        <?php
                    }
                    ?>

                    <?php
                    if (!empty($error)) {
                        ?>
                        <div class="alert alert-danger"><?= $error ?></div>
                        <?php
                    }
                    ?>

                    <?php $Field1= $_POST['Field1']; ?>
                    <?php $Field2= $_POST['Field2']; ?>
                    <?php $Field3= $_POST['Field3']; ?>
                    <?php $Field4= $_POST['Field4']; ?>
                    <?php $Field5= $_POST['Field5']; ?>
                    <?php $Field6= $_POST['Field6']; ?>
                    <?php $Field7= $_POST['Field7']; ?>
                    <?php $Field8= $_POST['Field8']; ?>
                    <?php $Field9= $_POST['Field9']; ?>

                    <form id="target" method="post">
                        <div class="form-group">
                            <label for="name">Field 1</label>
                            <input type="text" name="Field1" id="Field1" class="form-control" 
                                   value="<?php echo $Field1?>">
                        </div>

                        <div class="form-group">
                            <label for="subject">Field 2</label>
                            <input type="text" name="Field2" id="Field2" class="form-control"
                                   value="<?php echo $Field2?>">
                        </div>

                        <div class="form-group">
                            <label for="email">Field 3</label>
                            <input type="text" name="Field3" id="Field3" class="form-control" 
                                   value="<?php echo $Field3?>">
                        </div>

                        <div class="form-group">
                            <label for="subject">Field 4</label>
                            <input type="text" name="Field4" id="Field4" class="form-control"
                                   value="<?php echo $Field4?>">
                        </div>

                        <div class="form-group">
                            <label for="subject">Field 5</label>
                            <input type="text" name="Field5" id="Field5" class="form-control"
                                   value="<?php echo $Field5?>">
                        </div>

                        <div class="form-group">
                            <label for="subject">Field 6</label>
                            <input type="text" name="Field6" id="Field6" class="form-control"
                                   value="<?php echo $Field6?>">
                        </div>

                        <div class="form-group">
                            <label for="subject">Field 7</label>
                            <input type="text" name="Field7" id="Field7" class="form-control"
                                   value="<?php echo $Field7?>">
                        </div>
                   
                        <div class="form-group">
                            <label for="subject">Field 8</label>
                            <input type="text" name="Field8" id="Field8" class="form-control"
                                   value="<?php echo $Field8?>">
                        </div>

                        <div class="form-group">
                            <label for="message">Field 9</label>
                            <input type="text" name="Field9" id="Field9" class="form-control" 
                                   value="<?php echo $Field9?>">
                        </div>

                        <div class="form-group text-center">
                            <div align="center" class="g-recaptcha" data-sitekey="<?= CONTACTFORM_RECAPTCHA_SITE_KEY ?>"></div>
                        </div>

                        <button "name="submit" class="btn btn-primary btn-block"> Send Email</button>
                    </form>

                    <form action="../list.php">
                        <p><br></p>
                        <button class="btn btn-primary btn-block">Return home.</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
</html>

<script language="Javascript">
<!--

$('form').submit(function(event) {
        event.preventDefault();
        $.ajax({
            method: 'POST',
            url: 'submit.php',
            data: $( this ).serialize()
        });
    });
-->
</script>

When I click on 'Send Email' nothing happens.

**I want to click 'Send Email' and see the message 'Message sent successfully'. At the same time I want that same data to be sent to appointment.php, which inserts the data into a table. I'd prefer that 'appointment.php' doesn't even open, I want to stay on index.php when I click 'Send Email'**



Code of submit.php

<?php

require_once __DIR__.'/vendor/autoload.php';
require_once __DIR__.'/functions.php';
require_once __DIR__.'/config.php';

session_start();

// Basic check to make sure the form was submitted.
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
echo "The form must be submitted with POST data.";
exit();
}

require "appointment.php";

// Do some validation, check to make sure the name, email and message are valid.
if (empty($_POST['g-recaptcha-response'])) {
    echo "Please complete the CAPTCHA.";
}

$recaptcha = new \ReCaptcha\ReCaptcha(CONTACTFORM_RECAPTCHA_SECRET_KEY);
$resp = $recaptcha->verify($_POST['g-recaptcha-response'], $_REQUEST['REMOTE_ADDR']);

if (!$resp->isSuccess()) {
    $errors = $resp->getErrorCodes();
    $error = $errors[0];

    $recaptchaErrorMapping = [
        'missing-input-secret' => 'No reCAPTCHA secret key was submitted.',
        'invalid-input-secret' => 'The submitted reCAPTCHA secret key was invalid.',
        'missing-input-response' => 'No reCAPTCHA response was submitted.',
        'invalid-input-response' => 'The submitted reCAPTCHA response was invalid.',
        'bad-request' => 'An unknown error occurred while trying to validate your response.',
        'timeout-or-duplicate' => 'The request is no longer valid. Please try again.',
    ];

    $errorMessage = $recaptchaErrorMapping[$error];
    echo "Please retry the CAPTCHA: ".$errorMessage;
}

// Everything seems OK, time to send the email.

$mail = new \PHPMailer\PHPMailer\PHPMailer(true);

try {
    //Server settings
    $mail->SMTPDebug = CONTACTFORM_PHPMAILER_DEBUG_LEVEL;
    $mail->isSMTP();
    $mail->Host = CONTACTFORM_SMTP_HOSTNAME;
    $mail->SMTPAuth = true;
    $mail->Username = CONTACTFORM_SMTP_USERNAME;
    $mail->Password = CONTACTFORM_SMTP_PASSWORD;
    $mail->SMTPSecure = CONTACTFORM_SMTP_ENCRYPTION;
    $mail->Port = CONTACTFORM_SMTP_PORT;

    // Recipients
    $mail->setFrom(CONTACTFORM_FROM_ADDRESS, CONTACTFORM_FROM_NAME);
    //$mail->addAddress(CONTACTFORM_TO_ADDRESS, CONTACTFORM_TO_NAME);
    //$mail->addAddress(CONTACTFORM2_TO_ADDRESS, CONTACTFORM2_TO_NAME);
    $mail->addAddress(CONTACTFORM3_TO_ADDRESS, CONTACTFORM3_TO_NAME);
    //$mail->addAddress(CONTACTFORM4_TO_ADDRESS, CONTACTFORM4_TO_NAME);
    //$mail->addReplyTo("marketing@lgp-italia.it");


    // Content
    $mail->Subject = "Appointment at ".$_POST['Field1'];
    $mail->Body    = <<<EOT
    Appointment at:  {$_POST['Field1']},  {$_POST['Field2']}
    {$_POST['Field3']}
    {$_POST['Field4']}
    {$_POST['Field5']}
    {$_POST['Field6']}
    {$_POST['Field7']}

EOT;

    $mail->send();
    
} catch (Exception $e) {
    echo "An error occurred while trying to send your message: ". $mail->ErrorInfo;
}

    



Code of appointment.php

<?php

if (isset($_POST['submit'])) {

    require "../../../security/config.php";
    require "../../../security/common.php";

    try  {
        $connection = new PDO($dsn, $username, $password, $options);
       
            $new_call = array(
                "Field1"  => $_POST['Field1'],
                 [...]
            );

        echo var_dump("1");

        $sql = sprintf(
                "INSERT INTO %s (%s) values (%s)",
                "db.appointments",
                implode(", ", array_keys($new_call)),
                ":" . implode(", :", array_keys($new_call))
        );

        echo var_dump("2");
        
        $statement = $connection->prepare($sql);
        $statement->execute($new_call);

        echo var_dump("3");

    } catch(PDOException $error) {
        echo $sql . "<br>" . $error->getMessage();
    }

    echo var_dump("4");
}
    echo var_dump("5");
?>

  • Did you add jquery in your code ? – John Doe May 17 '21 at 09:19
  • The whole code is up there, also I'm not very familiar with it. – gigiopasticcio May 17 '21 at 09:21
  • Add this some where at the top and then test it – John Doe May 17 '21 at 09:22
  • Nothing happens, as the page just reloads and nothing changes. – gigiopasticcio May 17 '21 at 09:26
  • Edit your question and show me what you have updated. – John Doe May 17 '21 at 09:28
  • I've edited the code. – gigiopasticcio May 17 '21 at 09:32
  • 1
    Instead of two AJAX requests, why not send the data to one PHP script which does both jobs? That would make more sense. Also `async: false` is deprecated, you really should not be using it, it is well known to create a horrible user experience. – ADyson May 17 '21 at 09:33
  • before "code, add https:// – John Doe May 17 '21 at 09:33
  • Now my page says: The form must be submitted with POST data. – gigiopasticcio May 17 '21 at 09:36
  • 1
    Also why are you doing an AJAX and then redirecting to the same page? That makes no sense. The whole point of using AJAX is to avoid doing any reloads, refreshes, redirects or anything like that, and just allow the user to remain on the same page. If you're just going to redirect to the page after you've AJAX'd it, you might as well have just POST-ed the form to that page in the first place, and not bother with AJAX. – ADyson May 17 '21 at 09:36
  • 1
    Also, it's unclear - is the code you've shown us in the question part of "submit.php", or another page? – ADyson May 17 '21 at 09:37
  • What have you tried to resolve the problem? Where are you stuck? – Nico Haase May 17 '21 at 09:38
  • The code is the whole page "index.php", that sends data in the form to submit.php. In appointment.php I put a simple INSERT script to add the data in a table. – gigiopasticcio May 17 '21 at 09:39
  • `In appointment.php I put a simple INSERT script to add the data in a table` ...so why not just `require` that from the `submit.php` script, instead of sending a separate AJAX to it? – ADyson May 17 '21 at 09:40
  • `I want to stay on index.php when I click 'Send Email'**` ...don't redirect to submit.php after the AJAX finished, then – ADyson May 17 '21 at 09:44
  • 1
    Re your edits: There should be no need to do **any** kind of redirect. That's the **whole point** of using AJAX. Why not just remove that `window.location.href` line entirely? And `window.open("index.php");` makes **no** sense. Why did you change that? Do some **thinking** about the code instead of guessing. Also if you don't want that window to open at all then you need to look back at what I said [here](https://stackoverflow.com/questions/67566986/send-email-and-insert-from-the-same-form#comment119427526_67566986) – ADyson May 17 '21 at 09:47
  • You probably want to do _something_ when the AJAX request ends though, like display an acknowledgement message to the user, so they know it submitted ok. So I wouldn't remove the entire "success" block, just alter it. You're still guessing, aren't you? Maybe you need to take a step back and actually familiarise yourself with how AJAX works through some tutorials and practice, rather than just blundering about hoping you'll eventually find the magic combination of code to make it work. – ADyson May 17 '21 at 09:50
  • Yeah I'm not familiar with it, I'm just kind in a "hurry" let's say. Do you think that the method of requiring appointment.php in submit.php would be easier to do? – gigiopasticcio May 17 '21 at 09:53
  • Also for now I just want this to work. Send the email and simultaneously add the data into a table. Then I can work on how to display to the user the success of the work. – gigiopasticcio May 17 '21 at 09:55
  • `Do you think that the method of requiring appointment.php in submit.php would be easier to do` it should be easier, and also it removes the need to open another window or send a second request. I can't tell you **exactly** what to do though, because we can't see the code of submit.php or appointment.php here. – ADyson May 17 '21 at 09:55
  • I've added those 2 pages. – gigiopasticcio May 17 '21 at 10:05
  • You need to remove all the HTML from appointment.php, but other than that you ought to be able to just `require` it from submit.php. You might want to set a variable which shows if the insert succeeded, then you can use that in the response back to the AJAX request, so it can tell if each part (insert into DB and sending email) was successful, or if any part failed. – ADyson May 17 '21 at 10:07
  • Okay so I've edited appointment.php (took out html) and submit.php (added require appointment.php).Do I really need the ajax request now? Because the button needs to run submit.php and no other pages now. – gigiopasticcio May 17 '21 at 10:14
  • You shouldn't need the second AJAX call which sends to appointment.php, no. – ADyson May 17 '21 at 10:17
  • BTW `if (isset($_POST['submit']))` in appointment.php probably isn't going to return true, because there's no "submit" field in your form. You might want to test another field instead, or just test whether it's a POST request generally – ADyson May 17 '21 at 10:19
  • Done that too but it still doesn't do anything. – gigiopasticcio May 17 '21 at 10:20
  • `$( "#submit-form" ).click(function() { $( "#target" ).submit(); });` is redundant, you don't need that. – ADyson May 17 '21 at 10:20
  • `Done that` ...done what, exactly? – ADyson May 17 '21 at 10:20
  • Also `$('form').submit(function() { $.ajax...` needs to be `$('form').submit(function(event) { event.preventDefault(); $.ajax...` because otherwise it won't prevent the standard postback (and that means the AJAX won't run properly, it will just submit the form back to index.php instead). https://api.jquery.com/event.preventdefault/ – ADyson May 17 '21 at 10:23
  • Took out the second ajax request and added the event.preventDefault(); part – gigiopasticcio May 17 '21 at 10:25
  • Ok good. You should be getting somewhere now. Watch your browser's Console and Network tools to spot any problems while you run it, and also ensure you've got PHP and PDO error logging switched on so you can see PHP and SQL errors in the log file, if they occur. – ADyson May 17 '21 at 10:29
  • It gives me: Uncaught SyntaxError: Unexpected token ';' . Also I can see from the network panel that it doesn't arrive to the point of opening submit.php – gigiopasticcio May 17 '21 at 10:43
  • Remove the `;` from the end of `$( this ).serialize();` – ADyson May 17 '21 at 10:45
  • Also as I mentioned much earlier, please remove `async: false,`, it's unnecessary and detrimental. – ADyson May 17 '21 at 10:48
  • Removed the ; and async:false but the buttons now seem stuck, I can't click them – gigiopasticcio May 17 '21 at 10:51
  • Not clear what "stuck" means exactly? Have you opened the debugging tools as I mentioned? Any feedback from those? – ADyson May 17 '21 at 10:51
  • It means that I click on them, but nothing happens. Also it seems strange to say that but I'll be back in an hour – gigiopasticcio May 17 '21 at 10:55
  • Like I said you need to debug with the browser tools – ADyson May 17 '21 at 11:49
  • I made a demo of your client-side code: https://jsfiddle.net/7h9eaw86/ . If you watch the network tool there you'll see it sends the AJAX request correctly. If something is failing on the PHP side in your version, you might see some feedback in the "response" tab of the AJAX request in the Network tool, and/or in the PHP error log (assuming you configured it properly as I advised earlier). You might also find http://www.phpknowhow.com/basics/basic-debugging/ useful. – ADyson May 17 '21 at 11:52
  • Now when I click the button nothing shows up like before, so I don't have 'Message sent successfully' coming out, but for now it's not a problem. The mail is sent and received, but nothing is added to the table in the db. – gigiopasticcio May 17 '21 at 12:26
  • `nothing shows up like before` ...because you're not running that code. `Message sent successfully` is part of index.php, but you're not executing index.php, you're executing submit.php. Any output you want to see needs to be a) output from submit.php, and b) captured in your AJAX "success" function and then displayed as appropriate using some Javascript code. That's how AJAX works. – ADyson May 17 '21 at 12:30
  • `nothing is added to the table in the db`...ok and what have you done to try and debug that? Did you make the change I suggested [here](https://stackoverflow.com/questions/67566986/send-email-and-insert-from-the-same-form?noredirect=1#comment119428539_67566986), and also switch on PHP and PDO error logging, before testing it? (Guidance on the setting up the logging can be found [here](https://stackify.com/php-error-logs-guide/) (PHP logs) and [here](https://www.php.net/manual/en/pdo.error-handling.php) (PDO errors) – ADyson May 17 '21 at 12:30
  • I'm trying to find a way to debug and see where it stops – gigiopasticcio May 17 '21 at 12:37
  • Also I don't know what redirectWithError() and redirectSuccess() do, but it sounds like they probably try to do a redirect, which won't work in an AJAX context. To adapt this for AJAX usage you need to remove any redirects, and just output any feedback messages directly back to the AJAX code using `echo`. – ADyson May 17 '21 at 12:39
  • But this would solve the problems of giving me errors when sending the email and not when inserting into the db. – gigiopasticcio May 17 '21 at 13:03
  • why? You're inserting into the DB in the same script now (via the require) - so any DB errors, you can echo them in appointment.php and they would be combined with the output from submit.php. It would solve both. It really seems you lack some basic knowledge here, both PHP and JavaScript, and maybe the web in general – ADyson May 17 '21 at 13:09
  • So I just replace the redirectWithError() and redirectSuccess() with echo? Also yes I do lack the basis I know, the learning at school wasn't really enough – gigiopasticcio May 17 '21 at 13:24
  • Maybe you should do some more tutorials etc then. Anyway for now yes just replace those with an echo or two, to explain the situation to the user. Even if you don't then implement anything in the "success" bit of AJAX yet, you will at least be able to see that output in the Response section of the request in your browser's Network tool, which can help with debugging. – ADyson May 17 '21 at 13:26
  • I've added the echo in those parts, now I'm checking in the response section but it says Failed to Load Response Data – gigiopasticcio May 17 '21 at 14:25
  • what HTTP status did you get? There are a few things online about that error already, maybe one of them applies to you: https://www.google.com/search?q=failed+to+load+response+data . https://stackoverflow.com/questions/38924798/chrome-dev-tools-fails-to-show-response-even-the-content-returned-has-header-con looks promising, but there are others too. – ADyson May 17 '21 at 14:49
  • I'll check them now. The status it gives me on submit.php is 302 FOUND, while on index.php it gives me 200 OK – gigiopasticcio May 17 '21 at 15:16
  • 302 FOUND is a response code you get when the server is trying to tell the browser to redirect. Looks like you didn't remove all the redirects from the PHP. – ADyson May 17 '21 at 15:17
  • I saw that I didn't remove redirectSuccess();, but as I took it out when I click submit it goes on 'Pending'. Nevermind, now everything went through – gigiopasticcio May 17 '21 at 15:20
  • The email got sent, I still don't have anything in the response panel but now the status is 200 OK – gigiopasticcio May 17 '21 at 15:24
  • You won't get anything in the response panel unless you echo something from submit or appointment – ADyson May 17 '21 at 15:30
  • I've added to appointment echo var_dump($new_call); but I still don't have anything as a response – gigiopasticcio May 17 '21 at 15:33
  • Maybe that line doesn't get executed then? You said it still wasn't writing to the DB. Add some more var_dump statements in other places as debugging, so you can see which paths the code does and doesn't take. – ADyson May 17 '21 at 15:35
  • I've added it like 5 times in different part of the code and now I have a response but it gives me NULL – gigiopasticcio May 17 '21 at 15:38
  • Well it'll obviously be NULL if you put it in a place where $new_call doesn't exist! Better to make it output some unique text which indicates which place in the code it has passed. Can be as simple as `var_dump("here 1");` in one place and `var_dump("here 2");` in another, etc. so you can tell them apart. Not sure how you expect to work out what's going on if they all try to output the same thing, or try to output things which won't exist in that section of the code? You do need to put a little bit of thought into this, please...being a beginner isn't an excuse for not applying basic logic. – ADyson May 17 '21 at 15:40
  • I added the var dump before only after creating $new_call obviously, just in 5 different places below its creation. Now I have as a response 5, so I know it gets the var_dump from the last line of code – gigiopasticcio May 17 '21 at 15:46
  • But there's only one place after it's creation where it would be valid - the line immediately afterwards. Once you get out of the `try` block it would be out of scope. – ADyson May 17 '21 at 15:50
  • Anyway if you want me to help with interpreting your results you're going to have to show where you've put the dumps, and exactly which responses you get, and ensure I'm looking at the latest version of your code. (Just because it gets to the end doesn't mean it passes through all of the places in between which you wanted to.) – ADyson May 17 '21 at 15:51
  • Is that really your latest code? You haven't removed any of the redirects? I can see the dumps in appointment.php though...if you're only seeing "5" out of all of those, then pay attention to this earlier comment I made: https://stackoverflow.com/questions/67566986/send-email-and-insert-from-the-same-form?noredirect=1#comment119428539_67566986 – ADyson May 17 '21 at 15:56
  • I've uploaded the latest version of appointments.php, although I'll be able to work on it only tomorrow – gigiopasticcio May 17 '21 at 15:56
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/232524/discussion-between-adyson-and-gigiopasticcio). – ADyson May 17 '21 at 16:04

0 Answers0