0

This is my first post to this site, and I hope someone can help.

I have a newsletter signup system. The form calls the processing script, but upon running, it outputs to another page.

I would like it to process on same page, and output the appropriate message.

After some research, the closet I could find was this article: similar question

Here is the code i am using:

HTML

<h6 class="mailingHeadine">Join Our Mailing List</h6>
    <!-- start newsletter -->
    <form id="mailing_list" name="mailing_list" action="<?php echo $_SERVER['PHP_SELF'] ?>" method="POST" >

        <!-- start maillist -->
        <div class="maillist">
            <input type="text" id="e_mail" name="e_mail" value="Enter Your Email" onfocus="if(this.value=='Enter Your Email')this.value=''; this.className='email'" onblur="if(this.value=='')this.value='Enter Your Email'; this.className='email'" />
            <p class="submit"><button type="submit" name="e_submit" value="Subscribe" id="submit">Join</button></p>

        </div><!-- end maillist -->
    </form><!-- end newsletter -->
    <div id="formResponse" style="display: none;"></div>

IN PAGE SCRIPT

<script type="text/javascript">
$("#mailing_list").submit(function() {
$.post('link-to-script.php', {email:    $('e_mail').val(), e_submit: 'yes'}, function(data) {
    $("#formResponse").html(data).fadeIn('100');
    $('#e_mail').val(''); /* Clear the inputs */
}, 'text');
return false;
});
</script>

PHP

<?php include('loader.php'); ?>

<?php include('head.php'); ?>

<?php
if(defined('SMTP') && SMTP == 'true')
{
    include('class.phpmailer.php');
}   
?>

<!-- MAIN -->
<div id="main" class="container-fluid">

    <!-- container content -->
    <div class="container-fluid">

        <!-- row-fluid -->
        <div class="row-fluid">

        <?php if(isset($_POST['e_submit']) && strlen($_POST['e_mail']) !== 0) { ?>

            <?php 

            // The system settings
            include('settings.php');

            // grab the user email
            $email = $_POST['e_mail'];

            // validate the email
            if(substr_count($email,'@') == 1 && substr_count($email,'.') >= 1) 
            {

                // check if user is already subscribed - avoids duplications
                $results = $script->checkSubscription($email);

                // subscribe the user
                if(empty($results))
                {
                    $subscribe_user = $script->subscribeUser($email);

                    // Notify Admin that an user as been subscribed
                    if($subscribe_user)
                    {
                        if($options['script_notifications'] == 'subscriptions' || $options['script_notifications'] == 'both') 
                        {
                            $subject = 'Subscription Notification ID-'.mt_rand(0, 5).': Subscription for: '.$email;

                            $message = str_replace('{EMAIL}', $email, $options['script_notification_message']);
                            $message_send = str_replace('{ACTION}', $translate->__('cancels subscription'), $message);

                            if(defined('SMTP') && SMTP == 'false')
                            {
                                $from = $options['script_email'];
                                $headers = "From: {$from}\r\n";
                                $headers .= "X-Mailer: script\r\n";
                                $headers .= "Content-Type: text/html; charset=utf-8";

                                if($subscribed) 
                                {
                                    @mail($from, $subject, $message_send, $headers);    
                                }

                            } elseif(defined('SMTP') && SMTP == 'true') {

                                $mail = new PHPMailer;

                                $mail->IsSMTP();                                      
                                $mail->Host = SMTP_HOST;  

                                if(defined('SMTP_AUTH') && SMTP_AUTH == 'true')
                                {
                                    $mail->SMTPAuth = true;
                                    $mail->Username = SMTP_USERNAME;                           
                                    $mail->Password = SMTP_PASSWORD;                            
                                } else {
                                    $mail->SMTPAuth = false;    
                                }

                                $mail->From = $options['script_email'];
                                $mail->FromName = 'script';

                                $mail->IsHTML(true);
                                $mail->Subject = $subject;
                                $mail->AddAddress($options['script_email']);
                                $mail->Body = $message_send;

                            }
                        }   
                        echo '          
                            <div class="alert alert-success tac">
                                <img src="images/done.png" width="48" height="48" alt="done"/>
                                <p>Thank you for subscribing to our Newsletter.</p>
                            </div>
                        ';  
                    } else {
                        echo '          
                            <div class="alert alert-error tac">
                                <img src="images/failed.png" width="48" height="48" alt="failed"/>
                                <p>Error occured while subscribing you.</p>
                            </div>
                        ';      
                    }

                } else {
                    echo '          
                        <div class="alert alert-error tac">
                            <img src="images/failed.png" width="48" height="48" alt="failed"/>
                            <p>You are already subscribed to our newsletter.</p>
                        </div>
                    ';      
                }

            } else {
                ?>
                <div class="alert alert-error tac">
                    <img src="images/failed.png" width="48" height="48" alt="failed"/>
                    <p>Invalid E-mail Address</p>
                </div>
                <?php
            }

            ?>

        <?php } else { ?>
            <div class="alert alert-error tac">
                <img src="images/failed.png" width="48" height="48" alt="failed"/>
                <p>You must have an e-mail address in order to subscribe to newsletter</p>
            </div>
        <?php } ?>

        </div><!-- // .row-fluid -->  

    </div>
    <!-- // end content -->

