Nov 9 2009

This is How Credit Card Numbers Are Generated

I was reading an article today in one of my favorite publications about how to get free trials without actually using your credit card by generating valid credit card numbers using a simple algorithm called the Luhn check. So I wrote a little script that generates credit card numbers that will be deemed valid by most software checks. This will work because the service won’t know that the credit card is invalid until they actually try to charge it. Well, the card may be valid since my script uses random numbers. Obviously this if for informational purposes only and should never actually be used.

Most credit card numbers are validated using an algorithm called the “Luhn check”. This is a very simple algorithm that doubles the odd digits and does a sum to see if the number is divisible by 10. The credit card companies use a slightly different version that involves a check digit as the last digit. To generate a credit card number that will pass most validation software (as long as they don’t actually try to process the credit card) one only needs to follow these steps to make sure that the generated credit card is valid.

Choose 16 random numbers starting with a 3,4,5 or 6.
Starting with the first digit, double every other number.

If doubling a number results in a two digit number, add those digits together to produce a single digit number

Replace the odd digits with the new ones just created. You should now have 16 numbers consisting of all the new numbers and the original even numbers

Add up all sixteen numbers.

Manipulate the check digit so that the sum is divisible by 10.

Replace the last digit of the original random string with the new manipulated check digit.

Thats really all there is to it. Check out the source of my javascript credit card generator if you want to see how to generate and validate the credit card numbers.

The reason for starting with a 3,4,5, or 6 is that different card types start with different digit. The 3 is American Express, 4 is Visa, 5 is Master Card, 6 is a Discover Card.

Some companies use more digits to show that the card is from them. For example 5254 is a Master Card from the Bank of America and 4013 shows that it is a Visa card from Citibank. Also note that the expiry date has nothing at all to do with the card number.

Share

Jul 28 2009

JavaScript innerText and textContent

I was having an issue with the javascript innerText property today. I was to lazy to convert the legacy code that I was working on to use proper DOM so I did some reading on the issue.

Turns out that FireFox doesn’t use innerText at all. Apparently the proper DOM property to use is textContent. textContent does basically the same thing as innerText.

A not so pretty solution to this issue is to check at the start of the script whether the browser supports innerText or textContent. I found a few resources that allowed me to copy and paste a few lines to make everything work.

This one which I found on coderlab is a little bulky but it gets the job done. It checks which property is available and then forces the programmer to check that flag every time he wants to use the property.


var hasInnerText =
(document.getElementsByTagName("body")[0].innerText\
 != undefined) ? true : false;
var elem = document.getElementById('id');
if(!hasInnerText){
    elem.textContent = value;
} else{
    elem.innerText = value;
}

This is the method I actually used. I just or’d the two different properties together and it seemed to work. I guess one will always be undefined.


var message = elem.innerText || elem.textContent || "";

At least FireFox is following the standards unlike Internet Explorer which always needs special css and javascript. Making everything work in Internet Explorer always adds hours onto development time…

Share

Jun 22 2009

Update Twitter using Command Line, Javascript, Or PHP.

Everyone seems to be all about Twitter so here’s some simple examples of how to update your Twitter status from a command line prompt, web server or simple html web site. These three examples require curl so install it if you don’t already have it. For these examples I’ll be using my Twitter user name ‘codytaylor1234’. My password is not ‘mypassword’ so make sure you put in your own information.

The easiest way to update your Twitter account is to just call curl from the command line with this command.


curl --basic --user "codytaylor1234:mypassword" --data-ascii 
"status=This Twitter update brought to you by curl on the command line" 
"http://twitter.com/statuses/update.json"


To update your Twitter status with PHP you are going to want to do the same sort of thing but with a bit more typing.

<?php
$username = 'codytaylor1234';
$password = 'mypassword';

$update = 'This Twitter update is from a php script using curl';

$url = 'http://twitter.com/statuses/update.json';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "$url");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "status=".$update);
curl_setopt($ch, CURLOPT_USERPWD, $username.":".$password);
$result = curl_exec($ch);
curl_close($ch);

if($result)
    echo 'success';

?>;

Since a cross-domain request in Javascript isn’t really an option we have to create a proxy using PHP in order to authenticate the user on the Twitter API. If anyone knows an easy way authenticate a Twitter user using only javascript I’d love to hear it. Anyway if we replace a small amount of code in the above example and put it in a file then we can use a simple ajax request to update our Twitter status. So the new PHP file would be:


