AJAX form submission problem

Hello everyone,

I have an email sign up section on my index page. I have figured it all out except the validation and ajax part. When I submit the email it saves it to database and send me an email. But it displays simple success message. What I want to do is to validate the email address and and upon submission only refresh the form itself. The tricky part for me is I want to display any error or success message inside the input field itself. Simply because if I display it above or beneath the input field it messes up the layout of the page. I shot a screenshot here: http://i.imgur.com/14BXzil.png

Any help is greatly appreciated on how to construct this function. Many thanks to you´all.

Hi,

What code do you currently have to handle the form submission?

Hi,

My code is below.

<?php
    
    require_once("database.php");
    
    $_MY_EMAIL_ADDRESS="...@gmail.com";
    
    $output["success"]=false;
    $output["message"]="Nothing processed!";
    
    if(!isset($_POST)){
        $output["success"]=false;
        $output["message"]="Invalid Request";
        goto end;
    }
    
    $sql="";
    $table="";
    
    if(isset($_POST)){
        $table="newsletter";
        $sql="INSERT INTO newsletter(
            newsletter_sub
        )VALUES(
        '{$_POST["newsletter-email"]}'
        )";
    }

    $result_set=$database->query($sql);
    if($result_set!==false){
        send_mail($table, $database->insert_id());
        $output["success"]=TRUE;
        $output["message"]="Your contact request has been successfully submitted";
    }else{
        $output["success"]=false;
        $output["message"]="Sorry, there was an error while processing your request.";
    }
    
    end:
    echo json_encode($output);
    
    
    function send_mail($table,$id){
        global $database;
        global $_MY_EMAIL_ADDRESS;
        $sql="SELECT * FROM {$table} WHERE id={$id}";
        $table="";
        $result_set=$database->query($sql);
        if($result_set===false || $database->num_rows($result_set)==0)
            return false;
        $row=$database->fetch_array($result_set);
        if($table=="newsletter"){
            $table="
                <table>
                    <tbody>
                        <tr>
                            <td>EMAIL</td>
                            <td>{$row["person_email"]}</td>
                        </tr>
                    </tbody>
                </table>
                        ";
        }
        $subject="Newsletter Subscriber @ ";
        $body="
        <html>
            <body>
                $table
            </body>
        </html>
        ";
        $headers = "MIME-Version: 1.0" . "\r\n" .
                   "Content-type: text/html; charset=UTF-8" . "\r\n";
        return mail($_MY_EMAIL_ADDRESS,$subject,$body,$headers); 
    }
    
?>

Sorry, I meant on the client - the Ajax routine.
Also, I removed your email address from your code - it’s not a good idea to post that in plain text.

I have tried couple of scripts but none of them worked as I expected, as you can tell I am not very savvy on JS. I was wondering what would be the best way to construct such functionality. I found most tutorials either incomplete or confusing.

P.S Thanks for removing my email :smile:

Well, you have a form that accepts an email address.
The user enters something and you validate it.
If the user’s input doesn’t validate, then display an error message.
If the input does validate, submit the details via Ajax and process them on the server.

I am presuming you have all of this working.

You can do this in a success callback in your Ajax function:

$.ajax({
  url: '/path/to/file',
  type: 'POST',
  data: {param1: 'value1'},
  success: function(){
    $("form input[type=text]").val("");
  }
});

Is this the kind of thing you mean?

Yes sort of. I use your code and tried it on localhost but I still did not get the result I want. It proceeded to the blank thank you page as before.

Can you post the HTML/JS you have for the form?

My HTML is this:

                <form id="newsletter" action="scripts/ebulten.php" method="POST" name="ebulten"> <!--NEWSLETTER SUBSCRIPTION-->
                      <div class="row"> 
                      <div class="small-12 columns"> 

                      <div class="small-1 columns zero-pad"> 
                        <label for="signup-input" class="right inline newsletter-label">Email:</label> 
                      </div> 
                      <div class="small-8 columns"> 
                        <input name="newsletter-email" id="newsletter-email" type="text" id="signup-input" placeholder="Please enter your email address." > 
                      </div> 
                      <div class="small-3 columns left zero-pad">
                        <input type="submit" class="button round button-newsletter" value="SEND">
                      </div>   

                      </div> 
                      </div> 
                </form>

I don´t have any JS as it directly submits the information upon submission. PHP script I have sent previously does the emailing and DB registry.

Ah ha! This was the missing piece of the puzzle.

Well, here’s a simple example to demonstrate the concept:

index.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Document</title>
  </head>
  <body>
    <form>
      Enter email: <input type="email" id="email" />
      <button>Send</button>
    </form>
    <p id="response"></p>

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script>
      $("form").on("submit", function(e){
        e.preventDefault();
        var email = $("#email").val();
        $.ajax({
          url: 'submit.php',
          type: 'POST',
          data: {email: email},
          success: function(res){
            console.log(res);
            $("#response").html("The server received: " + res);
            $("form input[type=email]").val("");
          }
        });
      });
    </script>
  </body>
</html>

submit.php:

<?php
$email = filter_var($_POST['email'], FILTER_SANITIZE_STRING);
echo $email;

This should do what you want. It assumes that both files are in the same folder on your server.

Hi,

Thanks for taking time to response. I have tried it and it works on local host, on live server however, it did not work. Since local host cannot send email, I have received a PHP error inside the p tag but it shows it that is working. The id for the email field is not email but “newsletter-email” so I have changed the “data: {email: email}” to “data: {newsletter-email: email},” also appended the PHP you have sent me to my own PHP script. It is really frustrating. I need to pick up on JS asap… :S

No probs : )
It was only meant to demonstrate the concept, not as a drop in replacement.
Let me know if you get stuck.

So did I change it correctly? This is what I have:

<script>
      $("form").on("submit", function(e){
        e.preventDefault();
        var newsletter-email = $("#newsletter-email").val();
        $.ajax({
          url: 'scripts/ebulten.php',
          type: 'POST',
          data: {newsletter-email: email},
          success: function(res){
            console.log(res);
            $("#response").html("The server received: " + res);
            $("form input[type=email]").val("");
          }
        });
      });
</script>

If you kept the HTML otherwise the same, that seems like it should work.

You don’t actually need the console.log() statement (but it is useful for debugging).

Ok many thanks…

Shouldn’t

data: {newsletter-email: email},

just be

data: newsletter-email,

?

Hello donboe,

I have stripped the curly braces but still no luck. I am about to lose my mind. Would you please look at my code and tell what I am doing wrong? I keep getting a blank page with success message but PHP takes over once I hit the submit button.

Try this:

var email = $("#newsletter-email").val();
     data = 'email='+ email;

and then in your AJAX call

data: data,

Maybe not the best way and probably fretburner, Pullo or Paul Wilkins have way better sollutions, but give it a try

I really appreciate the answers. As you may have guessed, I’ve tried it but no luck. I’m certain that there is something wrong with my PHP script but everything seems ok !!!

Hey donboe,

Nah, data can be an object literal. That’s fine.
Looking at the code again, though the minus in the variable name is causing the script to break.
It should probably be:

<form>
  Enter email: <input type="email" id="newsletterEmail" />
  <button>Send</button>
</form>
<p id="response"></p>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
  $("form").on("submit", function(e){
    e.preventDefault();
    var newsletterEmail = $("#newsletterEmail").val();
    $.ajax({
      url: 'submit.php',
      type: 'POST',
      data: {email: newsletterEmail},
      success: function(res){
        $("#response").html("The server received: " + res);
        $("form input[type=email]").val("");
      }
    });
  });
</script>