<?php
//email signup ajax call
if($_GET['action'] == 'signup'){

    mysql_connect('localhost','root','');  
    mysql_select_db('newsletter');

    //sanitize data
    $email = mysql_real_escape_string($_POST['signup-email']);

    //validate email address - check if input was empty
    if(empty($email)){
        $status = "error";
        $message = "You did not enter an email address!";
    }
    else if(!preg_match('/^[^\W][a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\@[a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\.[a-zA-Z]{2,4}$/', $email)){ //validate email address - check if is a valid email address
            $status = "error";
            $message = "You have entered an invalid email address!";
    }
    else {
        $existingSignup = mysql_query("SELECT * FROM signups WHERE signup_email_address='$email'");   
        if(mysql_num_rows($existingSignup) < 1){

            $date = date('Y-m-d');
            $time = date('H:i:s');

            $insertSignup = mysql_query("INSERT INTO signups (signup_email_address, signup_date, signup_time) VALUES ('$email','$date','$time')");
            if($insertSignup){ //if insert is successful
                $status = "success";
                $message = "You have been signed up!";  
            }
            else { //if insert fails
                $status = "error";
                $message = "Ooops, Theres been a technical error!"; 
            }
        }
        else { //if already signed up
            $status = "error";
            $message = "This email address has already been registered!";
        }
    }

    //return json response
    $data = array(
        'status' => $status,
        'message' => $message
    );

    echo json_encode($data);
    exit;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ajax &amp; JSON Email Singup Form</title>

<style type="text/css">

/* Qucik and dirty. I normally use a custom css reset and would not advise using the below. But for the purposes of this tutorial it should be fine. */

* { 
    padding:0;
    margin:0;
}

body {
    font-size:12px;
    font-family:Arial, Helvetica, sans-serif;   
}

fieldset {
    border:none;    
}

form {
    width:930px;
    margin:20% auto;    
    padding:15px;
    border:solid 6px #9FCBFF;
    -moz-border-radius:6px;
    -webkit-border-radius:6px;
    border-radius:6px;
}

input {
    border:none;
    background-color:none;  
}

#signup-email {
    border:1px solid #999999;
    color:#9E9E9E;
    padding:5px;
    margin-left:10px;
    margin-right:4px;
}

#signup-email:focus {
    border-color:#9FCBFF;
    background-color:#DFEEFF;
    background-image:none;
    color:#000;
}

#signup-button {
    background-color:#9FCBFF;
    color:#FFF;
    -moz-border-radius:10px;
    -webkit-border-radius:10px;
    border-radius:10px;
    padding:5px;
    text-shadow: 1px 1px 1px #5FA8FF;   
}

#signup-button:hover {
    cursor:pointer;
    background-color:#7FB9FF;
}

#signup-response {
    display:inline;
    margin-left:4px;
    padding-left:20px;
}

.response-waiting {
    background:url("loading.gif") no-repeat;
}

.response-success {
    background:url("tick.png") no-repeat;
}

.response-error {
    background:url("cross.png") no-repeat;
}

</style>

<!-- We will get our jQuery from google -->
<script src="https://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">
    google.load('jquery', '1.4.1');
</script>

<script type="text/javascript">
$(document).ready(function(){
    $('#newsletter-signup').submit(function(){

        //check the form is not currently submitting
        if($(this).data('formstatus') !== 'submitting'){

            //setup variables
            var form = $(this),
                formData = form.serialize(),
                formUrl = form.attr('action'),
                formMethod = form.attr('method'), 
                responseMsg = $('#signup-response');

            //add status data to form
            form.data('formstatus','submitting');

            //show response message - waiting
            responseMsg.hide()
                       .addClass('response-waiting')
                       .text('Please Wait...')
                       .fadeIn(200);

            //send data to server for validation
            $.ajax({
                url: formUrl,
                type: formMethod,
                data: formData,
                success:function(data){

                    //setup variables
                    var responseData = jQuery.parseJSON(data), 
                        klass = '';

                    //response conditional
                    switch(responseData.status){
                        case 'error':
                            klass = 'response-error';
                        break;
                        case 'success':
                            klass = 'response-success';
                        break;  
                    }

                    //show reponse message
                    responseMsg.fadeOut(200,function(){
                        $(this).removeClass('response-waiting')
                               .addClass(klass)
                               .text(responseData.message)
                               .fadeIn(200,function(){
                                   //set timeout to hide response message
                                   setTimeout(function(){
                                       responseMsg.fadeOut(200,function(){
                                           $(this).removeClass(klass);
                                           form.data('formstatus','idle');
                                       });
                                   },3000)
                                });
                    });
                }
            });
        }

        //prevent form from submitting
        return false;
    });
});
</script>
</head>

