0

User clicks on a url, ie: example.com/AEQ438J

When I perform this in the code below:

$referrer = $_GET['_url'];
    // echo $referrer displays the referrer ID contents correctly as "AEQ438J"
    
    if ( ! empty($referrer))
    {
    $mysqli->query("UPDATE coming_soon_emails SET clicks = clicks + 1 WHERE code='" . $referrer ."'");
    }
    // this also updates the database correctly as it should

    if (!empty($_POST['email'])){

   // echo $referrer displays the referrer ID contents as BLANK. It should display "AEQ438J"!

$referrer displays correctly BEFORE if($_POST), however during the if($_POST) $referrer is empty.
How can I fix my code so that $referrer is not empty during the time the user posts their email address in the form?

Thank you!


Complete PHP and HTML

<?php
    
    require "includes/connect.php";
    
    function gen_code($codeLen = 7) {     
    $code = '';     
    for ($i=0; $i<$codeLen; $i++) {         
     $d=rand(1,30)%2;       
     $code .= $d ? chr(rand(65,90)) : chr(rand(48,57));      }  
     return $code; 
     }  
    
    
     function add_code($email_id) {
     global $mysqli;
     $code = gen_code(7); 
     $mysqli->query("UPDATE coming_soon_emails SET code='" . $code ."' WHERE email_id='" . $email_id . "'");  
     if($mysqli->affected_rows != 1) {   
     add_code($email_id);  
     } else return $code; } 
    
    $msg = '';
    $referrer = $_GET['_url'];
    // echo $referrer displays the referrer ID contents correctly
    
    if ( ! empty($referrer))
    {
    $mysqli->query("UPDATE coming_soon_emails SET clicks = clicks + 1 WHERE code='" . $referrer ."'");
    }
    
    if (!empty($_POST['email'])){
    
    // echo $referrer displays the referrer ID contents as BLANK
    
        // Requested with AJAX:
        $ajax = ($_SERVER['HTTP_X_REQUESTED_WITH']  == 'XMLHttpRequest');
    
        try{
            if(!filter_input(INPUT_POST,'email',FILTER_VALIDATE_EMAIL)){
                throw new Exception('Invalid Email!');
            }
    
            $mysqli->query("INSERT INTO coming_soon_emails
                            SET email='".$mysqli->real_escape_string($_POST['email'])."'");
    		
            if($mysqli->affected_rows != 1){
                throw new Exception('This email already exists in the database.');
            } else {   
              $email_code = add_code($mysqli->insert_id); 
            } 
    				
    		$msg = "http://www.example.com/" . $email_code;
    		
    		//the following doesn't work as referrer is now empty
    		if ( ! empty($referrer))
    		{
    		$mysqli->query("UPDATE coming_soon_emails SET signup = signup + 1 WHERE code='" . $referrer ."'");
            }
    		
    		if($ajax){
    			die(json_encode(array('msg' => $msg)));
    		}
    
        }
        catch (Exception $e){
    
            if($ajax){
                die(json_encode(array('error'=>$e->getMessage())));
            }
    
            $msg = $e->getMessage();        
        }
    }
    
    ?>
    
    
    <!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    
    <link rel="stylesheet" type="text/css" href="css/styles.css" />
    
    </head>
    
    <body>
    
    <div id="launch">
    
        
        <form id="form" method="post" action="">
        	<input type="text" id="email" name="email" value="<?php echo $msg;?>" />
            <input type="submit" value="Submit" id="submitButton" />
        </form>
        
        <div id="invite">
        <p style="margin-top:20px;">The ID of who referred you: <?php echo $referrer; //this displays correctly?>)</p>
        <p style="margin-top:20px;"><span id="code" style="font-weight:bold;">&nbsp;</span></p>
    	</div>
    
        
    </div>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
    <script src="js/script.js"></script>
    </body>
    </html>

Javascript (script.js)

$(document).ready(function(){
    
    	// Binding event listeners for the form on document ready
    
    	$('#email').defaultText('Your Email Address');
    
    	// 'working' prevents multiple submissions
    	var working = false;
    	
    	$('#form').submit(function(){
    		
    		if(working){
    			return false;
    		}
    		working = true;
    		
    		$.post("./index.php",{email:$('#email').val()},function(r){
    			
    			if(r.error){
    				$('#email').val(r.error);
    						} else {
    			    $('#email').val(r.msg); // not needed but gets hidden anyways...
    				$('#launch form').hide(); 
    				$("#code").html(r.msg);
    				$("#invite").fadeIn('slow'); 
    			}
    
    			
    			working = false;
    		},'json');
    		
    		return false;
    	});
    });
    
    // A custom jQuery method for placeholder text:
    
    $.fn.defaultText = function(value){
    	
    	var element = this.eq(0);
    	element.data('defaultText',value);
    	
    	element.focus(function(){
    		if(element.val() == value){
    			element.val('').removeClass('defaultText');
    		}
    	}).blur(function(){
    		if(element.val() == '' || element.val() == value){
    			element.addClass('defaultText').val(value);
    		}
    	});
    	
    	return element.blur();
    }

htaccess

RewriteEngine on
    
    RewriteCond %{HTTP_HOST} ^example.com
    RewriteRule (.*) http://www.example.com/$1 [R=301,L]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^([a-z0-9]+)$ /index.php?_url=$1 [NC,L,QSA]

table.sql

CREATE TABLE IF NOT EXISTS `coming_soon_emails` (   
      `email_id` int(11) NOT NULL auto_increment,   
      `email` varchar(64) collate utf8_unicode_ci NOT NULL,   
      `code` char(7) collate utf8_unicode_ci DEFAULT NULL,
      `clicks` int(64) collate utf8_unicode_ci DEFAULT 0,
      `signup` int(64) collate utf8_unicode_ci DEFAULT 0,
      `ts` timestamp NOT NULL default CURRENT_TIMESTAMP,   
      PRIMARY KEY  (`email_id`),   
      UNIQUE KEY `email` (`email`),
      UNIQUE KEY `code` (`code`)
    ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Edited by SuPrAiCeR69: n/a

1
Contributor
1
Reply
2
Views
6 Years
Discussion Span
Last Post by SuPrAiCeR69
0

EDIT:

In JS if I comment out the ajax call of

,'json')

and in index.php comment out the line

$ajax = ($_SERVER['HTTP_X_REQUESTED_WITH']  == 'XMLHttpRequest');

it then updates the DB correctly (the original issue is now fixed) and all works well!

However, now ajax no longer hides and shows the divs.. so knowing what the issue is, what can I do to sort it?

Edited by SuPrAiCeR69: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.