Web Service using JSONP from External Domain – PHP – JQuery
Posted by dan in Code, Javascript, PHP, jQuery on February 3, 2012
You may want to look at this previous post where I setup a PHP Webservice that uses JSON PDO – Accessed by JQuery AJAX
OK, so this code will use php to generate the JSON code that will get delivered over the internet to the JSONP (JSON Padding) client on an external domain. This allows your webservice to be available too whoever wants to call it.
Here is the PHP Code: (Not all of it, but enough to get the idea)
//http://SERVER_domain.com/webservice.php private function GetTriviaTag($row) { $t = new Tag(); $t->id = $row['id']; $t->triviaid = $row['triviaid']; $t->tagid = $row['tagid']; return $t; } public function GetWhere($where) { $retArray; $sql = "SELECT * FROM trivia_tags WHERE {$where}"; foreach ($this->pdo->query($sql) as $row) { $retArray[] = $this->GetTriviaTag($row); } return $retArray; } $where = " (1 = 1)"; // THIS WILL SELECT ALL $tarray = GetWhere($where); //OUTPUT JSON: header('Content-type: application/json'); echo $_GET['callback']; // <-- THIS IS IMPORTANT FOR EXTERNAL DOMAIN ACCESS!!! echo "(" . json_encode($tarray) . ")";
And now, to access it from javascript in an external domain (non – SERVER_domain.com ):
http://CLIENT_domain.com/Test.html:
<html> <head> <title>Test</title> <script src="http://code.jquery.com/jquery-latest.js"></script> </head> <body> <div id="triviaQuestions"> loading... </div> <script> $(function() { // THE 'callback=?' in this request is IMPORTANT FOR EXTERNAL DOMAIN ACCESS!!! $.getJSON('http://SERVER_domain.com/webservice.php&callback=?', function(data) { var items = []; var htmlResult = ""; $.each(data, function(key, val) { htmlResult += "<br />Q: "+ val.id +", '"+ val.question +""; }); $('#triviaQuestions').html(htmlResult); }); }); </script> </body> </html>
PHP Webservice that uses JSON PDO – Accessed by JQuery AJAX
Posted by dan in Javascript, PHP, jQuery on January 6, 2012
You may want to look at this previous post where I setup a Web Service using JSONP from External Domain – PHP – JQuery
The HTML that calls the Javascript:
<div id="taglist"></div> <input name="searchTags" id="searchTags" type="text" /> <input type="button" name="searchtags" onclick="getTags()" value="search"/> <div id="tagresult"> </div>
The JavaScript (JQuery) AJAX Request and Response Processing:
function getTags() { var q = $('#searchTags').val(); $.getJSON('ws.php?type=tag&wN=name&wO=like&wV=' + q, function(data) { var items = []; var htmlResult = ""; $.each(data, function(key, val) { //As you can see, you can access the JSON (at the bottom of the page) by doing val.PROPERTYNAME: htmlResult += "<br />Add : <a href=\"#\" onclick=\"addTag("+ val.id +", '"+ val.getfullname +"'); return false;\">"+ val.getfullname +"</a>"; }); $('#tagresult').html(htmlResult); }); }
PHP Code that returns JSON in the PHP file called by the AJAX: (ws.php)
$ta = new TagAccess(); $tarray = $ta->GetTagsWhere(" {$whereName} LIKE '%{$whereVariable}%'"); header('Content-type: application/json'); echo "", json_encode($tarray), "";
The GetTagsWhere Helper Function:
public function GetTagsWhere($where) { $retArray; $sql = "SELECT * FROM tags WHERE {$where}"; // THE PDO Object was created previously foreach ($this->pdo->query($sql) as $row) { $retArray[] = $this->GetTag($row); } return $retArray; }
JSON Returned:
[{"id":"4","name":"FICTION","parentid":"3","getfullname":"BOOKS > FICTION"},{"id":"5","name":"NON-FICTION","parentid":"3","getfullname":"BOOKS > NON-FICTION"}]
Fantastic Thrift Store – Hours
Fan-tastic Thrift Store Hours
Monday: 10am – 6pm
Tuesday: 10am – 6pm
Wednesday: 10am – 6pm
Thursday: 10am – 6pm
Friday: 10am – 6pm
Saturday: 10am – 6pm
Sunday: CLOSED
I thought I would call and post what they said since I I couldn’t find the store hours for Fantastic Thrift anywhere online.
ASP.Net Update Panel – Javascript Event – jQuery Click
Posted by dan in .Net, Code, Javascript, jQuery on November 7, 2011
I needed to add a onclick event to a textbox in asp.net to change it to remove text from a textbox onClick when it is clicked.
The normal code would look something like this:
1 | <asp:TextBox ID="txtStoreLocatorZip" ValidationGroup="CustomerServiceEmail" runat="server" Text="Enter Zip" CssClass="txtStoreLocatorZip_CssClass" /> |
1 2 3 4 5 6 7 8 9 | <script> if ($('.txtStoreLocatorZip_CssClass').val() == 'Enter Zip') { $('.txtStoreLocatorZip_CssClass').click(function () { if ($('.txtStoreLocatorZip_CssClass').val() == 'Enter Zip') { $('.txtStoreLocatorZip_CssClass').val(''); } }); } </script> |
But, this won’t quite work because my textbox is in a UpdatePanel’s ContentTemplate and the javascript is not read on postback.
So, This is what I ended up doing (a simplified version):
1 2 3 4 5 | <asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional"> <ContentTemplate> <asp:TextBox ID="txtStoreLocatorZip" ValidationGroup="CustomerServiceEmail" runat="server" Text="Enter Zip" CssClass="txtStoreLocatorZip_CssClass" /> </ContentTemplate> </asp:UpdatePanel> |
1 2 3 4 5 6 7 8 9 10 11 12 | <script> Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler); function endRequestHandler(sender, args) { if ($('.txtStoreLocatorZip_CssClass').val() == 'Enter Zip') { $('.txtStoreLocatorZip_CssClass').click(function () { if ($('.txtStoreLocatorZip_CssClass').val() == 'Enter Zip') { $('.txtStoreLocatorZip_CssClass').val(''); } }); } } </script> |
This will add an endRequest handler to the end of the partial page postback so that you can call a nice little function at the end of it.
Hope this helps some people!
Roasted Winter Squash Recipe

Roasted Winter Squash
Recipe:
- Winter Squash, or really anything gourd-like.
The spread on top contains:
- Some of the squash seeds
- Sage
- Something spicy, i used jalapeno, but you can use anything with kick, or don’t.
- Cinnamon
- Salt
- Black Pepper
- A little oil (olive)
Instruction:
Cut and place squash on cooking sheet, cut/grind up the remaining ingredients, add oil. rub on top.
Cover with tin-foil to prevent burning.
Cook for ~20 min.
Uncover and cook till golden brown/not burnt. (~10)
Bonus tip: throw in the rest of the seeds to cook them too. They are a good snack.
Asp.Net – Adding Parameters to CommandType.Text
This is how you add parameters to a standard CommandType.Text SQL call.
This should prevent sql injection attacks.
Using conSQL = New SqlConnection("CONNECTION STRING TO DATABASE") Try str = "SELECT * FROM TableName where customerid = @CustomerID and CartType = @CartType" cmdSQL = New SqlCommand(str, conSQL) cmdSQL.CommandType = CommandType.Text cmdSQL.Parameters.AddWithValue("@CustomerID", CustomerID) cmdSQL.Parameters.AddWithValue("@CartType", cartType) cartcount = cmdSQL.ExecuteScalar() Catch ex As Exception cartcount = 0 End Try End Using
Free Webcam Security – Dorgem – WinSCP

This is how you setup a free home security webcam using dorgem and winscp.exe.
First Download:
- Download WinSCP and install it.http://winscp.net/
- Download Dorgem and install it. http://dorgem.sourceforge.net/
Next Configure Dorgem:
Most people are going to want to use the “Web Server” option. This will setup a webserver with your webcam on it…. Pretty straight forward.
But, when I was looking this up, I couldn’t find anywhere that tells you how to use WinSCP. So here I go:
First Configure WinSCP
- Open WinSCP
- New
- Type in all the correct info in session
- Make sure you set a default folder under Environment->Directories->Remote Directory
- Save… and remember the name of the session
- Connect and make sure you set it to remember passwords and everything
Second Configure Dorgem:
- Open Dorgem
- Preview the source
- Click “Store Settings”
- Add
- External Program
- Name it something to remember
- Check Enable
- Command: “C:\Program Files (x86)\WinSCP\winscp.exe” name_of@winscp_session.com /upload %s /defaults
- OK
- Click “Capture Now” to test it out.
- You should now see a tmp file on the WinSCP server.
- If you dont, then you might want to try changing the path to WinSCP in the command or double check the name of the stored WinSCP session in the command.
- Then, you can enable motion detection under “options” on the main screen
Hope this helps some people!
ASPDotNetStoreFront: Adding Topic to XML Packages or .aspx Pages
This is how you add a DotNetStoreFront’s Topic into a XMLPackage:
<xsl:value-of select="aspdnsf:Topic('TOPIC_NAME')" disable-output-escaping="yes"/>
Now, if you want to add it to a .aspx or .ascx page on dnsf:
<aspdnsf:Topic runat="server" ID="Topic1" TopicName="TOPIC_NAME" />
Me and Micaela at the Beach
yeah.. we cool
Simple PHP Pseudo Proxy

This is the code for a simple php pseudo proxy. If you are blocked by a firewall and google cache isn’t working for some reason. You can use a url with this php file in it:
<?php $filename = $_GET["url"]; if (isset($filename)) { $handle = fopen($filename, "rb"); $contents = stream_get_contents($handle); print $contents; fclose($handle); } else { echo "url"; ?> <form method="GET"> <input type="text" name="url" /><input type="submit"/> </form> <?php } ?>
Then you can go to where the url is hosted and try something like this:
index.php?url=http%3A%2F%2Fwww.last.fm%2Fuser%2Fdanfolkes%2Fcharts%3Frangetype%3D6month%26subtype%3Dartists
FoxToPhone – Send Links from Firefox to Android – (Like ChromeToPhone)

Just found out about FoxToPhone.
It gives you a little button in Firefox that allows you to send it to be opened by your browser on your Android phone.

The integration is seamless and it works like a charm.
Useful Links:
- Firefox Plugin: FoxToPhone
- Android App: Google Chrome to Phone
Small After Lunch Motorcycle Ride
This was a fun little motorcycle ride after my lunch break today.
Bon Air, VA
- curves
- hills
- train tracks
- not a ton of traffic
- paved
Facebook Website Integration – HTML
Posted by dan in Code, Javascript, PHP, jQuery on May 25, 2011

To integrate Facebook on to a website without the use of a facebook app you need these things:
- Facebook Page RSS Feed (can be tricky)
- Feedburner Account (free,easy) (here)
Once you have both of those things you can do this in feedburner:
- Add a new feed (your facebook url)
- Go to the publicize tab
- Go to BuzzBoost
- Sroll down and fill out the form, you will be given html code.
-
<script src="http://feeds.feedburner.com/DanielFolkessFacebookStatusUpdates?format=sigpro" type="text/javascript" ></script> <noscript><p>Subscribe to RSS headline updates from: <a href="http://feeds.feedburner.com/DanielFolkessFacebookStatusUpdates"></a> <br/>Powered by FeedBurner</p> </noscript>
- Preview:
And that’s it!
You can now style it up a little bit with some CSS and stuff.
Java – Singleton / Global – Data Access – SQLite
This will make a Java global object:
import java.io.File; import java.io.IOException; import com.almworks.sqlite4java.SQLite; import com.almworks.sqlite4java.SQLiteConnection; import com.almworks.sqlite4java.SQLiteException; import com.almworks.sqlite4java.SQLiteJob; import com.almworks.sqlite4java.SQLiteQueue; import com.almworks.sqlite4java.SQLiteStatement; public final class DataAccess { // Singleton Stuff private static class SingletonHolder { public static final DataAccess INSTANCE = new DataAccess(); } public static DataAccess getInstance() { return SingletonHolder.INSTANCE; } // End Singleton Stuff private String HomePath = ""; private File DBFile; private static SQLiteQueue queue; private boolean initalized = false; private DataAccess() { if (!initalized) { initDB(); initalized = true; } } private void initDB() { DBFile = locateDBFile(); DeleteDatabaseContents(); } private File locateDBFile() { File f = null; try{ HomePath = System.getProperty("user.home"); System.out.println("HomePath: " + HomePath); f = new File(HomePath + "/database.sqlite"); if (f.canRead()) return f; else { boolean success = f.createNewFile(); if (success) { // File did not exist and was created } else { // File already exists } } } catch (IOException e) { //Maybe try a new directory. } return f; } private void DeleteDatabaseContents() { queue.execute(new SQLiteJob<Object>() { protected Object job(SQLiteConnection connection) throws SQLiteException { // this method is called from database thread and passed the connection StringBuilder sb = new StringBuilder(); sb.append("DROP TABLE IF EXISTS Playlist;"); sb.append("DROP TABLE IF EXISTS Settings;"); //sb.append("DELETE FROM someTable;"); //sb.append("DELETE FROM someTable;"); connection.exec(sb.toString()); return null; } }); } public String getHomePath() { return HomePath; } }
Now you can run this from anywhere:
DataAccess da; da = DataAccess.getInstance();
Source: http://en.wikipedia.org/wiki/Singleton_pattern
PHP API – Google Calendar – Updating Visibility
The Privacy / Visibility Part:
$event->visibility->value = "http://schemas.google.com/g/2005#event.private";
Here it is in context: Read the rest of this entry »
Minecraft – Script – Backup – Update Server – Restart
This is the script I use that will:
- Automatically backup minecraft map
- Automatically update minecraft server
- Automatically restart the server if it stops or dies
#!/bin/bash while [ true ]; do # make md5 of current file for update check. md5sum minecraft_server.jar > minecraft_server.jar.md5 wget -o updatelog.log -N --trust-server-names http://www.minecraft.net/download/minecraft_server.jar # display updated status if md5sum -c --status minecraft_server.jar.md5 then echo "Server Up to Date." else echo "Updated Server!" fi java -Xmx1024M -Xms1024M -jar minecraft_server.jar nogui rsync -a --delete --progress /home/dan/serv/minecraft/world "/home/dan/serv/minecraft/bak/world"`eval date +%Y%m%d`"" done
Code Explained:
This will put the server in an infinite loop. You can kill it by hitting Control+C a couple times in a row.
while [ true ]; do
This will make a hash of the current minecraft_server.jar and then download the newest copy using wget.
md5sum minecraft_server.jar > minecraft_server.jar.md5 wget -o updatelog.log -N --trust-server-names http://www.minecraft.net/download/minecraft_server.jar
This will run minecraft in headless mode and with a limit on RAM.
java -Xmx1024M -Xms1024M -jar minecraft_server.jar nogui
This will create a backup of the minecraft world folder in a backup folder. You probably should work on this part.
rsync -a --delete --progress /path/to/minecraft/world "/path/to/minecraft/bak/world"`eval date
Well, hope this helps someone. Have a good day.
Reading some Rousseau

Discourse on the Origins of Inequality
Rsync – Speed Limit – Trickle – Slow
Install rsync and trickle:
sudo apt-get install rsync sudo apt-get install trickle
Now you can run rsync:
This will download at a limit of 80 KB/s from host:
rsync -auvPe "trickle -d 80 ssh" user@host:/src/ /dst/
Explanation of Commands:
-a, --archive archive mode; equals -rlptgoD (no -H,-A,-X) -u, --update skip files that are newer on the receiver -v, --verbose increase verbosity -P --progress show progress during transfer -e, --rsh=COMMAND specify the remote shell to use trickle -d 80 = -d rate Limit the download bandwidth consumption to rate KB/s.
Outlook Rule : Only at Specific Times

Lets say you want to have a rule in outlook send to you only between specific times in the day.
- Only after 6pm and before 8am
- Only on your lunch hour
- When you are not at work
I will explain this by having emails forward to my cell phone, only when I am normally not at the office. (From 6pm-8am) This way, I will be able to receive important emails that may require special outside assistance.
What I do is:
- Create a special category called FWD
- Use other rules to set messages into the FWD category if I want them forwarded. (Explained Below)
- Then, create a rule to run last in the rules list called FWD Rule
- *Important Part* This will check the time on the messages, if it’s within the specified hours, it will forward the email (Explained Below)
Creating a Rule to set the FWD Category:
Your Rule Description should look something like this. The important part is that it is assigning it to the FWD Category:
Apply this rule after the message arrives
with 'Emergency from client' in the subject
and marked as 'high importance'
and assigned to 'FWD' CategoryThe Rule that will email header* for UTC times. Make sure it’s assigned to the FWD category. And then FWD it:
Apply this rule after the message arrives
with '2011 23:' or '2011 02:' or ... '2011 10:' in the message header
and assigned to 'FWD' category
forward it to 'email@example.com'* This should work on most emails, but if you want to look at the email header Right-click on the message in the Inbox and select Message Options.
* I included the 2011 and the colon to make it more specific.
UTC Time for 6pm – 8am:
Email Header contained:
X-OriginalArrivalTime: 18 Feb 2011 03:23:52.0368 (UTC)
So I searched for:
2011 23:,2011 01:,2011 02:,2011 03:,2011 04:,2011 05:,2011 06:,2011 07:,2011 08:,2011 09:,2011 10:,2011 11:
jQuery – Ajax – Extra Parameters – GET, success
Posted by dan in Javascript, jQuery on February 11, 2011

Here is the standard jQuery Ajax call with success handler as well as the ability to pass another parameter to an external function:
$.ajax({ type: "GET", url: Humancurl, dataType: "xml", success: function(data){ NameOfFunctionToParseReturnedData(data,ExtraParameter); } });
Here is the standard jquery ajax call with success handler:
$.ajax({ url: 'ajax/test.html', success: function(data) { $('.result').html(data); alert('Load was performed.'+data); } });
Gulliver, the Christmas Elf
Gulliver, the Christmas Elf, originally uploaded by danfolkes.
Gulliver is very happy because he has both a good family and an awesome new jacket.
Peanut Butter, Banana, Marshmallow
This is a Peanut Butter, Banana, Marshmallow sandwhich that some friends and I made on a camping trip last year.
Digital Bar
Digital Bar, originally uploaded by danfolkes.
Car stereo thing