</div>
<!-- // END MAIN -->

</body>
</html>

It only kinda works. It runs through the PHP script and always outputs "You must have an e-mail address in order to subscribe to newsletter", the last line in the PHP code.

Any help would be greatly appreciated.

Community
  • 1
  • 1
Heintz74
  • 1
  • 1

3 Answers3

0

A few things.

First, your PHP file should just be PHP -- no HTML. At this point, don't try to mix another HTML page that contains PHP to be your PHP ajax processor file. It's tricky and not recommended.

I have not troubleshot your PHP page, just reduced it to what, perhaps, it should be:

<?php 
    include('e-includes/loader.php');
    include('e-head.php');

    if(defined('SMTP') && SMTP == 'true') {
        include('e-includes/class.phpmailer.php');
    }

    if(isset($_POST['e_submit']) && strlen($_POST['e_mail']) !== 0) {
            // The system settings
            include('e-includes/settings.php');

            // grab the user email
            $email = $_POST['e_mail'];

            // validate the email
            if(substr_count($email,'@') == 1 && substr_count($email,'.') >= 1) {

                // check if user is already subscribed - avoids duplications
                $results = $easyLetters->checkSubscription($email);

                // subscribe the user
                if(empty($results)) {
                    $subscribe_user = $easyLetters->subscribeUser($email);

                    // Notify Admin that an user as been subscribed
                    if($subscribe_user) {
                        if($options['easyLetters_notifications'] == 'subscriptions' || $options['easyLetters_notifications'] == 'both')  {
                            $subject = 'Subscription Notification ID-'.mt_rand(0, 5).': Subscription for: '.$email;
                            $message = str_replace('{EMAIL}', $email, $options['easyLetters_notification_message']);
                            $message_send = str_replace('{ACTION}', $translate->__('cancels subscription'), $message);

                            if(defined('SMTP') && SMTP == 'false') {
                                $from = $options['easyLetters_email'];
                                $headers = "From: {$from}\r\n";
                                $headers .= "X-Mailer: easyLetters\r\n";
                                $headers .= "Content-Type: text/html; charset=utf-8";

                                if($subscribed) {
                                    @mail($from, $subject, $message_send, $headers);    
                                }

                            } elseif(defined('SMTP') && SMTP == 'true') {

                                $mail = new PHPMailer;

                                $mail->IsSMTP();                                      
                                $mail->Host = SMTP_HOST;  

                                if(defined('SMTP_AUTH') && SMTP_AUTH == 'true') {
                                    $mail->SMTPAuth = true;
                                    $mail->Username = SMTP_USERNAME;                           
                                    $mail->Password = SMTP_PASSWORD;                            
                                } else {
                                    $mail->SMTPAuth = false;    
                                }

                                $mail->From = $options['easyLetters_email'];
                                $mail->FromName = 'EasyLetters';

                                $mail->IsHTML(true);
                                $mail->Subject = $subject;
                                $mail->AddAddress($options['easyLetters_email']);
                                $mail->Body = $message_send;

                            }
                        }
                        echo '          
                            <div class="alert alert-success tac">
                                <img src="e-images/done.png" width="48" height="48" alt="done"/>
                                <p>Thank you for subscribing to our Newsletter.</p>
                            </div>
                        ';  
                    } else {
                        echo '          
                            <div class="alert alert-error tac">
                                <img src="e-images/failed.png" width="48" height="48" alt="failed"/>
                                <p>Error occured while subscribing you.</p>
                            </div>
                        ';      
                    }

                } else {
                    echo '          
                        <div class="alert alert-error tac">
                            <img src="e-images/failed.png" width="48" height="48" alt="failed"/>
                            <p>You are already subscribed to our newsletter.</p>
                        </div>
                    ';      
                }

            } else {
                ?>
                <div class="alert alert-error tac">
                    <img src="e-images/failed.png" width="48" height="48" alt="failed"/>
                    <p>Invalid E-mail Address</p>
                </div>
            }

        } else {
            <div class="alert alert-error tac">
                <img src="e-images/failed.png" width="48" height="48" alt="failed"/>
                <p>You must have an e-mail address in order to subscribe to newsletter</p>
            </div>
        }