<?php
$username = $_POST['username'];
$password = $_POST['password'];

$update = $_POST['update'];

$url = 'http://twitter.com/statuses/update.json';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "$url");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "status=".$update);
curl_setopt($ch, CURLOPT_USERPWD, $username.":".$password);
$result = curl_exec($ch);
curl_close($ch);

?>

For this example I called that php file ‘twitter-update.php’. Now that we have our simple proxy we can update our twitter status with a simple html form and a little ajax. I used the prototype framework for my javascript.


<script src="includes/prototype.js" type="text/javascript">
<script type='text/javascript'>
function update_twitter()
{
  var param_string = "username="+$('username').value+"&password="+
        $('password').value+"&update="+$('update').value;
  alert(param_string);
  var options = {
    method: "post",
    parameters: param_string,
    onSuccess: function (xhr, Json) {
      alert("Response received successfully.");
    },
    onFailure: function (xhr, Json) {
      alert("Request was unsuccessful.");
    }
  };
  
  var oRequest = new Ajax.Request("twitter-update.php", options);
}

</script>

Obviously this is for example purposes only and if you’re actually using it for production then you should edit it a lot. Now for the last little bit here’s the simple html form that starts it all.


User Name : <input type='text' id='username' value='codytaylor1234'><br>
Password  : <input type='password' id='password' value='mypassword'><br>
New Status : <input type='text' id='update' 
value='Twitter Update from html/javascript/php'><br>
<input type='button' value="Update Twitter" onclick='update_twitter();'>

Share

Jun 9 2009

Adding Sack Ajax To Your WordPress Plugin’s Admin Page

Using my previous wordpress example plugin I’m going to demonstrate how to use ajax within the admin panel. WordPress uses the Simple AJAX Code-Kit (SACK) which is relatively easy to use and understand.

For this example I’m going to expand on my previous example and add a simple javascript function that queries some data from the server. WordPress forces us to do this in a roundabout way. First we have to add two new function hooks. One prints my javascript function in the scripts section of the admin panel and the other is the code that gets called by the ajax sack request.


//add my custom ajax function to the scripts section in the admin panel
add_action('admin_print_scripts', 'ajax_request');

//add data returning ajax refresh table function
add_action('wp_ajax_do_something', 'get_random_number');

The ajax_request function is a shell function for the javascript ajax call get_random_number_from_server which is our sack ajax request. Note that we are calling the admin-ajax.php script. This script will handle the calling of the get_random_number function for us because of the action defined above.


