Archive for the ‘HTML’ Category

Google maps, mySQL locations, PHP service

Wednesday, May 4th, 2016

HTML:

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
    <link rel="stylesheet" href="dealers.css">
</head>
    <body>
        <div class="row mapSection">
            <div class="col-xs-12">

                <div id="map"></div>
                <div id="panel">
                    <div id="entryRow">
                        <div><select id="locationSelect" style="width:100%;visibility:hidden"></select></div>
                        <input type="text" id="addressInput" />
                        <select id="radiusSelect">
                            <option value="5" selected>5 miles</option>
                            <option value="25" selected>25 miles</option>
                            <option value="100">100 miles</option>
                            <option value="200">200 miles</option>
                            <option value="500">500 miles</option>
                        </select>
                        <input type="text" id="find" value="Search"/>
                        <input type="button" id="refresh" value="redo Search"/>
                    </div>
                    <ul class="resultDealers">
                    </ul>
                </div>

            </div>
        </div>

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
        <script src="https://maps.googleapis.com/maps/api/js?key=***YOUR*KEY*HERE***" type="text/javascript"></script>
        <script type="text/javascript" src="Maps.js"></script>
    </body>
</html>

CSS:

body {
  font-family: sans-serif;
  margin: 0px;
  padding: 0px;
}
#map,
#panel {
  height: 500px;
  float: left;
}
#map {
  width: 60%;
}
#entryRow {
  margin: 0 0 0 15px;
}
#panel {
  width: 40%;
}
.resultDealers {
  padding: 0;
  margin: 15px;
  overflow: scroll;
  height: 420px;
}
.resultDealers li {
  list-style-type: none;
  border-left: 1px solid;
  border-top: 1px solid;
  border-right: 1px solid;
  padding: 10px;
}
.resultDealers li:last-child {
  border-bottom: 1px solid;
}
.highlightDealer {
  background: #E8E8E8;
}
.markerBox {
  cursor: pointer;
}
.markerBox:hover {
  background: #E3F4F9;
}
#panel .feature-filter label {
  width: 130px;
}
p.attribution,
p.attribution a {
  color: #666;
}
#find {
  background: #DEDCDC;
  border: 1px solid gray;
  width: 65px;
  padding: 2px;
  text-align: center;
  font-weight: bold;
  cursor: pointer;
  margin-left: 15px;
}
#find:hover {
  background: #F9F4F4;
}
#radiusSelect {
  margin-left: 15px;
}
#addressInput {
  float: left;
  margin-left: 5px;
  padding-left: 10px;
  width: 65px;
}
#locationSelect {
  margin: 10px 5px;
  width: 95% !important;
}

JavaScript:

/* ---------  Start Maps.js  --------- */

Maps Module
//Usage: Maps.init();

