0

So I'm trying to send some information from a contact form via javascript to a php function. Code snippets below:

$(function() {
    // Get the form.
    var form = $('#contact_form');

    // Get the messages div.
    var formMessages = $('#form-messages');

    // Set up an event listener for the contact form.
    $(form).submit(function(event) {

      // Stop the browser from submitting the form.
      event.preventDefault();
      
      // Serialize the form data.
      var formData = $(form).serialize();
      alert($(form).attr('action'));
      // Submit the form using AJAX.
      $.ajax({
          type: 'POST',
          url: $(form).attr('action'),
          data: formData
      })
      
      .done(function(response) {
            // Make sure that the formMessages div has the 'success' class.
            $(formMessages).removeClass('error');
            $(formMessages).addClass('success');

            // Set the message text.
            $(formMessages).text(response);

            // Clear the form.
            $('#name').val('');
            $('#email').val('');
            $('#message').val('');
        })
        
        .fail(function(data) {
            // Make sure that the formMessages div has the 'error' class.
            $(formMessages).removeClass('success');
            $(formMessages).addClass('error');

            // Set the message text.
            if (data.responseText !== '') {
                $(formMessages).text(data.responseText);
            } else {
                $(formMessages).text('Oops! An error occured and your message could not be sent.');
            }
        });
        
    }); 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="contact_form" method="post" class="form" role="form" action="/mailer.php">
    <div class="row">
        <div class="col-md-6 form-group">
            <label for="name"> Your name:</label>
            <input class="form-control" id="name" name="name" placeholder="Name" type="text" required maxlength="50" />
        </div>
        <div class="col-md-6 form-group">
            <label for="email"> Your email address:</label>
            <input class="form-control" id="email" name="email" placeholder="Email" type="email" required maxlength="50" />
        </div>
    </div>
    <div class="form-group">
      <label for="message"> Your message:</label>
      <textarea class="form-control" id="message" name="message" placeholder="Message" maxlength="6000" rows="7" required></textarea>
    </div>
    <br />
    <div class="row">
        <div class="col-md-12">
            <!-- <input type="submit" name="submit" value="Submit">-->
            <button class="btn btn-lg btn-success pull-right" name="submit" type="submit">Submit</button>
        </div>
    </div>
</form>
<div id="form-messages"></div>
<?php

//only process POST 
if(isset($_POST['submit'])){

    // This is in the PHP file and sends a Javascript alert to the client
    $message = "it is a post";
    echo "<script type='text/javascript'>alert('$message');</script>";

    //do something

} 
else {

    // Not a POST request, set a 403 (forbidden) response code.
    http_response_code(403);
    echo "There was a problem with your submission, please try again.";

    // This is in the PHP file and sends a Javascript alert to the client
    $message = "not POST";
    echo "<script type='text/javascript'>alert('$message');</script>";

    if(isset($_GET['submit'])) {
    echo "is GET";}
}?>

When I submit the form I know that the js is working as I get the alert pop up just before the $.ajax({ line.

However, then the php function echos "There was a problem with your submission, please try again." Implying that the sumbit method isn't POST? But then I never see the "is GET" echo...

I've checked chromes developer mode -> network and the form submission does indeed seem to be a POST. So I'm lost as to what could be wrong.

Can anyone help?

Thanks!

Rob
  • 538
  • 2
  • 11
  • If you are going to send javascript to the client to be executed isn't it easier to implement JSONP? https://stackoverflow.com/questions/2067472/what-is-jsonp-all-about – Raymond Nijland Aug 01 '18 at 10:21
  • Is the `submit` button name/value included when serializing the form data like that? Doesn't seem necessary to check for that in the first place. – David Aug 01 '18 at 10:21
  • You can easily debug by `print_r($_POST)` or `print_r($_REQUEST)` at the very first line of your PHP file. Why don't you just let the submit button do its work, i.e. submit the form? – Raptor Aug 01 '18 at 10:27

1 Answers1

1

Implying that the sumbit method isn't POST?

… because it isn't. The serialize method does not include submit buttons. (A submit button is only a successful control when used to a submit a form, and the form isn't being submitted, JavaScript is submitted data read from it instead).

Change your PHP to use some other test to see if form data is being POSTed.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Ahhhh ok, great that makes sense. What would be a sensible thing to check for? – Rob Aug 01 '18 at 10:27
  • The pieces of data that you require be in the POST request. – Quentin Aug 01 '18 at 10:28
  • So I just changed the if statement to: if($_SERVER["REQUEST_METHOD"] == "POST"){ and that seems to be working fine :-) – Rob Aug 01 '18 at 10:46