//This function will print out in the header section. 
//Put all your javascript in this function.
function ajax_request()
{
        //print out the sack ajax library
        wp_print_scripts( array( 'sack' ));  
  ?>
  <script type="text/javascript">
  //<![CDATA[
    
  function get_random_number_from_server()
  {
    //creates the sack object and 
                //gives it the url that it should request to.
    var mysack = new sack( '<?php 
                bloginfo( "wpurl" ); ?>/wp-admin/admin-ajax.php' );    
        
    mysack.execute = 1;   //execute whatever is returned
    mysack.method = 'POST';
    
    //Set POST fields
    mysack.setVar( "action", "do_something" );
        
    mysack.encVar( "cookie", document.cookie, false );
    mysack.onError = function() { alert('Ajax Error')};
    mysack.runAJAX();  //run the result

    return true;

  } // end of JavaScript function myplugin_ajax_elevation
  //]]>
  </script>
  <?php
  
}

This is the php function that is called by the javascript function above. It spits out a alert javascript function and then dies. Not sure why but it is recommended to die in this function.


//This is the server side code for the ajax sack request
function get_random_number()
{
  $minimum_number = 0;
  $maximum_number = 100;
  die("alert('".rand($minimum_number,$maximum_number)."');");
} 

This code can now be run like the following in your plugins admin page.


<input type='button' value='Get Random Number' 
onclick='get_random_number_from_server();'>

When the button is hit a popup with a random number in it will pop up. Here’s a link to the entire example plugin code.

Share

Jun 3 2009

10 Things To Know About JSON (JSON Javascript Examples)

I used JSON for the first time today and it’s really nothing special. I’ve heard about it a few times but never really given it much thought and theres no reason I should have. Here is the list of all you really need to know about this syntax for passing around name value pairs and arrays to javascript.

  1. JSON is an acronym for ‘Javascript Object Notation’.
  2. JSON is fast. Mostly because it is recognized natively by Javascript so there’s no processing overhead.
  3. JSON is an ordered list of name value pairs.
  4. JSON is so much easier to read and write than XML due to it’s simplicity.
  5. Apperently (Untested by me) data is formatted as JSON then Ajax can travel across domains.
  6. Almost every language used in web development either already has a JSON library or set of functions. If one doesn’t, then creating functions is a trivial task.
  7. ‘var jsonObject = { ‘cody : ‘taylor’ };’ is referenced by ‘jsonObject.cody’ which gives us ‘taylor’.
  8. ‘var jsonObect = {‘javascript’ : {‘json’ : ‘not xml’ };’ is referenced by ‘jsonObject.javascript.json’ which gives us ‘not xml’.
  9. You can also reference the JSON object as if it was an associative array like ‘jsonObject[‘cody’]’ or ‘jsonObject.javascript[‘json’]’ which gives the same values as previously.
  10. If you don’t want to use key/value pairs you can define a normal data array. ‘jsonObject = {‘arrayOfData’: {‘numbers’ : [‘1’, ‘2’, ‘3’]}};’ We use indexes for this dataset. Don’t use indexes for the collections defined in the ‘{ }’. ‘jsonObject.arrayOfData.numbers[1]’ will give us ‘2’.
  11. You can put functions in the dataset to pass around executable code.

So now you know basically all there is to know about JSON.

Share

Jun 2 2009

Execute Javascript in URL Bar of Browser

So it seems that most of the popular web browsers will allow you to write javascript where you normally put the url address. I thought this was kinda neat.

If you put something like ‘javascript:alert(“it works”);’ into the url field of your browser you should get a popup that says ‘it works’. This can be used to change any attribute on whatever page you are currently looking at. All you need to do is browse to the desired page and put something like the following into the url bar in your browser.

javascript:document.getElementById(“title”).innerHTML=”Fake Title”;

Of course this will only work on pages that contain a div or p element with the id of title (which most sites have).
I did have some issues with this depending on the browser used. Some browsers, like firefox 3.0.10 on Ubuntu Linux would just show me a blank page with Fake Title on it. This was solved by putting the javascript statements in an anonymous function in the url line.

This is all good and fun for small little tweaks but what if you wanted to do something a little more… crafty.
It is possible to include an external javascript file and alter the page so that you can execute your own little script from a specific domain. Have you ever been playing around with some ajax and gotten an ‘Access to restricted URI denied (NS_ERROR_DOM_BAD_URI)’ error message? Well the method outlined below would allow you to put some proper ajax code into the site that isn’t allowing your requests.

While I’m not going to explain explicitly how to do anything fun I will show you how to include an external javascript file into a page in your browser that will allow you to call functions from that file on the page. Even though this will include the script you will still have to call a function from the script in the url bar. The code in the script will not execute by itself just because you included it.

javascript:{{ var e=document.createElement(“script”); alert(“here”);e.src = “http://quick-content.com/include_me.js”;e.type=”text/javascript”; document.getElementsByTagName(“head”)[0].appendChild(e);} test();}

The snippet above should all be one line. So if you paste that long one liner into the url bar of your preferred browser the javascript file from the url specified (http://quick-content.com/include_me.js) will be included into the html. At the very end of that statement I call the test() function that just changes the title of my blog to ‘Tech Stuff From Null’ as opposed to ‘Tech Stuff From Cody Taylor’. Try it out. Paste that code into your browser as you’re looking at my blog and check the title. This will work for any js file so have fun and don’t break anything.

Share

May 31 2009

Javascript DOM List Swap Nodes Example

I couldn’t find an easy to follow example to do this anywhere on the web so I did my own up. Basically I wanted a list where each item has an up and a down button that will dynamically reorder the list. I tried swapping the nodes themselves but it didn’t work so it seems that I have to use the removeChild and insertBefore methods to actually see the results on the page.
Here is the Javascript DOM Example


<ul id='list' name='list'>
</ul>

<script type='text/javascript'>

//swap the current li node with the one above it
function up(button_node)
{
  var current_node = button_node.parentNode;
  var list_children = document.getElementById('list').childNodes;
  var list_node = document.getElementById('list');
  
  var temp_node;
  var previous_node;
  
  for(var i=0;i<list_children.length;i++)
  {
    if(current_node.id == list_children[i].id && previous_node)
    {
      temp_node = list_children[i].cloneNode(true);
      list_node.removeChild(list_children[i]);
      list_node.insertBefore(temp_node,previous_node);
    }
    if(list_children[i].tagName=='LI')
      previous_node=list_children[i];
  }
}

//swap the chosen li node with the one below it
function down(button_node)
{
  var current_node = button_node.parentNode;
  var list_children = document.getElementById('list').childNodes;
  var list_node = document.getElementById('list');
  
  var temp_node;
  var previous_node = "";
  
  for(var i=0;i<list_children.length;i++)
  {
    if(current_node.id == list_children[i].id)
    {
      previous_node=list_children[i];  
    }
    else if(previous_node && list_children[i].tagName=='LI')
    {
      temp_node = list_children[i].cloneNode(true);
      list_node.removeChild(list_children[i]);
      list_node.insertBefore(temp_node,previous_node);
      previous_node = "";
    }
  }
}

//create the li elements
function create_list()
{
  for(var i=0;i<6;i++)
  {
    add_li('list', "Item "+i," Item "+(i+1)+" \
    <input type='button' id='up_button1' value='Up' onclick='up(this);'>\
    <input type='button' id='down_button1' value='Down' onclick='down(this);'>");
  }  
}

//add a li element
function add_li(list, id, text) {
  var list = document.getElementById(list);
  var li = document.createElement("li");
  li.innerHTML = text;
  li.id=id;
  list.appendChild(li);
}

create_list();
</script>

So it is a little longer than I expected but it works and it’s pretty easy to understand.

Share

May 24 2009

Recursive, Anonymous, and Simple functions in Javascript

Functions are objects. This makes recursion short and sweet in javascript using anonymous functions.
In your html, php, or asp file try this out.

<input type=’button’ id=’myButton’ value=”5″>

<script type=’text/javascript’>
var myButton = document.getElementById(“myButton”);
var i=myButton.value;

myButton.onclick = function() {
if(i==0)
{
alert(“DONE”);
myButton.value = i;
return i;
}
alert(i);
return arguments.callee(–i);
};

</script>

I attached the anonymous function onto the onclick event for the button that was created right above the javascript. When that button is clicked the anonymous function will call itself and decrement ‘i’ until it is zero. When ‘i’ becomes zero the value of the button is set to 0 and the function returns. Nice and simple.

The only possible confusing thing here is the arguments.callee line. Remember I said that functions are objects? The arguments.callee actually calls itself. We need this because we don’t have a handle for the anonymous function. The arguments object is a local variable that all functions have. It can be used like an array to access the values passed to the function. It also holds ‘callee’, ‘caller’, and ‘length’. Since the callee is the function itself then caller is obviously the function that called it and length is the number of arguments passed to the function.

Share

May 24 2009

Anonymous Function Examples in Javascript

Learning javascript by copying and pasting useful snippets off the web, the only aspects of Javascript that I’ve ever looked closely at were to change css properties, validate forms, or get some values with ajax. Because of this, there is stillĀ  a large portion of the language that I’m still learning. I’ve never used anonymous functions in any language, but they’ve always looked like an interesting concept, so I decided to give it a shot. This is what I learned with a few short examples.

This little javascript feature can be hugely useful for passing functions as variables or declaring quick functions inline for the programmer who is to lazy to switch files or scroll to wherever that annoying javascript declaration is.

To pass a function as a variable either with a reference or inline:

<script type=’text/javascript’>

//garbage example data
var array = [ 3, 14, 15, 9, 26 ]
var array2 = [ 3, 14, 15, 9, 26 ]

//This function takes an array and a function as parameters.
//It then executes the passed function on every element of the array.
function execute_on_array( array_of_stuff, anonymous_function )
{
    for (var i=0; i<array_of_stuff.length; i++)
    {
        alert(“before ” + array_of_stuff[i]);
        array_of_stuff[i] = anonymous_function(array_of_stuff[i]);
        alert(“after” + array_of_stuff[i]);
    }
}

//Here’s the anonymous function that is now referred to as nullify_function
var nullify_function = function (x) { if(x) return 0; else return x; }

//Passing an anonymous function in as a variable
execute_on_array( array_of_numbers, nullify_function);

//Here is the call to the previous function with an anonymous function defined inline
function execute_on_array( array2, function (x) { x=0; return x; } );

</script>

I could see how this would make recursion in javascript really easy.

Share

May 15 2009

Dojo Examples and Demos

The best resource for browsing all the features of dojo javascript is here. It not only displays all the features of dojo javascript but it also allows you to get any code for any feature you want. Check out here what you can do with it.

Share