Maps = (function ( window, google ) {

	var map,
		markers = [],
		infoWindow,
		locationSelect;

	var load = function load () {
			map = new google.maps.Map(document.getElementById("map"), {
				center: new google.maps.LatLng(40, -100),
				zoom: 4,
				mapTypeId: 'roadmap',
				// scrollWheel: false,
				// zoomControl: false,
				streetViewControl: false,
				rotateControl: false,
				fullscreenControl: false,
				navigationControl: false,
				scaleControl: false,
				// draggable: false,
				mapTypeControl: false,
				mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU}
		});
		infoWindow = new google.maps.InfoWindow();

		locationSelect = document.getElementById("locationSelect");
		locationSelect.onchange = function() {
			var markerNum = locationSelect.options[locationSelect.selectedIndex].value;
			if (markerNum != "none"){
				google.maps.event.trigger(markers[markerNum], 'click');
			}
		};

		refreshMap();

		google.maps.event.addListener(map, 'zoom_changed', function() {
			//$('#radiusSelect option:selected').next().attr('selected', 'selected');
			//console.log(map.getCenter());
			//searchLocationsNear (map.getCenter());
		});

	}

	var bindInfoWindow = function bindInfoWindow ( marker, map, infoWindow, html ) {
      google.maps.event.addListener(marker, 'click', function() {
        infoWindow.setContent(html);
        infoWindow.open(map, marker);
      });
    }

    var refreshMap = function refreshMap () {
    	if(navigator.geolocation) {
			navigator.geolocation.getCurrentPosition(function(position) {

				var latLng = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);

				var geocoder = new google.maps.Geocoder();

				geocoder.geocode({ 'latLng': latLng}, function (results, status) {
					if (status == google.maps.GeocoderStatus.OK) {

						for ( var j = 0; j < results[0].address_components.length; j++ ) {
							for ( var k = 0; k < results[0].address_components[j].types.length; k++ ) {
								if ( results[0].address_components[j].types[k] == "postal_code" ) {
									zipcode = results[0].address_components[j].short_name;
								}
							}
						}

						document.getElementById("addressInput").value = zipcode;
						searchLocations();
					} else {
						console.log("Geocoding failed: " + status);
					}
				});
			});
		}
	}

	var downloadUrl = function downloadUrl ( url, callback ) {
		var request = window.ActiveXObject ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest;
		request.onreadystatechange = function() {
			if ( request.readyState == 4 ) {
				request.onreadystatechange = doNothing;
				callback(request.responseText, request.status);
			}
		};

		request.open('GET', url, true);
		request.send(null);
	}

	var searchLocations = function searchLocations () {
		var address = document.getElementById("addressInput").value;
		var geocoder = new google.maps.Geocoder();
		geocoder.geocode({address: address}, function(results, status) {
			if (status == google.maps.GeocoderStatus.OK) {
	  			searchLocationsNear(results[0].geometry.location);
			} else {
	  			alert(address + ' not found');
			}
		});
	}

	var clearLocations = function clearLocations() {
		infoWindow.close();
		for (var i = 0; i < markers.length; i++) {
			markers[i].setMap(null);
		}
		markers.length = 0;

		locationSelect.innerHTML = "";
		var option = document.createElement("option");
		option.value = "none";
		option.innerHTML = "See all results:";
		locationSelect.appendChild(option);
	}

	var searchLocationsNear = function searchLocationsNear ( center ) {
		clearLocations();

		var radius = document.getElementById('radiusSelect').value;
		var searchUrl = '/dealers.php?lat=' + center.lat() + '&lng=' +  center.lng() + '&radius=' + radius;
		downloadUrl( searchUrl, function(data) {
			var xml = parseXml(data);
			var markerNodes = xml.documentElement.getElementsByTagName("marker");
			var bounds = new google.maps.LatLngBounds();
			for (var i = 0; i < markerNodes.length; i++) {
				var id = markerNodes[i].getAttribute("id");
				var name = markerNodes[i].getAttribute("name");
				var address = markerNodes[i].getAttribute("address");
				var city = markerNodes[i].getAttribute("city");
				var state = markerNodes[i].getAttribute("state");
				var zip = markerNodes[i].getAttribute("zip");
				var url = markerNodes[i].getAttribute("url");
				var email = markerNodes[i].getAttribute("email");
				var distance = parseFloat(markerNodes[i].getAttribute("distance"));
				var latlng = new google.maps.LatLng(
					parseFloat(markerNodes[i].getAttribute("lat")),
					parseFloat(markerNodes[i].getAttribute("lng")));

				createOption(name, distance, i);
				createMarker(id, latlng, name, address, city, state, zip, url, email);
				bounds.extend(latlng);
			}
			map.fitBounds(bounds);
			locationSelect.style.visibility = "visible";
			locationSelect.onchange = function() {
			 var markerNum = locationSelect.options[locationSelect.selectedIndex].value;
			 google.maps.event.trigger(markers[markerNum], 'click');
			};
		});
	}

	var createMarker = function createMarker ( id, latlng, name, address, city, state, zip, url, email ) {
		var html = "<div class='marker-" + id + "'><b>" + name + "</b> <br/>" + address +  "<br/>" + city + " " + state + ", " + zip + "<br />" + url + "<br /><a href='mailto:" + email + "'>" + email + "</a></div>";
		var marker = new google.maps.Marker({
			map: map,
			position: latlng
		});
		google.maps.event.addListener(marker, 'click', function() {
			//infoWindow.setContent(html);
			//infoWindow.open(map, marker);
			$("li[class*='marker-']").removeClass('highlightDealer');
			$("li.marker-" + id).addClass('highlightDealer');
			window.location.href = "#marker-"+ id;
			window.scrollTo(0, 0);

			map.setZoom(16);
			map.setCenter(marker.getPosition());
		});
		markers.push(marker);

		$("#panel ul").append("<li class='markerBox marker-" + id + "'><a name='marker-" + id + "'></a><b>" + name + "</b><br/>" + address +  "<br/>" + city + " " + state + ", " + zip + "<br />" + url + "<br /><a href='mailto:" + email + "'>" + email + "</a></li>");
		$('.marker-' + id).on('click', function() {
			$("li[class*='marker-']").removeClass('highlightDealer');
			$("li.marker-" + id).addClass('highlightDealer');
			map.setZoom(16);
			map.setCenter(marker.getPosition());
		});
	}

	var createOption = function createOption ( name, distance, num ) {
		var option = document.createElement("option");
		option.value = num;
		option.innerHTML = name + "(" + distance.toFixed(1) + ")";
		locationSelect.appendChild(option);
	}

	var parseXml = function parseXml(str) {
		if (window.ActiveXObject) {
			var doc = new ActiveXObject('Microsoft.XMLDOM');
			doc.loadXML(str);
			return doc;
		} else if (window.DOMParser) {
			return (new DOMParser).parseFromString(str, 'text/xml');
		}
	}

    function doNothing() {}

	$('#find').on('click', function() {
		$('#panel ul').empty();
		searchLocations();
	});
	$('#addressInput').on('click', function () {
		$(this).val('');
	});
	$('#radiusSelect').on('change', function () {
		$('#panel ul').empty();
		searchLocations();
	});
	$('#refresh').on('click', function () {
		var bounds = map.getBounds();
		var ne = bounds.getNorthEast(); // LatLng of the north-east corner
		var sw = bounds.getSouthWest(); // LatLng of the south-west corder

		var nw = new google.maps.LatLng(ne.lat(), sw.lng());
		var se = new google.maps.LatLng(sw.lat(), ne.lng());
		console.log('nw: ' + nw);
		console.log('se: ' + se);
		//searchLocationsNear();
		//searchLocations();
	});

	return {
		load: load
	}

})( window, google );

