Aaron Prowse
Aaron Prowse

Reputation: 47

HTML Form using Ajax and PHP not working

Just wondering if anyone can give me a hand?

I am trying to learn bits of Ajax (this language is so confusing) and I am discovering problems its like the script is being totally ignored or maybe im just making a massive amateur mistake.

Before I display code I tried to make a Jsfiddle but it doesn't allow a PHP file.

Html:

<form  method="post" action="email.php">
        <label for="name">Name</label>
         <input class="form-control" type="text" id="name" name="name" placeholder="Name">
         <label for="email">Email Address</label>
    <input class="form-control" type="email" id="email" name="email" placeholder="Email Address">
    <label for="phone">Phone Number</label>
    <input class="form-control" type="phone" id="phone" name="phone" placeholder="Phone Number">
    <label for="message">Message</label>
    <textarea placeholder="Message" name="comments" id="comments" class="form-control" rows="5"></textarea>
    <button type="submit" id="submit_button" class="btn btn-lg btn-success">Send</button>
    </form>

PHP (email.php):

<?php
if(isset($_POST['email'])) {

$name = $_POST['name']; // required
$email_from = $_POST['email']; // required
$phone = $_POST['phone']; // not required
$comments = $_POST['comments']; // required

// EDIT THE 2 LINES BELOW AS REQUIRED
$email_to = "[email protected]";
//$email_also ="[email protected]";
$email_subject = $name . " Website Inquiry";

function clean_string($string) {
  $bad = array("content-type","bcc:","to:","cc:","href");
  return str_replace($bad,"",$string);
}

$email_message .= "First Name: ".clean_string($name)."\n";
$email_message .= "Email: ".clean_string($email_from)."\n";
$email_message .= "Phone: ".clean_string($phone)."\n";
$email_message .= "Comments: ".clean_string($comments)."\n";


// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
@mail($email_to, $email_subject, $email_message, $headers);
//@mail($email_also, $email_subject, $email_message, $headers);
?>
<!-- include your own success html here -->
<!--Thank you for contacting us. We will be in touch with you very soon.
<?php
}
?>

Ajax:

<script type="text/javascript">
$(document).ready(function() {  
$("#submit_button").click, (function() {
// Get all of the values from the input fields through their ID's
var name = $("#name").val();
var email = $("#email").val();
var phone = $("#phone").val();
var comments = $("#comments").val();

// Validate the form to make sure that all of the required fields are not left empty
if(first_name != ''
&& email != ''
&& comments != '')
{
   $.ajax({
      url: "email.php",
      type: "POST",
      data: ({
           first_name: name,
           email: email,
           phone: phone,
           comments: comments
       }),
      success: function(data) 
      {
      alert("Message has been received");// You might want to display a message telling the user that the form was successfully filled out.
      }
  });
}

if(name == ''
|| email == ''
|| comments == '')
{
    alert("You left one of the required fields empty");
}
});
});
</script>

The end goal is to make a php form that runs inline on a document so no page refreshes

If anyone can help it will be much appreciated.

Upvotes: 1

Views: 582

Answers (3)

AiApaec
AiApaec

Reputation: 660

If you have a submit button(type="submit") and action="pageUrl" in the form, when you click that button will redirect to pageUrl. You can cancel the postback produced when submit button is clicked:

<script type="text/javascript">
$("#submit_button").click(function(event) {
    event.preventDefault(); //cancel postback
    // Get all of the values from the input fields through their ID's
    var name = $("#name").val();
    var email = $("#email").val();
    var phone = $("#phone").val();
    var comments = $("#comments").val();
    if(name != '' && email != '' && comments != '')
    {
        var postData = {
                       first_name: name,
                       email: email,
                       phone: phone,
                       comments: comments
                      };

        //ajax:
        $.post("email.php", data: postData, function(response){
            alert("Message from email.php: " + response);
        });
    }
    else
    {
    alert("You left one of the required fields empty");
    }   
});
</script>

Or using ajax() function:

<script type="text/javascript">
$(document).ready(function() {  
    $("#submit_button").click(function(event) {
        event.preventDefault();//cancel postback
        // Get all of the values from the input fields through their ID's
        var name = $("#name").val();
        var email = $("#email").val();
        var phone = $("#phone").val();
        var comments = $("#comments").val();

        // Validate the form to make sure that all of the required fields are not left empty
        //if(first_name != '' <-- ERROR: variable does not exist.
        if(name != '' && email != '' && comments != '')
        {
           $.ajax({
              url: "email.php",
              type: "POST",
              data: {
                   first_name: name,
                   email: email,
                   phone: phone,
                   comments: comments
               },
              success: function(data) 
              {
                // You might want to display a message telling 
                //the user that the form was successfully filled out.
                alert("Message has been received");
              }
          });
        }
        else
        {
        alert("You left one of the required fields empty");
        }    
    });//click()
});//ready()
</script>

Upvotes: 1

american-ninja-warrior
american-ninja-warrior

Reputation: 8235

After applying @magnified 's answer, it will still redirect to the email.php as a page when submit button is clicked...

Here's the fix. This line

$("#submit_button").click, (function() {

should be like this

$("#submit_button").click(function() {

The comma probably came in as a typo probably. Also, since you're using ajax to submit the form,

<form  method="post" action="email.php">

should be

<form>

and

<button type="submit" id="submit_button"

should be

<button id="submit_button"

Upvotes: 1

magnified
magnified

Reputation: 78

You don't have a "name" attribute on your comments textarea input. Give that a try. I don't believe POST will pick it up if you don't use the name attribute.

Also, change this section

$email_subject = $name + " Website Inquiry";

to this...

$email_subject = $name . " Website Inquiry";

PHP concatenates strings using the . javascript uses a +

Upvotes: 1

Related Questions