1

Hey guys I am creating a newsletter sign-up form and trying to submit it with AJAX..

Here is my form:

<div id="form-content">
  <form method="POST" id="news-form" name="newsletter">
     <div class="bd-input-2 form-group">
        <input type="email" name="newsletter_email" placeholder="Enter your email address" required />
     </div>             
     <div class="form-group">
        <button type="submit" name="newsletter">Submit</button>
     </div>
   </form>
</div>

And this one is my JS file in same page as form:

$('#news-form').submit(function(e){     
    e.preventDefault();
    $.ajax({
        url: 'newsletter-submit.php',
        type: 'POST',
        data: $(this).serialize()
    })
    .done(function(data){
        $('#form-content').fadeOut('slow', function(){
            $('#form-content').fadeIn('slow').html(data);
            console.log(data);
        });
    })
    .fail(function(){
        alert('Ajax Submit Failed ...');    
    });
});

On console nothing is displaying not even an error just an empty line.

And my newsletter-submit.php file :

<?php
if(isset($_POST['newsletter'])){
    $newsletter_email = filter_var($_POST['newsletter_email'],FILTER_VALIDATE_EMAIL);    
    if(filter_var($newsletter_email, FILTER_VALIDATE_EMAIL)){
        $newsletter_email = filter_var($newsletter_email, FILTER_VALIDATE_EMAIL);
        $em_check = sqlsrv_query($con, "SELECT email FROM newsletter_signups WHERE email='$newsletter_email'",array(), array("Scrollable"=>"buffered"));
        $num_rows = sqlsrv_num_rows($em_check); 
        if($num_rows > 0){
            echo "<br/><p style='color: #fff;'>Email exist in our newsletter list.</p>";
        }else{
            $query = "INSERT INTO newsletter_signups (email) VALUES ('{$newsletter_email}')";
            $insert_newsletter_query = sqlsrv_query($con,$query);
            echo '<br/><p style="color: green;">Thank you for sign up in our newsletter</p>';
        }
    }
}
?>

But if I add any code after php tags e.g Hello world that is displayed after the submission.

My php code was working before AJAX file

10

1 Answer 1

3

Your input field is named newsletter_email and in your php you are checking for isset($_POST['newsletter']) which is always false.

Sign up to request clarification or add additional context in comments.

1 Comment

@Maria To avoid this implement the else's , because you will get another empty response if filter_var($newsletter_email, FILTER_VALIDATE_EMAIL) returns false

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.