1

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.

2
  • Why are you using type="email", I never understood these types of things, you'd be better off with type="text" Commented Jul 20, 2014 at 2:04
  • Combine the two answers below and your issues should be resolved. However I would suggest that instead of using a click event on the button please use a submit event on the form: $('form').submit(function(e) { e.preventDefault(); //rest of your cocde }); Commented Jul 20, 2014 at 2:35

3 Answers 3

1

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>
Sign up to request clarification or add additional context in comments.

4 Comments

I tried this but i think because at the moment the ajax is not being called it is not working.
I see you are doing this: data: ({}). That must be: data:{}. I'll update my previous answer.
Still No luck when i hit submit all that happens is the URL updates with this and the page goes to top and no email is passing. (websitename.com/…
I fixed the problem I was calling the Jquery in at the bottom of the page this is why the web browser did not understand jquery lmao.
1

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 +

2 Comments

Brilliant that solves that just need to work out why Ajax won't put an alert back to page without refreshing. At the moment it goes to the email.php as a page when submit button is clicked
it doesn't look like the email.php file actually returns anything. Try adding echo "complete"; to the end of the PHP file and change the alert to alert(data) in the AJAX file to see if that alerts "complete"
1

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"

1 Comment

This has not worked the Ajax has been ignored and messages are no longer being posted to the email.php file. maybe its a problem with the ajax coding?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.