Nikola Marinov
Nikola Marinov

Reputation: 263

Prevent redirect PHP form

Here I am using a contact form. When I click on the submit button instead of displaying "message sent successfully" on the same page, it redirects to blank page. My HTML form

<!-- form element -->
<div class="row">
    <div class="col-md-6 form-group">
        <input name="name" type="text" class="form-control" placeholder="Name" required>
    </div>
    <div class="col-md-6 form-group">
        <input name="email" type="email" class="form-control" placeholder="Email" required>
    </div>
    <div class="col-md-6 form-group">
        <input name="subject" type="text" class="form-control" placeholder="Subject" required>
    </div>
    <div class="col-12 form-group">
        <textarea name="message" class="form-control" rows="3" placeholder="Message" required></textarea>
    </div>
    <div class="col-12">
        <input n id="btnClick" type="submit" class="btn btn-success" value="Send Message">
    </div>
</div>
<!-- end form element -->

My JavaScript code:

$('#btnClick').on('click', function(e){
   e.preventDefault();

   var name = $('input#name').val(),
       email = $('input#email').val(),
       message = $('textarea#message').val(),
       subject = $('input#subject').val()
       formData = 'name=' + name + '&email=' + email + '&message=' + message + '&subject=' +  subject;

    $.ajax({
      type: 'post',
      url: 'mail.php',
      data: formData,
      success: function(results) {
        $('ul#msgSubmit').html(results);
      }
    });
});

And my php code:

<?php

    if ($_SERVER["REQUEST_METHOD"] == "POST") {

        # FIX: Replace this email with recipient email
        $mail_to = ""; // my email here
        
        # Sender Data
        $subject = trim($_POST["subject"]);
        $name = str_replace(array("\r","\n"),array(" "," ") , strip_tags(trim($_POST["name"])));
        $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
        $message = trim($_POST["message"]);
        
        if ( empty($name) OR !filter_var($email, FILTER_VALIDATE_EMAIL) OR empty($subject) OR empty($message)) {
            # Set a 400 (bad request) response code and exit.
            http_response_code(400);
            echo "Please complete the form and try again.";
            exit;
        }
        
        # Mail Content
        $content = "Name: $name\n";
        $content .= "Email: $email\n\n";
        $content .= "Message:\n$message\n";

        # email headers.
        $headers = "From: $name <$email>";
    $headers .= 'MIME-Version: 1.0' ."\r\n";
    $headers .= 'Content-Type: text/HTML; charset=utf-8' . "\r\n";
    $headers .= 'Content-Transfer-Encoding: 8bit'. "\n\r\n";
    $headers .= $text . "\r\n";


        # Send the email.
        $success = mail($mail_to, $subject, $content, $headers);
        if ($success) {
            # Set a 200 (okay) response code.
            http_response_code(200);
            echo "Thank You! Your message has been sent.";
        } else {
            # Set a 500 (internal server error) response code.
            http_response_code(500);
            echo "Oops! Something went wrong, we couldn't send your message.";
        }

    } 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.";
    }

?>

I tried everything change **<input type="submit" to button** Use ajax **e.preventDefault();** and again it redicted me to new page mywebsite.eu/assets/js/mail.php I dont know how to fix it.

Upvotes: 0

Views: 1303

Answers (2)

Dayachand Patel
Dayachand Patel

Reputation: 497

You only need to change the button type from submit to button as below:-

<input id="btnClick" type="button" class="btn btn-success" value="Send Message">

Upvotes: 2

Saud
Saud

Reputation: 878

There are several things you can do to stop redirecting the page.

  • Change input type from submit to button.
  • Replace input element to html's button element with type="button".
  • Wrap your whole JavaScript event handler code into a function and call it on the html event attribute like this: onsubmit="return foo();".

In my humble opinion, you can do something like this:

HTML:

<form action="mail.php" method="POST" onsubmit="return foo(this);">
    <input type="text" name="full_name" value="" required>
    <button type="submit">submit form</button>
</form>

JavaScript:

function foo(form){
    $.ajax({
        url: $(form).attr('action'),
        type: 'POST',
        data: $(form).serialize(),
        success: (res)=>{
            // success...
            console.log(res);
        },
        error: (err)=>{
            // error...
            console.error(err);
        },
        complete: ()=>{
            // something here...
        }
    });

    return false;
}

This way if somehow your js stops working, your form will still post with php, because of that action you defined in your form.

Upvotes: 1

Related Questions