$(function(){
    loadModules.start();
})

var loadModules = loadModules || {};
loadModules.start = function(){
    // Maps module init
    Maps.load();
};
/* ---------  End Maps.js --------- */

PHP:

<?php
    header("Access-Control-Allow-Origin: *");
    $servername = "***Your*DB*URL***";
    $username = "***Your*DB*USERNAME***";
    $password = "***Your*DB*PASS***";
    $dbname = "***Your*DB*NAME***";

    // Get parameters from URL
    $center_lat = $_GET["lat"];
    $center_lng = $_GET["lng"];
    $radius = $_GET["radius"];

    // Start XML file, create parent node
    $dom = new DOMDocument("1.0");
    $node = $dom->createElement("markers");
    $parnode = $dom->appendChild($node);

    // Opens a connection to a mySQL server
    $connection=mysql_connect ($servername, $username, $password);
    if (!$connection) {
      die("Not connected : " . mysql_error());
    }

    // Set the active mySQL database
    $db_selected = mysql_select_db($dbname, $connection);
    if (!$db_selected) {
      die ("Can\'t use db : " . mysql_error());
    }

    // Search the rows in the markers table
    $query = sprintf("SELECT id, name, address, city, state, zip, url, email, lat, lng, ( 3959 * acos( cos( radians('%s') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('%s') ) + sin( radians('%s') ) * sin( radians( lat ) ) ) ) AS distance FROM dealers HAVING distance < '%s' ORDER BY distance LIMIT 0 , 20",
      mysql_real_escape_string($center_lat),
      mysql_real_escape_string($center_lng),
      mysql_real_escape_string($center_lat),
      mysql_real_escape_string($radius));
    $result = mysql_query($query);

    $result = mysql_query($query);
    if (!$result) {
      die("Invalid query: " . mysql_error());
    }

    header("Content-type: text/xml");

    // Iterate through the rows, adding XML nodes for each
    while ($row = @mysql_fetch_assoc($result)){
        $node = $dom->createElement("marker");
        $newnode = $parnode->appendChild($node);
        $newnode->setAttribute("id", $row['id']);
        $newnode->setAttribute("name", $row['name']);
        $newnode->setAttribute("address", $row['address']);
        $newnode->setAttribute("city", $row['city']);
        $newnode->setAttribute("state", $row['state']);
        $newnode->setAttribute("zip", $row['zip']);
        $newnode->setAttribute("url", $row['url']);
        $newnode->setAttribute("email", $row['email']);
        $newnode->setAttribute("lat", $row['lat']);
        $newnode->setAttribute("lng", $row['lng']);
        $newnode->setAttribute("distance", $row['distance']);
    }

    echo $dom->saveXML();

