error in ajax response if condition error

I want to show error ie. Email already exists in database. If not show Thank you message.

I’m using ajax and jquery for this. Here is my code:
Ajax jquery:

<script type="text/javascript" >
$(function() {
    var val_holder;
    $("#subscribe").click(function() {
        val_holder      = 0;
        var subscribe_mail       = jQuery.trim($("#subscribe_mail").val()); // email field
        var email_regex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}$/;

        if(subscribe_mail == "") {
            $(".error_message").html("This field is empty.");
            val_holder = 1;
        }
        if(subscribe_mail != "") {
            if(!email_regex.test(subscribe_mail)){ // if invalid email
                $(".error_message").html("Your email is invalid.");
                val_holder = 1;
            }
        }
        if(val_holder == 1) {
            return false;
        }
        val_holder = 0;
        var dataString = '&subscribe_mail=' + subscribe_mail;

        $.ajax({
            type: "POST",
            url: "ajax_subscribe.php",
            data: dataString,
            datatype: "json",
            success: function(response) {
                console.log(response);
                if(response!= '')
                {
                    $('.error_message').html(subscribe_mail + ' is already Exists.');
                    return true;

                } else {
                    $('.error_message').html('Thanks For subscription!');
                    return false;
                }
            }
        });
        $("#subscribe_form")[0].reset();
        return false;
    });
});

And php file code is:

<?php error_reporting('E_ALL ^ E_NOTICE'); include('config.php');if($_POST) {   $subscribe_mail = $_POST['subscribe_mail'];
$date = date('Y-m-d');

$q = mysql_query("select * from signups where signup_email_address='".$subscribe_mail."' ") or die(mysql_error());
$n = mysql_fetch_row($q);
if( $n>0 )
{
    echo 'Already Exists';
}
else
{
    $insert = mysql_query("insert into signups(signup_email_address,signup_date) values('$subscribe_mail','$date')") or die(mysql_error());

    $from = 'sunshine.kapoor270@gmail.com';
    $to = $subscribe_mail;   
    $headers  = 'MIME-Version: 1.0' . "rn";
    $headers .= "From: " . $from . "rn"; // Sender's E-mail
    $headers .= "Reply-to: " . $from . "rn";
    $headers .= "Return-Path: $fromn";
    $headers .= 'Content-type: text/html; charset=iso-8859-1' . "rn";

    $subject = "Thanks for Subscription";  
    $message = "Subscription email id : ".$subscribe_mail." ";     

    $sentmail = mail($to,$subject,$message,$headers);
    $sentmail = mail($from,$subject,$message,$headers);
} } ?>

Only
if(response!= ''){$('.error_message').html(subscribe_mail + ' is already Exists.'); return true; }
this condition is working. its not going to else part if response is blank.


Source: jquery

Leave a Reply