Solved

How can I incorporate a PHP SELECT statement at this point in Javascript?

Posted on 2016-08-18
10
74 Views
Last Modified: 2016-08-19
Here's the challenge:

User clicks on "Credit Card." They're getting ready to make a payment. Before the box reveals itself  that contains all of the CC fields, I want to install an alert box that' s triggered based on whether or not this person a payment that's currently in process.

Here's the way it looks / what I've been able to figure out thus far:

the alert box
Here's the source code for the page:

<!DOCTYPE html>
<html>
	<head>
		<title>Patient Pay Portal</title>
		 <!--<script src="http://192.168.1.149:8080/target/target-script-min.js" type="text/javascript" charset="utf-8"></script>-->


		<script src="/dynamicassets/js/useragent.js" type="text/javascript" charset="utf-8"></script>
	    <script src="/assets/js/modernizr.262.js" type="text/javascript" charset="utf-8"></script>
	    <script src="/assets/js/jquery-1.10.2.min.js" type="text/javascript" charset="utf-8"></script>
	    <script src="/assets/js/jquery.easing.js" type="text/javascript" charset="utf-8"></script>
		<script src="/assets/js/jquery.mobile.custom.js" type="text/javascript" charset="utf-8"></script>
	    <script src="/assets/js/mvc/mvc.js" type="text/javascript" charset="utf-8"></script>
	   
		<link href="https://fonts.googleapis.com/css?family=Open+Sans:400,300,700,600|Titillium+Web:200,300,600,700" rel="stylesheet" type="text/css">
		<link href="/dynamicassets/css/patientportal.css" type="text/css" rel="stylesheet"/>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no" />
		<meta name="mobileoptimized" content="1"/>
		<meta charset="utf-8"/>
	</head>
    	<body class='development'>
		<div class='devnot' style="position:fixed;bottom:0;left:0;width:100%;height:30px;line-height:30px;text-align:center;z-index:3000;background-color:red;color:white;font-family:'Titillium Web';font-weight:700;">DEV ENVIRONMENT: Data is not live.</div>
			<div id="app_viewport"><div id="app_stage">
			<div id="menu_group">
				<header>
					<div id="logo_container">
												<img src="/assets/images/logos/color/demo.jpg" />
												<ul id="logo_colors">
							<li id="logo_color_1"></li>
							<li id="logo_color_2"></li>
							<li id="logo_color_3"></li>
						</ul>
					</div>
					<div id="name_card">
						<div id="patient_name">
							<span class="firstname">Luke</span><span class="lastname">Skywalker</span>
						</div>
						<div id="patient_accountid">
							<label>Acc #</label><span>99953-1306117</span>
						</div>
						<div id="mobile_header">
							<span class="entypo" id="menu_btn">☰</span>
							<div id="header_balance">
								<label>Left to Pay</label>
								<div id="balance_box">
									<span class="balance">$166.72</span><span class="tagback"></span>
								</div>
							</div>
						</div>
						<div id="header_buttons">
							<a class="button settings " href='/myaccount'>My Account</a><a class="button logout" href='/logout'>Logout</a>
						</div>
					</div>
					<nav>
						<ul>
							<li ><a href='/'  class="active" tabindex="-1">Make A Payment 	<span class="entypo">πŸ’³</span></a></li>
							<li disabled title="Accounts owing less than $180.00 are not elligible for a payment plan."><a href='/paymentplan' tabindex="-1" class="">Setup a Payment Plan		<span class="entypo">πŸ“…</span></a></li>
							<li><a href='/details' class="">Balance Details							<span class="entypo">ξ€…</span></a></li>
																					<li><a href='/contact' class="">Contact Us								<span class="entypo">πŸ“±</span></a></li>
							<li class="mobile"><a href='/myaccount' class="">My Account			<span class="entypo">βš™</span></a></li>
							<li class="mobile"><a href='/logout'>Logout 					<span class="entypo">🚫</span></a></li>
						</ul>
					</nav>
				</header>
				<div id="menu_screen"></div>
			</div>
			<!--^^ This is the header.-->

									<div id="balance_message">
				<span class="firstname">Luke</span>, you currently have
				<div class="balance money">$166.72</div>
				left to pay.
				<a href="/details"><span class="entypo">ξœ„</span> View Details</a>
			</div>
              

			<!--^^ This is the balance card.-->

			<div id="makeapayment" class="panel">
				<form id="makeapayment_form" method="POST">
										<div class="content nomarginbottom">
						<label id="toplabel">How much would you like to pay today?</label>
						<select class="full howmuchtopay" data-default="166.72" name="paymentamount">
							<option value="166.72" >I'll pay it all ($166.72)</option>
							<option value="56" >I'll pay a third now ($56.00)</option>														<option value="specialamount" >I'll pay another amount</option>						</select>
						<div class="howmuchtopaycontainer">
							<p class="howmuchtopaymessage" style="display:none"></p>
						</div>
										</div>
						<!--VV This is the payment form.-->
					<div id="payment_form">
		<div id="paymentform_typechoice" class="content">
		<input type="hidden" name="cardorbank"/> 
		<button class="half " id="btn_credit_card">Credit Card</button><button class="half " id="btn_electronic_check">Electronic Check</button>
	</div>
	 	<div class="credit_card_version" >
		<hr>
		<div class="content">
			<ul class="cards">
				<li class="visa"></li>
				<li class="mastercard"></li>
				<li class="discover"></li>
				<li class="amex"></li>
			</ul>
			<div class="full">
				<label>NAME (as it appears on the card)</label>
				<input name="name" type="text" placeholder="Enter name here" validate="nonempty" valid="Great name!" fail_nonempty="Who will we thank?" value="Luke Skywalker"/>
			</div>
			<div class="full">
				<label>CARD NUMBER (the 16 digits on the front of your card)</label>
				<input name="cardnum" type="text" placeholder="Enter card number" validate="credit" valid="That looks right!" fail_nonempty="We could guess random numbers... but that only works like a third of the time." fail="This card number doesn't look right" value=""/>
			</div>

			<div class="full">
				<div class="left expiration">
					<label>EXPIRATION DATE</label>
					<div class="validatewrapper cardyear">
						<div class="raw_input">
							<input name="cardmonth" type="number" placeholder="MM"  validate="exp:m" maxlength="2" value=""/>
							<input name="cardyear" type="number" placeholder="YYYY"  validate="exp:y" maxlength="4" fail_nonempty="The expiration date is required." fail="This date doesn't look right." fail_expired="This card is expired!" valid="Awesome!" value=""/>
						</div>
						<div class="validation">
							<div class="entypo icon"></div>
							<div class="message"></div>
						</div>
					</div>
				</div><div class="right cv">
					<label>CV CODE <a href="#" tabindex=-1 class="entypo" title="The three or four digit security code on your card.">ξœ„</a></label>
										<input name="cvcode" type="number" placeholder="XXX" validate="numbers<4>3" valid="Nailed it!" fail_nonempty="Where's the CV Code?" fail="This code doesn't look quite right." value="" />
				</div>
			</div>
		</div>
		
	</div>
	<div class="e_check_version" >
		<hr>
		<div class="content">
			<div class="full">
				<label>NAME (as it appears on the account)</label>
				<input name="account_name" type="text" placeholder="Enter name here" validate="nonempty" valid="Great name!" fail_nonempty="Who will we thank?"  value="Luke Skywalker"/>
			</div>
			
			<div class="full">
				<div class="half routing">
					<label>ROUTING NUMBER <a href="#" tabindex=-1 class="entypo" title="The routing number is the nine digit number in the lower left corner of your check.">ξœ„</a></label>
					<input name="routingnumb" type="text" placeholder="XXXXXXXXX" validate="numbers:9" valid="Got it!" fail="That doesn't look quite right" fail_nonempty="The routing number is required." value=""/>
				</div><div class="half account">
					<label>ACCOUNT NUMBER</label>
					<input name="accountnum" type="text" placeholder="XXXXXXXXXXXXX" validate="numbers" valid="Looks good!" fail="The account number is required." value=""/>
				</div>
			</div>
		</div>

	</div>
	<div class="content email" >
		<div class="full">
			<label>EMAIL (we'll send you a receipt)</label>
			<input name="email" type="email" placeholder="Email address" validate="email" valid="Great! We'll send your receipt to this address." fail_nonempty="We need to send your payment confirmation somewhere!" fail_email="You might want to double check this email." value="jonathanj@patientfocus.com"/>
		</div>
			</div>
</div>
					<div  id="make_a_payment_submit" >
						<hr>
						<div class="content">
							<span class="lightgrey">By clicking "Secure Checkout" you acknowledge that you have read and agree to the <a tabindex="-1" href="/legal/terms" target="_blank">PatientFocus Terms and Conditions</a> and our <a href="/legal/tila" tabindex="-1" target="_blank">TILA Disclosure</a>.</span>
						</div><div class="content">
							<button class="full" type="submit"><span class="entypo">πŸ”’</span> Secure Checkout <span class="amount">- $166.72</span></button>
						</div>
					</div>
				</form>
			</div>		</div></div>
		<script src="/assets/js/views/patientportal/portal.js" type="text/javascript" charset="utf-8"></script>
<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-50374521-1', 'patientfocus.com');
  ga('send', 'pageview');

</script>
			</body>
</html>

Open in new window


...and here's the JS code with my alert box positioned where I need to run my query (portal.js [line 156]):

$(function(){
	//For some reason, the jquery mobile ajax style links are breaking some of my anchor tags.
	$.mobile.ajaxEnabled = false;

	var $html = $('html');
	var $doc = $(document);
	var _ = new jsMVC();

	//Handling keyboardevents for anything assigned a tabindex that does NOT natively support tabbing.
	$doc.on('keypress.tabber','*[tabindex]:focus:not(a,area,button,input,object,select,textarea)',function(e){
		if(e.which=='13'||e.which==32){
			//Enter or space.
			$(this).click();
		}
	});

	//Login Handlers
	$('#login_page .whereisit .openit,#login_page .whereisit .closeit').click(function(){
		$(this).parents('.whereisit').toggleClass('open');
	});
	$('#login_page').on('click.openinfo','.openthething', function(){
		$('.whereisit').toggleClass('open');
		return false;
	});
	$('#login_page').on('click.cantlogin', 'a.cantlogin', function(){
		$('.displayer li.loginform').removeClass('active');
		$('.displayer li.cantlogin').addClass('active');
	});
	$('#login_page').on('click.backtologin', 'a.backtologin', function(){
		$('.displayer li.loginform').addClass('active');
		$('.displayer li.cantlogin').removeClass('active');
	});
	/*$('#login_page button[type="submit"]').click(function(){
		var form = $(this).parents('form');
		form.find('input').blur();
		if(form.find('.invalid').length){

		} else {
			form.submit();
		}
		return false;
	});*/

	Date.prototype.getFullMonth = function() {
		var month = this.getMonth() + 1;
		return month < 10 ? '0' + month : '' + month; // ('' + month) for string result
	};

	//Input validation
	$.fn.nonvalid = function(){
		var wrapper = $(this).parents('.validatewrapper').removeClass('invalid valid');
		var input = wrapper.find('input').removeClass('invalid valid');
		var messagecontainer = input.attr('name') == 'specialamount' ? $('.howmuchtopaymessage').removeClass('invalid valid') : wrapper.find('.message');
		messagecontainer.hide();
	};
	$.fn.valid = function(showmessage, replacewith){
		var wrapper =  $(this).parents('.validatewrapper').removeClass('invalid').addClass('valid');
		var input = wrapper.find('input').removeClass('invalid').addClass('valid');
		wrapper.find('.entypo').html("βœ“");
		var message = '';


		input.each(function(){
			var inp = $(this);
			if(showmessage && inp.attr('valid') && message === ''){
				message = inp.attr('valid').replace('{{replace}}', replacewith || '');
			}
		});
		
		var messagecontainer = input.attr('name') == 'specialamount' ? $('.howmuchtopaymessage').removeClass('invalid').addClass('valid') : wrapper.find('.message');
		messagecontainer.html(message).slideDown(200);
		
	};
	$.fn.invalid = function(fails, replacewith){
		var wrapper = $(this).parents('.validatewrapper').removeClass('valid').addClass('invalid');
		var input = wrapper.find('input').removeClass('valid').addClass('invalid');
		wrapper.find('.entypo').html("❌");
			var message = '';
			input.each(function(){
				var inp = $(this);
				if(inp.attr('fail_'+fails[0])){
					message = inp.attr('fail_'+fails[0]);
				} else if(inp.attr('fail') && message === ''){
					message = inp.attr('fail');
				} else {
					//console.log('input is missing this attribute: fail_'+fails[0]);
				}
			});
			message = message.replace('{{replace}}', replacewith || '');
		//console.log(wrapper.find('.message'));
				
		var messagecontainer = input.attr('name') == 'specialamount' ? $('.howmuchtopaymessage').removeClass('valid').addClass('invalid') : wrapper.find('.message');
		messagecontainer.html(message).slideDown(200);
	};

	/**

		Modernizr Placeholder Replacement

	**/

	if(!Modernizr.input.placeholder){

        $(document).on('focus.placeholder', '[placeholder]:not([type="password"])',function() {
          var input = $(this);
          if(input.parents('.loginform').length) return;

          if (input.val() == input.attr('placeholder')) {
            input.val('');
            input.removeClass('placeholder');
          }
        }).on('blur.placeholder', '[placeholder]:not([type="password"])',function() {
          var input = $(this);
          if(input.parents('.loginform').length) return;

          if (input.val() === '' || input.val() == input.attr('placeholder')) {
            input.addClass('placeholder');
            input.val(input.attr('placeholder'));
          }
        });
        $('[placeholder]').blur();
        $(document).on('submit.placeholder', 'form',function() {
          preparePlaceholders($(this));
        });

    }

    preparePlaceholders = function(form){
        $(form).find('[placeholder]').each(function() {
            var input = $(this);
            if (input.val() == input.attr('placeholder')) {
              input.val('');
            }
        });
    };

    /**

		Payment Form input disabling.

    **/

	var preparepaymentform = function(){

		var cc = $('#payment_form .credit_card_version');
		var ec = $('#payment_form .e_check_version');

		//Disable all inputs.
		cc.find('input').attr('disabled', true).nonvalid();
		ec.find('input').attr('disabled', true).nonvalid();
		$('#payment_form [name="email"], #payment_form [name="autodraftdate"]').attr('disabled',true).nonvalid();
		//console.log(cc);

		if(($('#autodraftexpander').length === 0 || $('#autodraftexpander').is(':checked')) && $('#btn_credit_card').hasClass('active')){
			
			alert("right here");

			//enable credit card inputs
			cc.find('input').attr('disabled', false);
			$('input[name="cardorbank"]').val('card').attr('disabled',false);
			$('#payment_form [name="email"], #payment_form [name="autodraftdate"]').attr('disabled',false);

		} else if(($('#autodraftexpander').length === 0 || $('#autodraftexpander').is(':checked')) && $('#btn_electronic_check').hasClass('active')){

			//enable electronic check inputs
			ec.find('input').attr('disabled', false);
			$('input[name="cardorbank"]').val('bank').attr('disabled',false);
			$('#payment_form [name="email"], #payment_form [name="autodraftdate"]').attr('disabled',false);

		}

	};
	preparepaymentform();

    /**

		Clicking the logo takes us home, usually the make a payment location

    **/
    $('#logo_container').click(function(){
		window.location = "/";
    });

	if(_ua.check('android')){
	/**

		Turn off transitions on android (They don't operate well)

    **/
		$html.removeClass('csstransitions');

	/**

		Turn all number input types into text until you focus

	**/

		$html.find('input[type="number"]').each(function(){
			$(this).addClass('numtype')[0].type = "text";
		});
		$html.on('focus.androidinputs','input.numtype',function(){
			this.type="number";
		}).on('blur.androidinputs','input.numtype',function(){
			this.type="text";
		});

	}
	
	//Overwrite disabled and active click states for nav
	$('nav li[disabled] a,nav li a.active').click(function(){
		return false;
	});

	/**

		Create jsMVC views.

	**/
		//Select box
		_.view({
			name:'select',
			html:'<div class="select" tabindex=0><div class="value" value="{{value}}">{{label}}</div><div class="raw_select"></div><ul class="dropdown">{{selectoptions}}</ul></div>'
		});
		//Select option
		_.view({
			name:'selectoption',
			html:'<li val="{{value}}">{{label}}</li>'
		});
		//Pay another amount special label
		_.view({
			name:'payanotheramount',
			html:'<span class="speciallabel">I\'ll pay</span><input name="specialamount" value="{{defaultval}}" validate="minpaymentrules" placeholder="Enter amount" valid="If you can make this payment every month<br/> you will be debt free by \\{\\{replace\\}\\}." fail_nonempty="An amount is required." fail_undermin="The minimum online payment is \\{\\{replace\\}\\}." fail_overmax="Can\'t pay more than you owe."/>'
		});
		//Input validation.
		_.view({
			name:'validator',
			html:'<div class="validatewrapper"><div class="raw_input"></div><div class="validation"><div class="entypo icon"></div><div class="message"></div></div>'
		});
		//Toggle button style checkbox
		_.view({
			name:'toggle',
			html:'<div class="toggle"><div class="raw_input"></div><ul><li class="option">{{on}}</li><li class="knob"><span></span></li><li class="option">{{off}}</li></ul></div>'
		});
		//Money formatter
		_.view({
			name:'money',
			html:'<span class="dollars">{{dollars}}</span><span class="cents">{{cents}}</span>'
		});
		//Ordinal formatter
		_.view({
			name:'ordinal',
			html:'<span class="base">{{base}}</span><span class="suffix">{{suffix}}</span>'
		});
	/**

		Create control functions.

	**/
		//Replace all selects that have not already been replaced with the markup version above.
		var replaceSelect = function(select){
			var retarray = [];
			var selects;

			select = select || 'select';
			selects = $(select).filter(function(){
				return $(this).parents('.select').length === 0;
			});

			selects.each(function(){
				var sel = $(this);
				var options = sel.find('option');
				var optionshtml = '';

				//Build the options first.
				options.each(function(){
					optionshtml += _.views['selectoption'].load({
						value: this.value || '',
						label: this.childNodes[0].nodeValue
					});
				});

				//Then drop the options into the select markup.
				var newSelect = $(_.views['select'].load({
					value			: sel.find('option:selected')[0].value,
					label			: sel.find('option:selected')[0].childNodes[0].nodeValue,
					selectoptions	: optionshtml
				}));

				sel.replaceWith(newSelect);

				//Don't discard the original markup. Just hide it and use it.
				//(makes for nice form processing)
				newSelect.find('.raw_select').append(sel);


				if(_ua.check('android') || _ua.check('iphone')){
					sel.css({
						"display": "block",
						"visibility": "visible",

						"width": newSelect.outerWidth(),

						"height": newSelect.outerHeight(),

						"opacity": "0",

						"position": "absolute",

						"top": "0",

						"left": "0",

						"cursor": "pointer",

						"z-index": "999999",

						"margin": "0",

						"padding": "0",

						"-webkit-appearance": "menulist-button"
					});
				} else newSelect.find('.raw_select').css('display', 'none');



				//This handles displaying the value of the select.
				sel.on('change.replSelect',function(e){
					var $select = $(this).parents('.select');
					var option = $(this).find('option:selected');

					$('.select').removeClass('open');
					if($(this).hasClass('howmuchtopay') && $(this).val() == 'specialamount'){
						//This is the special case value for the "I'll pay another amount selection"
						$select.find('.value').html(_.views['payanotheramount'].load({
							defaultval:$(this).data('default')
						}));
						replaceInputs($select.find('input[name="specialamount"]'));
						$select.find('input[name="specialamount"]').blur().select().click(function(e){
							e.stopPropagation();
						});
					} else {
						$select.find('.value').html(option[0].childNodes[0].nodeValue);
					}
					$select.attr('val',$(this).val());
				}).click(function(e){
					e.stopPropagation();
				});

				sel.change();

				//Push the reference into the array to be returned.
				retarray.push(newSelect);
			});

			//Assign document/html level open/close/select handlers.
			$doc
				.off('click.closeSelect')
				.on('click.closeSelect',function(){
					$('.select').removeClass('open');
				});
			$html
				.off('click.openselect')
				.on('click.openselect','.select:not(.open)',function(e){
					e.stopPropagation();
					$(this).addClass('open');
				})
				.off('click.changeselect')
				.on('click.changeselect','.select.open li',function(e){
					var option = $(this);
					var raw    = $(this).parents('.select').find('.raw_select select');

					raw.val(option.attr('val')).change();
				});

			//Return array of references to the new select markup.
			return retarray;
		};

	var replaceCheckbox = function(selector){
		var retarray;
		var checkboxes;
		selector = selector || 'input[type="checkbox"]';

		checkboxes = $(selector).filter(function(){
			return $(this).parents('.toggle').length === 0;
		});

		checkboxes.each(function(){
			var cb = $(this);
			var toggle = $(_.views['toggle'].load({
				on: cb.data('on_label') ||'On',
				off: cb.data('off_label') || 'Off'
			}));
			if(!cb.is(':checked')) toggle.addClass('off');
			cb.replaceWith(toggle);
			toggle.find('.raw_input').css('display','none').append(cb);

			cb.on('change.toggle',function(){
				var cb = $(this);
				var toggle = cb.parents('.toggle');

				if(cb.is(':checked')){
					toggle.removeClass('off');
				} else {
					toggle.addClass('off');
				}
			});
		});
		$html
			.off('click.toggler')
			.on('click.toggler','.toggle',function(e){
				e.stopPropagation();

				var toggle = $(this);
				var raw = toggle.find('.raw_input input');
				if(!toggle.parents('.togglehover').hasClass('locked')){
					raw[0].checked = raw[0].checked? false : true;
					raw.change();
				}
				
			})
			.off('click.togglertoo')
			.on('click.togglertoo','.togglehover',function(e){
				$(this).find('.toggle').click();
			});
			/*.on('swiperight.toggler','.toggle',function(e){
				e.stopPropagation();

				var toggle = $(this);
				var raw = toggle.find('.raw_input input');

				raw[0].checked = true;
				raw.change();
			})
			.on('swipeleft.toggler','.toggle',function(e){
				e.stopPropagation();

				var toggle = $(this);
				var raw = toggle.find('.raw_input input');

				raw[0].checked = false;
				raw.change();
			});*/
	};

	/*

		TITLE REPLACEMENT

	*/
	$('a[title][href="#"]').click(function(){
		var $this = $(this);
		var title = $this.data('title');
		setTitle(title, $(this));
	});
	$('[title]').each(function(){
		var $this = $(this);
		var title = this.title;
		this.removeAttribute('title');
		$this.attr('data-title',title);
	});
	var addtitletimer;
	var removetitletimer;
	var mouseX = 0;
	var mouseY = 0;
	$doc.on('mousemove.trackmouse',function(e){
		mouseX = e.pageX;
		mouseY = e.pageY;
	}).on('mouseenter.title','[data-title]',function(e){
		var $this = $(this);
		var title = $this.data('title');
		clearTimeout(addtitletimer);
		clearTimeout(removetitletimer);
		if(!$this.data('link')){
			addtitletimer = setTimeout(function(){
				setTitle(title, $this);
			},1000);
		}
	}).on('mouseleave.title','[data-title], .title_replacement',function(){
		clearTimeout(removetitletimer);
		removetitletimer = setTimeout(function(){
			var $this = $(this);
			/**
			
				HERES WHERE YOU LEFT OFF... TITLES AND FUN.

			*/
			//How do i keep this from firing when moving from the title back to the element?
			//Might have to breadcrumb outside of the function here.
			if($('.title_replacement:hover').length === 0){
				clearTimeout(addtitletimer);
				setTitle();
			}
		});
	});
	var setTitle = function(title, calledby){
		$('.linked').removeClass('linked').data('link',false);
		if($('.title_replacement').data('link'))$('.title_replacement').data('link').data('link', false);
		$('.title_replacement').remove();
		if(title){
			var t = $('<div class="title_replacement">'+title+'</div>');
			t.data('link',calledby);
			calledby.data('link',t).addClass('linked');
			$('body').append(t);
			t.css({
				position:'fixed',
				left:mouseX-t.outerWidth()/2+'px',
				top:mouseY-t.outerHeight()-6+'px'
			});
			//console.log(t);
		}
			
	};


	var replaceMoney = function(){
		//This replaces the instances of .money in the document with a formated superscript version.
		$('.money').each(function(){
			if($(this).find('.dollars').length === 0){

				var _el = $(this);
				var money = _el.html();

				var dollars = money.substring(0,money.indexOf('.'));
				var cents = money.substring(money.indexOf('.'));

				_el.html(_.views['money'].load({
					dollars : dollars,
					cents : cents
				}));
			}
		});
	};

	replaceMoney();

	//Used for pageready specific css rules.
	$html.addClass('pageready');

	//Replace all the select boxes.
	replaceSelect('select');

	//Replace all the check boxes.
	replaceCheckbox('input[type="checkbox"]');

	

	/*
		Mobile menu open/close functionality
	*/
	$('#menu_btn').click(function(e){ toggleMenu(); e.stopPropagation();});
	$('header').click(function(e){ e.stopPropagation();});
	$('#menu_screen, #mobile_header').on('mousedown',function(e){ closeMenu(); e.stopPropagation();});
	$('#menu_screen, #mobile_header').on('swipeleft',function(e){ closeMenu(); e.stopPropagation();});
	//if(!_ua.check('android')){
		$doc
			.on('swiperight',function(e){
				openMenu();
			})
			.on('swipeleft',function(e){
				closeMenu();
			});
	//}


	openMenu = function(){
		$html.addClass('menuopen');
		var easing = 'easeInOutCubic';
		var duration = 400;

		/*$('header').animate({
			left:0
		},duration,easing);
		$('#mobile_header, body').animate({
			left:200
		},duration,easing);*/
		/*$('#menu_screen').fadeIn({
			duration:duration,
			easing:easing,
			step:function(now, fx){
				var pct = fx.now/(fx.end-fx.start);
				var val = parseInt(200*pct,10);
				$('#mobile_header, body').css('left',val+'px');
				$('header').css('left',val-200+'px');
			}
		});*/
	};
	closeMenu = function(){
		$html.removeClass('menuopen');
		var easing = 'easeInOutCubic';
		var duration = 400;

		/*$('header').animate({
			left:-200
		},duration,easing);
		$('#mobile_header, body').animate({
			left:0
		},duration,easing);
		$('#menu_screen').fadeOut(duration);*/
	};
	toggleMenu = function(){
		if($html.hasClass('menuopen')) closeMenu();
		else openMenu();
	};

	/**

		Autodraft expander

	**/

	$('#autodraftexpander').change(function(){

			if($(this).is(':checked')) $('#paymentform_autodraft').slideDown(200).find('input');
			else $('#paymentform_autodraft').slideUp(200);
			preparepaymentform();

	});

	/**

		Credit card / echeck form switching

	**/
	$('#btn_credit_card').click(function(e){
		e.stopPropagation();

		var btn = $(this);
		if($('#btn_electronic_check').hasClass('active')){
			$('#btn_electronic_check').removeClass('active');
			$('#payment_form .e_check_version').slideUp();
		} else {
			$('#make_a_payment_submit, #payment_form .email').slideDown();

		}
		if(!btn.hasClass('active')){
			btn.addClass('active');
			$('#payment_form .credit_card_version').slideDown();
		}

		preparepaymentform();
		return false;
		
	});
	$('#btn_electronic_check').click(function(e){
		e.stopPropagation();

		var btn = $(this);
		if($('#btn_credit_card').hasClass('active')){
			$('#btn_credit_card').removeClass('active');
			$('#payment_form .credit_card_version').slideUp();
		} else {
			$('#make_a_payment_submit, #payment_form .email').slideDown();
		}
		if(!btn.hasClass('active')){
			btn.addClass('active');
			$('#payment_form .e_check_version').slideDown();
		}

		preparepaymentform();
		return false;
		
	});

	function replaceInputs(input){
		input = input || 'input[validate]';

		//trim out already replaced inputs.
		input = $('input[validate]').filter(function(){
			return $(this).parents('.validatewrapper').length === 0;
		});

		if(input) input.each(function(){
			var i = $(this);
			var labelizePlaceholder = false;

			if(!Modernizr.input.placeholder && (i.attr('type') == 'password' || i.parents('.loginform').length)){
				labelizePlaceholder = true;
			}

			var validator = $(_.views['validator'].load());
			if(i.data('getwidth')) validator.css('width',i.css('width'));
			i.replaceWith(validator);
			validator.find('.raw_input').append(i);

			if(labelizePlaceholder && i.attr('placeholder')){
				validator.find('.raw_input').prepend('<label>'+i.attr('placeholder')+'</label>');
				validator.addClass('labelize');
			}

			
		});

		if(!Modernizr.input.placeholder && $('#login_page').length){
			$('.whereisit').addClass('labelize');
			$('.whereisit .entypo.openit').removeClass('entypo').html('?');
		}
		
	}
	replaceInputs();


	var monthsarray = ['January','February','March','April','May','June','July','August','September','October','November','December'];
	var getOrdinal = function(n) {
		return n + getOrdinalSuffix(n);
	};
	var getOrdinalSuffix = function(n) {
		var s=["th","st","nd","rd"],
			v=n%100;
		return (s[(v-20)%10]||s[v]||s[0]);
	};
	function replaceOrdinals(ordinal){
		var ords = $(ordinal || '.ordinal').filter(function(){
			return $(this).children('.base').length === 0;
		});

		ords.each(function(){
			var _o = $(this);
			var base = _o.html();
			var suffix = getOrdinalSuffix(base);

			_o.html(_.views['ordinal'].load({
				base:base,
				suffix:suffix
			}));
		});
	}
	replaceOrdinals();

	$('select.howmuchtopay').on('change.securecheckoutcopy', function(){
		var payment;
		$('.howmuchtopaymessage').hide();
		switch($(this).val()){
			case "specialamount":
				payment = parseFloat($(this).parents('.select').find('input').val()) || false;
				break;
			default:
				payment = parseFloat($(this).val());
				break;
		}
		if(payment){

			$('#make_a_payment_submit button').attr('disabled',false);
			$('#make_a_payment_submit button .amount').html('- ' + payment.formatMoney());

		} else {

			$('#make_a_payment_submit button').attr('disabled',true);
			$('#make_a_payment_submit button .amount').html('');

		}
	});

	$html.on('blur.validate','input[validate]',function(){

		var _i = $(this);
		var _val = _i.val();
		var _validate = _i.attr('validate').match(/^[\s]*?([a-z,A-Z]+)/)[0].toLowerCase();
		var _aftercolon = _i.attr('validate').match(/:([a-z,A-Z,0-9]+)/);
		if(_aftercolon) _aftercolon = _aftercolon[1];
		var _replacewith = false;

		var _lessthan = _i.attr('validate').match(/<([a-z,A-Z,0-9]+)/);
		if(_lessthan) _lessthan = _lessthan[1];
		var _greaterthan = _i.attr('validate').match(/\>([a-z,A-Z,0-9]+)/);
		if(_greaterthan) _greaterthan = _greaterthan[1];
		/*if(!_greaterthan && !_lessthan && _aftercolon && _aftercolon.match(/^[0-9\s]$/)){
			_lessthan = _aftercolon;
			_greaterthan = _aftercolon;
		}*/

		var fails = [];
		switch(_i.attr('validate').match(/^[\s]*?([a-z,A-Z]+)/)[0].toLowerCase()){
			case 'email':
				if(!_val) fails.push('nonempty');
				else if(!_val.match("[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?")) fails.push('email');
				break;
			case 'numbers':
				//NUMBERS STYLE VALIDATION
				// : IMPLIES THE LENGTH OF THE NUMBER IN DIGITS
				// < IS ANY NUMBER LESS THAN THIS MANY DIGITS
				// > IS ANY NUMBER GREATER THAN THIS MANY DIGITS

				_val = _val.replace(/[^\d^*]/g,'');
				//_i.val(_val);

				if(!_val) fails.push('nonempty');

				else if(_greaterthan && _val.length < parseInt(_greaterthan,10)) fails.push('greaterthan');
				else if(_lessthan && _val.length > parseInt(_lessthan,10)) fails.push('lessthan');
				else if(_aftercolon && _val.length != parseInt(_aftercolon,10)) fails.push('length');

				break;
			case 'credit':

				$('#payment_form .cards li').removeClass('active');
				if(!_val) fails.push('nonempty');

				else{

					var cardtype = validateCard(_val);
					if(cardtype){
						
						$('#payment_form .cards .' + cardtype).addClass('active');
					} else {

						if(_val.charAt(0) != '*') fails.push('nonaccepted');
					}
				}
				break;
			case 'nonempty':
				if(!_val) fails.push('nonempty');
				break;
			case 'exp':
				//This is a special case validator.
				var minp = _i.parents('.expiration').find('[name="cardmonth"]');
				var yinp = _i.parents('.expiration').find('[name="cardyear"]');

				var m = parseInt(minp.val(),10);
				var y =  parseInt(yinp.val(),10);

				var validdate = true;
				if(!m){
					fails.push('nonempty');
					validdate = false;
				} else if(m<1 || m>12){
					fails.push('baddate');
					validdate = false;
				}
				if(!y){
					fails.push('nonempty');
					validdate = false;
				} else if(y<1000 || y>9999){
					fails.push('baddate');
					validdate = false;
				}

				if(validdate){
					m = m<10? '0' + m : m;
					var exp = parseInt(y+''+m,10);
					var d = new Date();

					var comp = parseInt(d.getFullYear() + '' + d.getFullMonth(),10);

					if(exp < comp){
						fails.push('expired');
					}
				}

				break;
			case 'days':
				//This is a special case validator
				if(_val < 1) _val = 1;
				else if(_val > 28)_val = 28;
				_i.val(_val);

				var date = new Date();
				_replacewith = monthsarray[date.getMonth()+ (date.getDate() >= _val? 1 : 0)] + ' ' + getOrdinal(_val) + '.';

				break;
			case 'minpaymentrules':
				//This is a special case validator for the I'll pay a different amount option on the front screen.
				_val = parseFloat(_val.replace(/\$|,/g,''));
				_i.val(_val? _val.formatMoney() : '');
				if(!_val){
					fails.push('nonempty');
					$('#make_a_payment_submit button').attr('disabled',true);
					$('#make_a_payment_submit button span.amount').html('');
				}else if(_val < _ud.minpayment){
					//This value is under the defined minimum (the lowest of paymentamount/totalbalance/30 dollars)
					fails.push('undermin');
					_replacewith = _ud.minpaymentformatted;
					$('#make_a_payment_submit button').attr('disabled',true);
					$('#make_a_payment_submit button span.amount').html('');

				}else if(_val > _ud.lefttopay){

					fails.push('overmax');
					$('#make_a_payment_submit button').attr('disabled',true);
					$('#make_a_payment_submit button span.amount').html('');

				} else {
					var now = new Date();
					var nummonths = Math.ceil(_ud.lefttopay/_val);

					$('#make_a_payment_submit button').attr('disabled',false);
					$('#make_a_payment_submit button span.amount').html('- '+parseFloat(_val).formatMoney());

					now.setMonth(now.getMonth()+nummonths -1);

					_replacewith = monthsarray[now.getMonth()] + ', ' + now.getFullYear();
				}
				break;
			default:
				//console.log('other');
				break;
		}
		if(fails.length){
			//console.log(fails);

			//_i = _i.attr('name') == 'cardmonth' ? _i.parents('.expiration').find('[name="cardyear"]') : _i;
			_i.invalid(fails, _replacewith);

		} else if (fails !== false) {
			_i.valid(true, _replacewith);
			//_i = _i.attr('name') == 'cardmonth' ? _i.parents('.expiration').find('[name="cardyear"]') : _i;
		}

	}).on('focus.devalidate', 'input[validate]',function(){
		$(this).nonvalid();
	});
	$('[name="specialamount"]').blur();
	
	function validateCard(cardnum)
	{

		//start without knowing the credit card type
		var result = false;

		//first check for MasterCard
		if (/^5[1-5][0-9]{14}$/.test(cardnum))
		{
			result = "mastercard";
		}

		//then check for Visa
		else if (/^4[0-9]{12}(?:[0-9]{3})?$/.test(cardnum))
		{
			result = "visa";
		}

		//then check for AmEx
		else if (/^3[47][0-9]{13}$/.test(cardnum))
		{
			result = "amex";
		}

		//then check for Discover
		else if (/^6(?:011|5[0-9]{2})[0-9]{12}$/.test(cardnum))
		{
			result = "discover";
		}


		return result;
	}

	var bd = $('#balancedetails');
	if(bd.length){
		//balance details page.

		$html.on('click.expandEncounter','.encounter .enc_id',function(){
			var enc_id = $(this);
			var encounter = enc_id.parents('.encounter');
			if(encounter.hasClass('open')){
				if(!_ua.check('android')){
					encounter.find('.enc_table').slideUp(200);
				}
				encounter.removeClass('open');
			} else {
				if(!_ua.check('android')){
					encounter.find('.enc_table').slideDown(200);
				}
				encounter.addClass('open');
			}
		})
		.on('click.expandPayments','.openPayments',function(e){
				//ADDITIONAL PAYMENTS EXPANDER
				var add = $(this).parents('li.additional');

				if(!_ua.check('android')){
					//ENSURE THAT THERE IS NO DOUBLE CLICK ERRING
					if(add.hasClass('inactive')) return;
					else add.addClass('inactive');

					//CLICKING LINKS OPENS IT
					if(!add.hasClass('open')){
						add.addClass('open');
						add.find('.popin').slideDown(200,function(){
							add.removeClass('inactive');
						});
					} else {
						add.removeClass('inactive');
					}
					//CLICKING LINKS ALSO CLOSES IT
					/*else{
						add.find('.popin').slideUp(200,function(){
							add.removeClass('open').removeClass('inactive');
						});
					}*/
				} else {
					//ADDITIONAL PAYMENTS EXPANDER
					add.addClass('open');
					add.find('.popin:not(label)').css('display','block');
					add.find('label.popin').css('display','inline-block');
				}
				//ENSURE THERE IS NO REDIRECT OR EVENT MISFIRING
				e.stopPropagation();
				return false;
			})
		//DOCUMENT CLICK CLOSE
		/*.on('click',function(){
				var add = $('li.additional');

				if(add.hasClass('inactive')) return;
				else add.addClass('inactive');

				add.find('.popin').slideUp(200,function(){
					add.removeClass('open').removeClass('inactive');
				});
			})*/
		.on('click','.total a.closeit', function(){
				var add = $('li.additional');
				if(!_ua.check('android')){
					if(add.hasClass('inactive')) return;
					else add.addClass('inactive');
					
					add.find('.popin').slideUp(200,function(){
						add.removeClass('open').removeClass('inactive');
					});
				} else {
					add.removeClass('open');
					add.find('.popin').css('display','none');
				}
			})
		.on('click.stopPropa','li.additional',function(e){ e.stopPropagation();});

	}

	var settings = $('#settings');
	if(settings.length){
		
		$('.address .editonly, .email .editonly').on('click.toggle',function(e){
			e.stopPropagation();
			var cb = $(this).find('input');
			cb[0].checked = cb[0].checked? false : true;
			cb.change();

		}).on('swipeleft',function(e){
			e.stopPropagation();
			var cb = $(this).find('input');
			cb[0].checked = false;
			cb.change();

		}).on('swiperight',function(e){
			e.stopPropagation();
			var cb = $(this).find('input');
			cb[0].checked = true;
			cb.change();
		});

		$('.editbtn').on('click.edit',function(){
			var btn = $(this);
			btn.parents('li.editable').addClass('edit').find('input').attr('disabled',false).eq(0).select();
		});

        $('.cancelbtn').on('click.cancel',function(){
            var btn = $(this);
            btn.parents('li.editable').removeClass('edit').find('input').each( function () {
                var inp = $(this);
                    inp.attr('disabled',true);
                    inp.val(inp.attr('value'));
                    inp.change();
            });
        });

        settings.on('click.save','.savebtn',function(){
            var btn = $(this),
                li = btn.parents('.editable'),
                inputs = li.find('input[name]'),
                form = $('<form action="/myaccount" method="post">').append(inputs.clone()).append('<input name="action" value="save">');

            form.submit();
        });

	}

	/*

		EDIT PAYMENT PLAN

	*/
	$('#editplan .editpaymentplan').click(function(){
		$('#editplan').addClass('edit');
		$('#editplan .draftdate input').blur();
		return false;
	});

	/*

		ANIMATING PAYMENT AMOUNT

	*/
	var pb = $('.progressbar[data-animate]');
	if(pb.length){
		setTimeout(function(){
			var start = parseInt(pb.find('.gradient').html(),10);
			var end = parseInt(pb.data('animate'),10);
			pb.children('.progress').animate({
				'width':pb.data('animate') +'%'
			},{
				duration:1000,
				easing:'easeInOutCubic',
				step:function(e, t){
					if(t.end == t.now) pb.find('.gradient').html(pb.data('animate')+'%');
					else {
						//console.log('now : ' +t.now);
						//console.log('dur : ' +(t.end - t.start));
						var now = t.now - t.start;
						var dur = t.end - t.start;
						var pct = (now / dur);
						var progress = Math.round(pct * (end - start));
						//console.log(end);
						pb.find('.gradient').html(start+progress+'%');
					}
				}
			});
		}, 2000);
	}


	/*

		SPECIAL CASE PAYMENT PLAN 12 MONTH REQUIRED AUTODRAFT

	*/
	$('select[name="paymentplanamount"]').on('change.twelver',function(){

		var $sel = $(this);
		var $op  = $sel.children('option:selected');

		if($op.data('require') && $op.data('require') == 'autodraft'){
			$('#autodraftexpander').prop('checked', true).change();
			$('.autodraft.togglehover').addClass('locked');
		} else {
			$('.autodraft.togglehover').removeClass('locked');
		}

	});


	/*

		SUBMIT BUTTONS

	*/
	$('button[type="submit"]').click(function(){
		var btn = $(this);
		var form = btn.parents('form');

		form.find('input:not([disabled])').blur();
		if(form.find('.invalid').length === 0){
			$(this).attr('disabled',true);
			form.submit();
		}
		return false;
	});

	$('#balancedetails ul.tabs .by_encounter').click(function(){
		$('ul.tabs .payments_only').removeClass('active');
		$(this).addClass('active');

		$('.showables .showable').removeClass('active');
		$('.showables .showable.byencounters').addClass('active');
	});
	$('#balancedetails ul.tabs .payments_only').click(function(){
		$('ul.tabs .by_encounter').removeClass('active');
		$(this).addClass('active');

		$('.showables .showable').removeClass('active');
		$('.showables .showable.bypayment').addClass('active');
	});

	$('[name="specialamount"]').blur();
});

Number.prototype.formatMoney = function(c, d, t){
	var n = this;
		c = isNaN(c = Math.abs(c)) ? 2 : c;
		d = d === undefined ? "." : d;
		t = t === undefined ? "," : t;
	var	s = n < 0 ? "-" : "",
		i = parseInt(n = Math.abs(+n || 0).toFixed(c),10) + "",
		j = (j = i.length) > 3 ? j % 3 : 0;
   return s + '$' + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
 };

Open in new window


Again, how do I incorporate a PHP SELECT statement that gives me the "if" clause I need to trigger the alert.

I'm thinking since I've got an email address, if I could establish that as a var and the pass that into a function and return a 1 or a 0, that would give me what I need.

What do you think?
0
Comment
Question by:brucegust
  • 5
  • 3
  • 2
10 Comments
 
LVL 52

Expert Comment

by:Scott Fell, EE MVE
ID: 41761968
Bruce, it may be me, but I am confused by your statement?
I want to install an alert box that' s triggered based on whether or not this person a payment that's currently in process.

Are you really asking if somebody submits a payment, then you don't want them to click the payment button again at least until after there is a response from your credit card processor?

  1. Click payment button
  2. Disable payment button
  3. Send payment info via ajax
  4. Retrieve ajax response and process
  5. Enable buttons

http://jsbin.com/debawafeci/edit?html,output
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <button class="half payBtn" id="btn_credit_card">Credit Card</button>
  <button class="half payBtn" id="btn_electronic_check">Electronic Check</button>
  
 
<script src="https://code.jquery.com/jquery-2.2.4.js"></script>
  <script>
    $(function(){
      // click function here
      $('.payBtn').attr('disabled','disabled');  // disable button on click
      // process via ajax
      // get ajax response
      // $('.payBtn').removeAttr('disabled'); //this funciton will enable the buttons
    });
 </script>
</body>
</html>

Open in new window

0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 41762295
I'm with Scott -- I'm having a hard time understanding the overall design.  I think you may be asking about AJAX.  jQuery implements an easy-to-use AJAX interface, shown in this article.

But in this context, this question appears to have a backstory that is so wrong that it borders on negligence.  There is a whole industry and legal framework around the thing called "PCI Compliance."  YOU DO NOT WANT TO TOUCH CREDIT CARD DATA, especially, you do not want to transmit and hold the accounts numbers, expiration dates, and CVV strings.  Most payment processors have all the software you need to integrate online payments into your existing banking systems, and you should just use what they provide, with an absolute minimum of your own customization.  

This stuff if not new - it's been around since PayPal was invented a generation ago.  In addition to PCI issues, there are potential criminal penalties, involving handcuffs and prison terms, for mishandling online payments, so please don't take the chance.
0
 

Author Comment

by:brucegust
ID: 41762451
Sorry, gentlemen. I didn't explain it very well, apparently.

I'm not interested in delving into any sensitive / secure information such as CC data. What's happening in some instances is that a customer is getting ready to make a payment. Unbeknownst to them, however, is that they've already made a payment, it just hasn't posted to their bank statement, or something along those lines.

Before they submit any CC data (when they click on the "Credit Card" button), I want to go to the database and look at the date of their last payment. If it's within 30 days, I want to trigger an alert that says, "Your last payment was 7/30/2016" so they're not making double payments.

So, I'm not trying to facilitate a payment. That infrastructure is already in place and I don't need to fool with that. Nor do I need to interact with the Credit Card processor, I simply need to look at the "transaction" table and see when they made their last payment.

I've used AJAX before and perhaps that's what I need for this scenario, but when I think AJAX, I think "form," and my user's not submitting any info. Hence my desire to get some other eyes on this thing.

So, the flow looks like this:

  • User clicks on Credit Card button (this reveals a popup with all of the CC fields etc)
  • Before the CC form is revealed, however, I want to first run a query (from my database, not a CC interface) that looks to see when their last payment was made
  • If their last payment was made within 30 days, an alert comes up to remind the user they have a payment in the system that's less than 30 days old
  • They can continue if they want, but there are some customers who are making more than one payment per month and they're not meaning to. This is what my client wants to put in place to help avoid that.

So, how can I run that query in the context of the JS flow?
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 41762512
jQuery implements an easy-to-use AJAX interface, shown in this article.

But why use AJAX at all?  Why not just look up the date of the last transaction before your server generates the web page?  Then your script can know in advance whether it needs to prompt the user about the date of the last payment.  You can build the prompt right into the HTML as you build the web page.
0
 

Author Comment

by:brucegust
ID: 41762569
Ray, I love the smell of what you're cooking and, frankly, that's kind of what I was hoping for just because I'm still a pig on roller skates when it comes to AJAX. But let me explain back to you what you're suggesting...

Rather than trying to introduce my query in the context of a JS script, instead run my query when the page loads as a straightforward, b flat, PHP melody and perhaps have an IF clause in place that triggers my alert when the page loads?

I'm reading your article and I will confess that since it says "AJAX," I'm wondering if I'm tracking with you.

No doubt there's more than one way to do this, but I want to catch your vision before I just make some assumptions.

What are you thinking?
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 

Author Comment

by:brucegust
ID: 41762574
BTW: I read your article. Very well laid out and explained. Surely you've written enough where you could compile everything into a book, yes? I would buy it! I'd buy the Kindle version to save money, but I would purchase it !
1
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 250 total points
ID: 41762602
Bruce: Thanks for your kind words.

See if this design idea makes sense.  In your application, you would use a database lookup to determine whether the alert is needed.  In this example, I just use the GET request variable.  For any unknown input there is no alert.  If it's Bruce, there is an alert.

Since the PHP runs before the HTML is sent to the client browser, PHP can configure the HTML, CSS, and JS in advance.  A template scheme like this one makes sense in a lot of cases.
https://iconoun.com/demo/temp_brucegust.php
https://iconoun.com/demo/temp_brucegust.php?q=ray
https://iconoun.com/demo/temp_brucegust.php?q=bruce
<?php // demo/temp_brucegust.php
/**
 * https://www.experts-exchange.com/questions/28964280/How-can-I-incorporate-a-PHP-SELECT-statement-at-this-point-in-Javascript.html
 */
error_reporting(E_ALL);


// USE PHP TO CREATE VARIABLES FOR OUR HTML
$out = NULL;
$get = !empty($_GET['q']) ? $_GET['q'] : NULL;
if (strtolower($get) == strtolower('Bruce')) $out = '<script>alert("Hello Bruce!");</script>';


// CREATE OUR WEB PAGE IN HTML5 FORMAT
$htm = <<<HTML5
<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<head>
<meta charset="utf-8" />
<meta name="robots" content="noindex, nofollow" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />

<style type="text/css">
/* STYLE SHEET HERE */
</style>

<script src="https://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function(){
    /* JQUERY CODE HERE */
});
</script>