?>

Styling radio buttons

Monday, December 21st, 2015

Hide/replace radio buttons

CSS:

[type="radio"] {
  border: 0; 
  clip: rect(0 0 0 0); 
  height: 1px; margin: -1px; 
  overflow: hidden; 
  padding: 0; 
  position: absolute; 
  width: 1px;
}

[type="radio"] + span {
  display: block;
}

/* the basic, unchecked style */
[type="radio"] + span:before {
  content: '';
  display: inline-block;
  width: 1em;
  height: 1em;
  vertical-align: -0.25em;
  border-radius: .5em;
  border: 0.15em solid @base-gray-medium;
  box-shadow: 0 0 0 0.1em @base-gray-medium;
  margin-right: 0.75em;
  transition: 0.5s ease all;
}

/* the checked style using the :checked pseudo class */
[type="radio"]:checked + span:before {
  background: red;
  box-shadow: 0 0 0 0.1em @base-gray-medium;
}

/* never forget focus styling */
[type="radio"]:focus + span:after {
  content: '\0020\2190';
  font-size: 1.5em;
  line-height: 1;
  vertical-align: -0.125em;
}

Handlebars template markup:

<script id="dealer-list-template" type="text/x-handlebars-template">
	<label for="dealer{{id}}" class="col-xs-10 dealerItem">
		<input type="radio" value="{{title}}" name="dealers" id="dealer{{id}}">
			<span class="dealerTitle">{{title}}</span>
			<span class="dealerAddress">{{address}}</span>
	</label>
	<div class="col-xs-2 distance">{{distance}}</div>
</script>

Foundation 5 Framework Animate Accordion (multiple, with dynamic AJAX content using reflow, and also nested)

Monday, January 27th, 2014

Out of the box there is no animation on these.  I tried for a CSS3 transition but couldn’t get one. If anyone finds one do tell. Anyhow, my current project has 3 accordion levels, the main off-canvas accordion, a second one loaded dynamically via AJAX into the main content area, and third level of accordions nested in each of the 2nd level accordions.

First, I gave them each an id, so that I could address them easily and individually:

<dl class=”accordion firstLevelAccordions” data-accordion> (in the ‘off-canvas’ left)

<dl class=’accordion secondLevelAccordions’ data-accordion> (in the main content right section, content thereof loaded dynamically via AJAX)

<dl class=’accordion thirdLevelAccordions’ data-accordion> (this one nested inside the secondLevelAccordions)

After the dynamic content load, Foundation makes you reflow to find/activate the new content:

$(document).foundation(‘reflow’);

The initialization of each accordion (you could merge these into one function, or parameter-ize the class piece, but for simplicity’s sake, this works just fine):

$(function(){ // onready

// first level off-canvas menu accordions
$(document).on(“click”, “.firstLevelAccordions > dd:not(‘.active’) > a”, function (event) {
$(“.firstLevelAccordions > dd.active”).removeClass(‘active’).children(“.content”).slideUp(1000);
$(this).parent().addClass(‘active’).children(“.content”).slideToggle(1000);
})

$(document).on(“click”, “.firstLevelAccordions > dd.active > a”, function (event) {
$(“.firstLevelAccordions > dd.active”).removeClass(‘active’).children(“.content”).slideUp(1000);
$(this).parent().removeClass(‘active’);//.find(“.content”).slideToggle(“fast”);
})

// second level article list/detail accordions
$(document).on(“click”, “.secondLevelAccordions > dd:not(‘.active’) > a”, function (event) {
$(“.secondLevelAccordions > dd.active”).removeClass(‘active’).children(“.content”).slideUp(1000);
$(this).parent().addClass(‘active’).children(“.content”).slideToggle(1000);
})

$(document).on(“click”, “.secondLevelAccordions > dd.active > a”, function (event) {
$(“.secondLevelAccordions > dd.active”).removeClass(‘active’).children(“.content”).slideUp(1000);
$(this).parent().removeClass(‘active’);//.find(“.content”).slideToggle(“fast”);
})

// third level nested accordions
$(document).on(“click”, “.thirdLevelAccordions > dd:not(‘.active’) > a”, function (event) {
$(“.thirdLevelAccordions > dd.active”).removeClass(‘active’).children(“.content”).slideUp(1000);
$(this).parent().addClass(‘active’).children(“.content”).slideToggle(1000);
})

$(document).on(“click”, “.thirdLevelAccordions > dd.active > a”, function (event) {
$(“.thirdLevelAccordions > dd.active”).removeClass(‘active’).children(“.content”).slideUp(1000);
$(this).parent().removeClass(‘active’);//.find(“.content”).slideToggle(“fast”);
})

});