Notice how there is only the one <?php tag, up top. That is all you need. All the rest is PHP, and the HTML that is echoed out is returned as a text string.

Now, if you are not receiving the correct response in your AJAX success function, then you will need to troubleshoot your PHP program logic. Begin by replacing the entire PHP file with just:

<?php
    die("I am here");

and modifying your AJAX code block to just display what is returned:

    $.post('http://www.american-designer.com/t/News/e-subscribe.php', {email:    $('e_mail').val(), e_submit: 'yes'}, function(data) {
        alert( data );
    }, 'text');

Finally, note that $.post(), $.get(), $.load() are all just shorthand versions of the full ajax construction: $.ajax(). Personally, I find $.post much more difficult to use.

I suggest that you read a bit more about AJAX:

AJAX request callback using jQuery

Community
  • 1
  • 1
cssyphus
  • 37,875
  • 18
  • 96
  • 111
0

I would reccomend Ajax in the form of Jquery to handle same page requests. Ajax will allow you to make a call to your server, run code and return the response to the client side without a leaving the page or even reloading it. You need to first add the library to your page using:

<script src="http://code.jquery.com/jquery-2.1.1.min.js" ></script>

Next you need to make sure the code does not run until the page is loaded. use:

$(document).ready(function(){
    //your code will be going here
});

Now we make the call to the php page using jquery's version of onclick():

$(document).ready(function(){
    $("#your_submit_button_id").click(function(){  //when you click the element having that particular id, we execute the function listed.

    });
});    

ok finally we have to make the ajax call to the php page and get the result.

$(document).ready(function(){
    $("#your_submit_button_id").click(function(){  //when you click the element having that particular id, we execute the function listed.
        $.ajax({
            url: "your_file.php",
            type: "POST",
            dataType: "xml",  //return type, can be xml, html, or json
            data: {email: "whatever"}, //this is the data you are sending, you'll have to add some code to get the value of the input. format is: variable_name: "value"
            success: function(data_returned_from_php){
               //whatever you decide to echo bakc will be in data_returned_from_php or whatever you decide to call the object
               //take the data you get back and do whatever the hell you want with it.
            }
        });
    });
}); 

The page will not reload but the returned data can be appended to the page or you can make and alert()

Vikk
  • 617
  • 7
  • 17
0

Ok, so i figured it out in case anyone else is interested.

<script type="text/javascript">
$("#mailing_list").submit(function() {
$.post('link to script here.php', {e_mail:   $('#e_mail').val(), e_submit: 'Subscribe'}, function(data) {
    $("#formResponse").html(data).fadeIn('100');
    $('#e_mail').val(''); /* Clear the inputs */
}, 'text');
return false;
});
</script>

I was missing the second value "e_submit", the name of the submit button, and the "value" i needed to pass.

This linked helped me out: PHP Contact Form - Want to stay on my site after send

Thanks to all who responded.

Community
  • 1
  • 1
Heintz74
  • 1
  • 1