<body>

<form id="newsletter-signup" action="?action=signup" method="post">
    <fieldset>
        <label for="signup-email">Sign up for email offers, news &amp; events:</label>
        <input type="text" name="signup-email" id="signup-email" />
        <input type="submit" id="signup-button" value="Sign Me Up!" />
        <p id="signup-response"></p>
    </fieldset>
</form>

</body>
</html>

I'm new to php. I was created database
Database name: newsletter
Table name: subscription
Field name: email, date and time.

Please check the following code, It's not insert my database.

Thanking you,

Member Avatar for LastMitch

@brave_demo

Please check the following code, It's not insert my database.

I don't check codes. You need to understand why it's not INSERT.

Add this or die(mysql_error()); to line 22

if(mysql_num_rows($existingSignup) or die(mysql_error());

What error did you get when you ran your code again?

If it's blank then it means you are connected to the DB. If it's there's error then post it.

I'm new to php.

Read more about it here a intro:

http://www.w3schools.com/php/php_mysql_intro.asp

Read and try to understand it here:

http://www.freewebmasterhelp.com/tutorials/phpmysql

Hi LastMitch,

Thanking you for your earlier response. You are right, but it's given at 5th line [die(mysql_error())] and I was mistaken given table name also. Now it's everything fine.

I have two more questions:

1.Time details getting not properly.
2.I'm getting message email id inserted successfully, the value still the input field. How can i clear the input field once it's getting done.

Database details like below:
P_Id | signup_email_address | signup_date | signup_time
1 aa@gmail.com  2013-01-08  0000-00-00 00:00:00

For your reference PHP code:

    <?php
    //email signup ajax call
    if($_GET['action'] == 'signup'){

        mysql_connect('localhost','root','') or die(mysql_error());  
        mysql_select_db('newsletter');

        //sanitize data
        $email = mysql_real_escape_string($_POST['signup-email']);

        //validate email address - check if input was empty
        if(empty($email)){
            $status = "error";
            $message = "You did not enter an email address!";
        }
        else if(!preg_match('/^[^\W][a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\@[a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\.[a-zA-Z]{2,4}$/', $email)){ //validate email address - check if is a valid email address
                $status = "error";
                $message = "You have entered an invalid email address!";
        }
        else {
            $existingSignup = mysql_query("SELECT * FROM subscription WHERE signup_email_address='$email'");   
            if(mysql_num_rows($existingSignup) < 1){

                $date = date('Y-m-d');
                $time = date('H:i:s');

                $insertSignup = mysql_query("INSERT INTO subscription (signup_email_address, signup_date, signup_time) VALUES ('$email','$date','$time')");
                if($insertSignup){ //if insert is successful
                    $status = "success";
                    $message = "You have been signed up!";  
                }
                else { //if insert fails
                    $status = "error";
                    $message = "Ooops, Theres been a technical error!"; 
                }
            }
            else { //if already signed up
                $status = "error";
                $message = "This email address has already been registered!";
            }
        }

        //return json response
        $data = array(
            'status' => $status,
            'message' => $message
        );

        echo json_encode($data);
        exit;
    }
    ?>
Member Avatar for LastMitch

@brave_demo

I know you know new to DaniWeb so welcome to DaniWeb! You don't to not include your comments with your code. It's very hard to read your code. In the future try look like this:

It should look like this:

Hi LastMitch,

Thanking you for your earlier response. You are right, but it's given at 5th line [die(mysql_error())] and I was mistaken given table name also. Now it's everything fine.

I have two more questions:
1.Time details getting not properly.
2.I'm getting message email id inserted successfully, the value still the input field. How can i clear the input field once it's getting done.

Database details like below:

P_Id | signup_email_address | signup_date | signup_time
1 aa@gmail.com 2013-01-08 0000-00-00 00:00:00
 <?php
//email signup ajax call
if($_GET['action'] == 'signup'){
mysql_connect('localhost','root','') or die(mysql_error());
mysql_select_db('newsletter');
//sanitize data
$email = mysql_real_escape_string($_POST['signup-email']);
//validate email address - check if input was empty
if(empty($email)){
$status = "error";
$message = "You did not enter an email address!";
}
else if(!preg_match('/^[^\W][a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\@[a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\.[a-zA-Z]{2,4}$/', $email)){ //validate email address - check if is a valid email address
$status = "error";
$message = "You have entered an invalid email address!";
}
else {
$existingSignup = mysql_query("SELECT * FROM subscription WHERE signup_email_address='$email'");
if(mysql_num_rows($existingSignup) < 1){
$date = date('Y-m-d');
$time = date('H:i:s');
$insertSignup = mysql_query("INSERT INTO subscription (signup_email_address, signup_date, signup_time) VALUES ('$email','$date','$time')");
if($insertSignup){ //if insert is successful
$status = "success";
$message = "You have been signed up!";
}
else { //if insert fails
$status = "error";
$message = "Ooops, Theres been a technical error!";
}
}
else { //if already signed up
$status = "error";
$message = "This email address has already been registered!";
}
}
//return json response
$data = array(
'status' => $status,
'message' => $message
);
echo json_encode($data);
exit;
}
?>

1.Time details getting not properly.

What detail is not getting properly? Is it the format? Is the time not appearing in the db? Can you explain what is the issue?

2.I'm getting message email id inserted successfully, the value still the input field. How can i clear the input field once it's getting done.

When you insert a data into the db and data is in the db. If you want to clear that data you need to used DELETE

The query should look like this:

$sql = 'DELETE FROM subscription WHERE P_Id=1';

If you want to see more in detail how it works. Read this link which has an example of how to DELETE the INSERT data from the db:

http://www.tutorialspoint.com/mysql/mysql-delete-query.htm

@ LastMitch

Thanking you for your reply.

I'm getting 3 values in database

Email id => aa@gmail.com
Date => 2013-01-08
Time => 0000-00-00 00:00:00

why the time value stored look like: 0000-00-00 00:00:00

Member Avatar for LastMitch

@brave_demo

why the time value stored look like: 0000-00-00 00:00:00

You can read more about this:

http://iamri.ch/2012/06/07/better-detecting-of-mysqls-0000-00-00-000000-in-a-string/

If you want it to appear with the date & time you can try this:

Since you are have this:

$date = date('Y-m-d');
$time = date('H:i:s');

Just add these few lines:

$time = $_POST['date'] . ' ' . $_POST['time'];
$time = mysql_real_escape_string($time);
$time = strtotime($time);
$time = date('Y-m-d H:i:s',$time);
$query = "INSERT INTO subscription(timestamp) VALUES ('$time')";

I'm not sure if it's gonna to work because of $time, you have 2 $time in your code now!

If that didn't work well try this:

$date = date('Y-m-d');
$time = date('H:i:s');

$datetime = $_POST['date'] . ' ' . $_POST['time'];
$datetime = mysql_real_escape_string($datetime);
$datetime = strtotime($datetime);
$datetime = date('Y-m-d H:i:s',$datetime);
$query = "INSERT INTO subscription(timestamp) VALUES ('$datetime')";

It's just combine $date & $time valves in to $datetime

Let me know how it goes.

@LastMitch

Thanking you for your reply. It's not working, i try to find the solution.

Take care

Member Avatar for LastMitch

@brave_demo

It's not working, i try to find the solution.

Can you explain more what is not working? What are you trying to do?

@LastMitch

Thanking you for your reply. Your code is working perfectly. Getting time value is more differentiate from actual time...

Member Avatar for LastMitch

@brave_demo

Getting time value is more differentiate from actual time...

Explain it more clearly. Give a example what is wrong with the time so I can have a better understanding what you are talking about.

@Last Mitch

Thanking you for your reply.

Actual time is: 10:00

Database Stored time value: 06:05

Hope you are understand now.

Member Avatar for LastMitch

@brave_demo

Actual time is: 10:00

Database Stored time value: 06:05

There's nothing wrong with the code.

You need to add this date_default_timezone_set () function to your code above read this:

date_default_timezone_set('Country/Your_City');

http://php.net/manual/en/function.date-default-timezone-set.php

Here is the list:

http://php.net/manual/en/timezones.php

You also need to add something in your php.ini file

date.timezone = "Country/Your_City"

That will do the trick. Let me know how it goes.

Thanking you very much.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.