simple JavaScript allow only digits/numbers in input field

Wednesday, October 23rd, 2013

<input onkeypress=”validate(event)” />

function validate(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode( key );
var regex = /[0-9]/;
if( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}

jQuery .hover change div background-position example

Wednesday, November 16th, 2011

example for reference:

$(“#formButtonSubmit“).hover(function(){
$(this).css({
backgroundPosition: ‘0px 0px’
});
}, function(){
$(this).css({
backgroundPosition: ‘0px 30px’
});
});

Secure HTML form example using PHP htmlentities, passing a token PHP, AJAX submission via jQuery

Wednesday, September 21st, 2011

<? php
// form page (index.php): initialize a session so that we can set a unique, random, encrypted value to a user session
session_start();
$token = md5(uniqid(rand(), true));
$_SESSION[‘token’] = $token;
? >
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<script src=”js/jquery.js” type=”text/javascript”></script>
<script src=”js/jquery.validation.js” type=”text/javascript”></script>
<script src=”js/registerSubmit.js” type=”text/javascript”></script>
</head>
<body>
<!– The Form –>
<form id=”topForm” name=”topForm” method=”post”>
<input type=”hidden” name=”token” id=”token” value=”<? php echo $token; ? >” />
<input name=”emailAddress” id=”emailAddress” value=”Email address” onclick=”if( this.value == ‘Email address’ ){ $(this).val(”); }” onblur=”if( this.value == ”){ $(this).val(‘Email address’); }” />
</form>
</body>
</html>

// The jquery.validation.js class uses a regular expression to stop the process if the email entered isn’t acceptable

;(function($) {
$.validation = {};
$.extend( $.validation, {
email:function(email) {
var filter = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
if ( filter.test(email) ) {
return true;
}
return false;
}
});
})(jQuery);

// The registerSubmit.js submits the entered email via AJAX, returning a success or failure message, to our contactSubmit.php script, which handles the submission of the new email to a database