<title>HTML5 Page With jQuery in UTF-8 Encoding</title>
</head>
<body>

<noscript>Your browsing experience will be much better with JavaScript enabled!</noscript>

$out

<p>Hello World</p>

</body>
</html>
HTML5;


// RENDER THE WEB PAGE
echo $htm;

Open in new window

0
 
LVL 52

Assisted Solution

by:Scott Fell, EE MVE
Scott Fell,  EE MVE earned 250 total points
ID: 41762784
BRUCE: I want to go to the database and look at the date of their last payment. If it's within 30 days
RAY: Why not just look up the date of the last transaction before your server generates the web page?

Exactly that.  

Somewhere you can either add to a field that can be accessed via js or just not output the button at all if you find no payment is needed.   I would do a little of both.

Making the button disabled I think will be less confusing and you can have a message somewhere that they already paid on xx/xx/xxxx.  

Ray, I love the smell of what you're cooking
I think you should smell my hickory smoked hog
20160415_171626.jpg
1
 

Author Comment

by:brucegust
ID: 41762793
It's lunch time and you dare to show me something that amazing when all I've got is McDonald's?

Man...
0
 

Author Comment

by:brucegust
ID: 41763028
Guys, I got it!

It's not an especially complicated solution. I just introduced another session variable, then did a quick and dirty IF statement to see what that value was and if it was greater than zero, I "echo-ed" an alert and it works great!

Thanks!

BTW: https://www.experts-exchange.com/questions/28964436/How-to-write-a-line-break-in-an-alert-box-that's-being-echoed-in-PHP.html
0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Suggested Solutions

This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

706 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now