$(document).ready(function() {

$(“#reg-button”).click(function(){
$(“#topForm”).submit();
});

$(“#topForm”).submit(function(event) {
event.preventDefault();
var $form = $( this ),
emailAddress = $form.find( ‘input[name=”emailAddress”]’ ).val(),
token = $form.find( ‘input[name=”token”]’ ).val(),
formaction = $form.attr( ‘action’ );

if($.validation.email(emailAddress)){
$( “#reg-description” ).html (“submitting…”);
$.ajax({
type: “POST”,
url: “contactSubmit.php”,
data: “firstName=” + firstName + “&lastName=” + lastName + “&emailAddress=” + emailAddress + “&token=” + token,
success: function(){
$( “#reg-description” ).html( “Thank you. You have been registered.” );
},
});
}
else{
$( “#emailAddress” ).val (“Please enter a valid email address”);
}
});
});

// contactSubmit.php:  receive the email, check the token, clean the data, pass to a database layer API

<? php
session_start();

set_include_path(‘DBlayerClass’);
require_once(‘EmailContact.php’);

if (isset($_SESSION[‘token’]) && $_POST[‘token’] == $_SESSION[‘token’]){
if(isset($_POST[’emailAddress’])){
$emailAddress = htmlentities($_POST[’emailAddress’]);
} else { $emailAddress = ”; }

$contact = new EmailContact($emailAddress)

try {
$contact->save();
} catch (Exception $e) {
; // do something
}
//$retrieve = new EmailContact($emailAddress);
//$retrieve->load();
//print_r($retrieve);
//}
? >

Bronto Direct Import API import .csv file (upload) via HTML form post or via PHP CURL with code examples

Tuesday, August 23rd, 2011

We are building a Cassandra based system (of record) to capture emails so that we can handle 100k users converging on an online event as quickly as possible.  Rather than relying on our third party email marketing vendor, Bronto, to handle the volume we could possibly experience, and risk possibly failing (as others doing the same thing recently have done…cough cough….Oprah and Eckhart Tolle), we’ll build our own system that can be tested correctly, and thus handle the volume, and then we’ll dump said new emails in reasonably sized files out to Bronto, who will then send out confirmation emails for us…

This post covers the script that will take file exports from Cassandra (sorry, no Cassandra in this one…), and Post them to Bronto.  Below is an example that uses a standard HTML form Post, for understanding and comprehensiveness, and an example that uses CURL (which easily allows this process to happen as part of an ordinary CRON job).

First we have to set up, and get some connection values, from Bronto:

  • Log into Bronto
  • From the top menu select Home->Settings
  • select Data Exchange
  • scroll to the bottom to Direct Import and grab the following connection values:
    • URL: http://app.bronto.com/mail/subscriber_upload/index/
    • site_id: YOUR_SITE_ID
    • user_id: YOUR_USER_ID
    • key: YOUR_KEY
Further reference, Bronto support docs are here:
https://app.bronto.com/mail/help/help_view/?k=mail:home:api_tracking:tracking_direct_import
 

Next let’s look at what this Post might look like as your common HTML form:

<form method=”post” action=”http://app.bronto.com/mail/subscriber_upload/index/” enctype=”multipart/form-data”>
<input type=”text” name=”source” value=”Test Contacts” />
<input type=”text” name=”format” value=”csv” />
<input type=”file” name=”filename” value=”C:\xampp\htdocs\YOUSITEFOLDERPATH\batch.csv” />
<input type=”text” name=”site_id” value=”YOUR_SITE_ID” />
<input type=”text” name=”user_id” value=”YOUR_USER_ID” />
<input type=”text” name=”key” value=”YOUR_KEY” />
<input type=”submit” name=”submit” value=”submit” />
</form>

Next let’s look at what this Post might look like in a PHP script using CURL:

<? php
$fields = array(
source‘=>”Test contacts“,
format‘=>csv,
filename‘=>’@‘.’C:\xampp\htdocs\YOURSITEFOLDERPATH\batch.csv‘,
site_id‘=>YOUR_SITE_ID,
user_id‘=>YOUR_USER_ID,
key‘=>’YOUR_KEY‘,
);

/* The key here is the ‘@’ above, which tells CURLOPT_POSTFIELDS to UPLOAD that file, parenthesis critical! */

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, ‘http://app.bronto.com/mail/subscriber_upload/index/‘);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
$result = curl_exec($ch);
curl_close($ch);

var_dump($result);
? >

Last but not least, make (or in our case receive from Cassandra export dump) the .csv file to be Posted.
First column, Email, 2nd through n filled with email addresses, save it as .csv comma delineated.
Yes, it’s actually that simple.
I hope this helps somebody.

Create a php page with a form that searches (curls) two separate WordPress applications

Friday, July 29th, 2011

We have many installations where I work, some of them newer, some older, some severely whacked at by coders, some pretty much default installations.

Anyhow, now they want a page from which a visitor could enter a search term, click submit, and get results from all of the separate applications!

Here is my solution:

The new page has your basic self submitting form:

<form action=”” method=”post”>
<label for=”search”>Search:</label>
<input name=”s” type=”text” value=””  />
<input type=”submit” />
</form>

Then, of course, it grabs what has been submitted:

<?php

/**
* Get Search parameters
*/
$search = $_POST[‘s’];
$search = str_replace(” “,”%20”,$search);
echo $search;

?>

This checks to ensure that the user didn’t submit nothing (as WordPress would give us every post as currently coded…! ick).  This would also be a great place to guard against injection attacks (or in the last step of course), to filter what may be searched for, etc., but I’ll leave those concerns for another discussion:

<?php
/**
* If desired search is NOT empty, search, otherwise don’t
*/
if(($search != ”) && ($search != null) && (!empty($search)) )
{
?>

Now we curl in the results from each installation:

<?php
/**
* Get Search results from WP app 1
*/
$sub_req_url = “http://YOURAPP1URLHERE/searchpage.php?s=” . $search;
$ch = curl_init($sub_req_url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$podcast_return = curl_exec($ch);
curl_close($ch);
echo $podcast_return;

/**
* End
*/
?>

<?php
/**
* Get Search results from WP app 2
*/
$sub_req_url = “http://YOURAPP2URLHERE/searchpage.php?s=” . $search;
$ch = curl_init($sub_req_url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$podcast_return = curl_exec($ch);
curl_close($ch);
echo $podcast_return;

/**
* End
*/
?>

Now let’s close our IF block, and maybe provide ELSE if we want to…

<?php
/**
* close if empty block
*/
}
else
{
}
?>

Ok, that’s the end of our new page, again, I’ll leave formatting of the results and the rest of the page to another discussion.  Now let’s make the above mentioned search pages “searchpage.php” (make one for EACH APP, lives in the ROOT of EACH WP installation that we’re searching!):

<?php
/**
* WordPress App 1 Post Results Pull-In
*/
define(‘WP_USE_THEMES‘, true);
include(‘wp-load.php’ );
$query = new WP_Query(‘s=’ . $_GET[‘s’]);
if ($query->have_posts()) : while ($query->have_posts()) : $query->the_post(); ?>

/* Again, how you choose to skin the results could be implemented here, but I’ll leave that up to you… */

<div id=”post-<?php the_ID(); ?>“>
<h2><?php the_title(); ?></h2>
<div>
<?php the_content(‘<p>Read the rest of this page &raquo;</p>‘); ?>
<?php wp_link_pages(array(‘before’ => ‘<p><strong>Pages:</strong> ‘, ‘after’ => ‘</p>‘, ‘next_or_number’ => ‘number’)); ?>
</div>
</div>
<?php endwhile; endif; ?>

Whoohoo! Great Work!

Snippets: HTML object swf embed within a WordPress post snag it n’ publish it code excerpt

Wednesday, December 29th, 2010

<object height=”24″ width=”500″ codebase=”http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0″ classid=”clsid:D27CDB6E-AE6D-11cf-96B8-444553540000″><param value=”file=http://www.site.net/track.mp3&amp;image=http://www.site.net/trackImage.jpg” name=”flashvars”><param value=”http://www.site.com/swf/player.swf” name=”movie”><embed height=”24″ width=”500″ flashvars=”file=http://www.site.net/track.mp3″ pluginspage=”http://www.macromedia.com/go/getflashplayer” type=”application/x-shockwave-flash” src=”http://www.site.com/swf/player.swf”></object>

anchor tag mailto subject body link example

Tuesday, December 14th, 2010

<a href=”mailto:?subject=Whatever you want the subject to be goes here&body=Whatever you want the body text to be goes here%0Aurl: http://www.alexyz.com/”>

WordPress limit search form to a category

Thursday, December 9th, 2010

example:

 

<script>
function submitter()
{
track_it(‘/podcast/searchFormSubmit/’);
document.searchform.submit();
}

</script>

 

<form method=”get” name=”searchform” id=”searchform” action=”<?php bloginfo(‘url’); ?>/”>

 

<input type=”text” value=”<?php the_search_query(); ?>” name=”s” id=”s” onclick=”this.value=””/>

 

This is the important new line, 5 is an example category id

 

<input type=”hidden” name=”cat” value=”5″ />

 

<a href=”javascript:submitter()” style=”text-decoration:none;font-size:11px;margin:0 0 0 5px;position:absolute;top:0px;”><img src=”wp-content/themes/New/images/go.png” onmouseover=”this.src=’wp-content/themes/New/images/go-over.png'” onmouseout=”this.src=’wp-content/themes/New/images/go.png'” border=”0″ />

 

</a>
</form>

 

source: http://wpgarage.com/code-snippets/how-to-hack-the-wordpress-search-function-search-categories-and-child-categories/

 

I always like to have a nice simple AJAX example on hand, you never know…

Tuesday, July 27th, 2010

reference:

http://w3schools.com/php/php_ajax_php.asp

HTML:

<html>
<head>
<script type=”text/javascript”>
function showHint(str)
{
if (str.length==0)
{
document.getElementById(“txtHint”).innerHTML=””;
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject(“Microsoft.XMLHTTP”);
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById(“txtHint”).innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open(“GET”,”gethint.php?q=”+str,true);
xmlhttp.send();
}
</script>
</head
<body>

<p><b>Start typing a name in the input field below:</b></p>
<form>
First name: <input type=”text” onkeyup=”showHint(this.value)” size=”20″ />
</form>
<p>Suggestions: <span id=”txtHint”></span></p>

</body>
</html>

Script:

<?php
// Fill up array with names
$a[]=”Anna”;
$a[]=”Brittany”;
$a[]=”Cinderella”;
$a[]=”Diana”;
$a[]=”Eva”;
$a[]=”Fiona”;
$a[]=”Gunda”;
$a[]=”Hege”;
$a[]=”Inga”;
$a[]=”Johanna”;
$a[]=”Kitty”;
$a[]=”Linda”;
$a[]=”Nina”;
$a[]=”Ophelia”;
$a[]=”Petunia”;
$a[]=”Amanda”;
$a[]=”Raquel”;
$a[]=”Cindy”;
$a[]=”Doris”;
$a[]=”Eve”;
$a[]=”Evita”;
$a[]=”Sunniva”;
$a[]=”Tove”;
$a[]=”Unni”;
$a[]=”Violet”;
$a[]=”Liza”;
$a[]=”Elizabeth”;
$a[]=”Ellen”;
$a[]=”Wenche”;
$a[]=”Vicky”;

//get the q parameter from URL
$q=$_GET[“q”];

//lookup all hints from array if length of q>0
if (strlen($q) > 0)
{
$hint=””;
for($i=0; $i<count($a); $i++)
{
if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))
{
if ($hint==””)
{
$hint=$a[$i];
}
else
{
$hint=$hint.” , “.$a[$i];
}
}
}
}

// Set output to “no suggestion” if no hint were found
// or to the correct values
if ($hint == “”)
{
$response=”no suggestion”;
}
else
{
$response=$hint;
}

//output the response
echo $response;
?>

jQuery bind select change to anchor window.open variable

Thursday, April 29th, 2010

add window.open() to an anchor tag…

HTML:

select dropdown changes the source:

<div class=”name”>
<select name=”tpom” style=”float: left; width: 100px; margin-right:20px; border: 1px solid #5A3C18;” >
<option value=”downloader.php?file=folder/file.mp3″>Mp3</option>
<option value=”downloader.php?file=folder/file.zip”>Zip</option>
<option value=”downloader.php?file=folder/file.m4b”>Ipod</option>
</select>

link or button gets source from dropdown via jQuery onReady function:

$(“div.name select”).bind(“change”,function(){
$(‘#button_download’).attr(‘href’,this.value);
windowUrl = $(this).val();
//console.log(windowUrl);
});

<a onclick=”window.open(windowUrl,’download’);return false;” id=”button_download”>Download</a>

meta no archive tag

Wednesday, April 28th, 2010

<META content=”noarchive” NAME=”robots”>

HTML form field readonly and disable

Thursday, April 22nd, 2010

<input type=”text” readonly=”readonly” …. />

and equally useful

<input type=”text” disabled=’disabled’ …/>

Javascript HTML form field onFocus onBlur

Tuesday, April 13th, 2010

<input name=”email” id=”email” type=”text” value=”Email” onFocus=”if(this.value == ‘Email’) this.value = ”;” onBlur=”if(this.value == ”) this.value = ‘Email’;”/>

Semantic value: ul li, ol li vs. dl dt dd

Monday, March 8th, 2010
<dl>
<dt>Name: </dt>
<dd>John Don</dd>

<dt>Age: </dt>
<dd>64</dd>

<dt>Gender: </dt>
<dd>Male</dd>

<dt>Day of Birth:</dt>
<dd>12th May 1946</dd>
</dl>
VS.
Unordered lists
Use a <ul> tag where the order of items is not significant.
Ordered lists
Use an <ol> tag where the order of items is significant, e.g. listing events in time order, or race results

HTML Meta redirect 301 forward

Wednesday, March 3rd, 2010

<html>
<head>
<meta http-equiv=”refresh” content=”0;url=http://www.google.com”>
</head>
<body>
<a href=”http://www.google.com”>This page has moved</a>
</body>
</html>