Mcloide's resources library

All about PHP, Javascript, concepts and development

Posts Tagged ‘Javascript’

New resources

Posted by mcloide on August 21, 2009

Happy Friday everybody ….

2 New resources for you to check out:

  1. Javascript Bookmarklets
  2. Zend Framework and Firebug – Log PHP warning, errors and exceptions

Don’t forget also of the PHPArch Free Webcast today about Running PHP on Windows with Hank Jansen and Zack Owens.

Have fun .. .

Posted in Javascript, PHP, Zend, development, resources | Tagged: , , , , , , , | Leave a Comment »

Client Side x Server Side Scripting

Posted by mcloide on August 7, 2009

When considering developing applications for the web two concepts, Client Side and Server Side Scripting,  will emerge and some times, for many beginners mixing this concept gets pretty messy.

Client Side Scripting

Client side scripting is when the application created is translated on the user web browser. The best programmable language that anyone can use to exemplify it is still Javascript.

Whenever working with Javascript all programmed methods, functions, actions and interactions are downloaded to the user web browser and then translated and executed.

Creating a little schematics to understand the process, the sequence would be:

  1. user browser requests a page / application part (index.html)
  2. the page / application part is fully downloaded to the browser
  3. the browser (in this case with Javascript enabled) translate the javascript code and output (print) the result

To better demonstrate this let’s do a small example:

<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01//EN” “http://www.w3.org/TR/html4/strict.dtd”>
<html>
<head>
<script type=”text/javascript”>
// don’t mind the code, is just for example
document.write(“<p>Browser: “);
document.write(navigator.appName + “</p>”);

document.write(“<p>Browserversion: “);
document.write(navigator.appVersion + “</p>”);

document.write(“<p>Code: “);
document.write(navigator.appCodeName + “</p>”);

document.write(“<p>Platform: “);
document.write(navigator.platform + “</p>”);

document.write(“<p>Cookies enabled: “);
document.write(navigator.cookieEnabled + “</p>”);

document.write(“<p>Browser’s user agent header: “);
document.write(navigator.userAgent + “</p>”);
</script>
</head>
<body>
<h1> Your browser information </h1>
</body>
</html>

In this small example, taken from W3C Schools, the javascript code will be downloaded to the user browser and executed displaying the result immediately to the user.

Server Side Scripting

Server Side Scripting is when the translation and execution of the code is done on the server side and only after that being downloaded to the user browser. There are many languages that are fit for the Server Side Scripting. Some great examples are PHP (off course), C# and ROR.

Whenever working with PHP, for example, all PHP code will be translated and executed on the server and substituted for the result that will be downloaded, all together with the page, to the user browser.

Let’s try to do a small schematics here to follow the process for that:

  1. User browser request a page / part of the application (index.php)
  2. The server understands that the page requested has PHP coding and send a request to the PHP engine to translate and execute the code returning the results
  3. After all is processed, the request is complete and the result page is returned to the user browser

To better exemplify this, I will place some body and code for the index.php application.

<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01//EN” “http://www.w3.org/TR/html4/strict.dtd”>
<html>
<head>
<title> A Server Side Application </title>
</head>
<body>
<ul>
<?php
// don’t worry about the code for now, just example
$menu = array(‘item1′, ‘item2′, ‘item3′);
foreach($menu as $index => $item)
{ ?>
<li><?php echo $item; ?></li><?php
}
?>
</ul>
</body>
</html>

The PHP engine will translate the PHP coding to output (print) item1, item2, item3 inside a list item for each one of them. The result from this small code will be:

  • item1
  • item2
  • item3

In the real world development, programmers uses both sides of scripting to create complex and interactive applications / pages to the users. Most of the time the client side scripting will take care of the interactions, usability, action requests, etc, and the server side will handle the security of data, output of massive data, body construction, logistics, etc.

To wrap up, take a look at the Google Maps application. While Javascript handles the marker positioning, displaying images, constructing the map, a server side language (PHP I believe) will retrieve the user position by it’s ip positioning the marker, calculate routes, gather the images from the map (in Google Maps specifically is done through an API).

Now let’s start learning some PHP scripting [next].

Posted in PHP, development, resources | Tagged: , , , , , | 1 Comment »

Tracking mobile with Google Analytics

Posted by mcloide on April 22, 2009

I’m working with mobile for a while now and today the question poped: how to track mobile with Google Analytics.

At first it did not make much sense, but most of the mobile devices does not support Javascript or Cookies.

After some googling on the net I came accross this post – http://www.vdgraaf.info/google-analytics-without-javascript.html – that shows a way to call the tracking from Google without Javascript.

I have just did a small test run in my website: http://www.mcloide.com and tomorrow I will post the results for you guys here.

Anyway is a great post and if you are having the same difficulties, this might help you out.

Have fun.


Update:

I have just checked the analytics for my site and it did correctly got the Blackberry, Nokia N90 and the Sony Ericsson. I have only one entry for Safari, so I guess that was for the Iphone string (it shows Iphone on the operating systems part).

All the entries shows the fake url (that’s how it was instructed at the blog) and the IP of origin. It also shows 100% of bounce rate.

It definitively works. I will keep it on my site for a long time track and see how things are going and anything new I will post a new update.

Posted in PHP, development, google, resources | Tagged: , , , , | Leave a Comment »

Javascript LIbrary Detector

Posted by mcloide on April 13, 2009

I was scooping out a blog from a friend of mine today, Smooka Blog, and I found this interesting post from a Firefox plugin for detecting Javascript libraries. It’s useful in many ways since you can learn if your project have correctly loaded the library or what library does the site that you are visiting have.

Anyway, cool post, check it out: http://www.smooka.com/blog/2009/03/26/javascript-library-detector/#more-52

Posted in Javascript, development, resources | Tagged: , , , , | Leave a Comment »

Creating your own Javascript AJAX Request

Posted by mcloide on January 9, 2009

Using Javascript to post variables to another script and process them is not something new. Posting by AJAX with nowadays libraries is also not new, but what about you creating your own javascript AJAX handler.

The first thing you need to know is about using the Javascript XMLHttpRequest.  It’s very simple object that will allow you to submit via get to anohter script and retrieve the response for it. For more information about this object you can always check W3Schools.

Creating your own script will need 4 required parameters:

  • form name
  • action of the form (script where you will be posting to)
  • parameters or variables to be sent
  • callback function to process the result

With this in hand you can create your function and submit the variables to your script using your own AJAX function.

You will need, for that, a script similar to this one:

var http_request = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,…
http_request = new XMLHttpRequest(); // creating the object
if (http_request.overrideMimeType) {
// set type accordingly to anticipated content type
//http_request.overrideMimeType(‘text/xml’);
http_request.overrideMimeType(‘text/html’);
}
}
else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject(“Msxml2.XMLHTTP”); // creating the object for IE
}
catch (e) {
try {
http_request = new ActiveXObject(“Microsoft.XMLHTTP”); // since it can work differently through versions, using the try catch event for Javascript will force IE to always create the object.
}
catch (e) {}
}
}
// got this test from other site, but don’t remember where….
if(!http_request){
// something did not work right
alert(‘Unable to create an HTTP request instance.’);
return false;
}

// if callback is not a function it will create one so the onreadystatechange from the get the parameters
callback = callback || function(){};

// creating the AJAX call
http_request.onreadystatechange = function completeAjaxRequest() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
// everything worked as it should
result = http_request.responseText;
// process the result by a callback function
callback(result);
return true;
}
else {
alert(‘There was a problem with the request.’);
return false;
}
}
};
// sending the parameters through the created object to the script
http_request.open(‘POST’, action, true);
http_request.setRequestHeader(“Content-type”, “application/x-www-form-urlencoded”);
http_request.setRequestHeader(“Content-length”, parameters.length);
http_request.setRequestHeader(“Connection”, “close”);
http_request.send(parameters);
return true;

Off course you need way more validation and testing to see if everything is working as it should, but this will kick start it.

Tip:

Create a function that will alert an error or write in console if you are using Firefox with Firebug. This will help to handle and troubleshoot your functions.

All you need is a simple test:

var type = typeof(console);
if(type == ‘undefined’) {
alert(message);
}
else {
console.log(message); // firefox with firebug only
}

Have fun.

Posted in Ajax, Javascript, development | Tagged: , , , | Leave a Comment »

SWFObject

Posted by mcloide on January 3, 2009

First post of the year and let’s start with something really cool.

Using PHP with Javascript and FLV players is not a big news on the market, but Google Code Project, SWFObject make it a new standart.

I bet that any deleveloper have done some ugly Javascript coding to print out the embed object on the page document. It have been so far the most easy and cross-browser reliable way to dinamically create flash embed objects on the page document. Google Code Project, SWFObject, creates a new way to construct this embed objects and an even better way to control the parameters, flash variables, attributes, etc.

The triad of PHP, Javascript and FLV players would come in way that PHP would stream the video content, guaranting more security, Javascript would grab the information, create the embed object and sent it to the FLV player to play the stream. You got love that. It’s a great and realiable way to stream flash content on your users browsers.

How would be the coding for the SWFObject? Simple:

<script type=”text/javascript” src=”swfobject.js”></script>
<script type=”text/javascript”>
var flashvars = {};
flashvars.src = “myPHPSCRipt.php”;
var params = {};
params.play = “true”;
params.loop = “false”;
params.menu = “false”;
params.quality = “autohigh”;
params.wmode = “transparent”;
params.devicefont = “false”;
params.swliveconnect = “false”;
params.allowfullscreen = “true”;
params.allowscriptaccess = “sameDomain”;
params.allownetworking = “none”;
var attributes = {};
attributes.id = “theFlashPlayerID”;
attributes.name = “theFlashPlayerID”;
attributes.align = “left”;
swfobject.embedSWF(“player.swf”, “theDivID”, “320″, “240″, “9.0.0″, “expressInstall.swf”, flashvars, params, attributes);
</script>

Simple and clean coding.

Add you flash player on the same location as the SWFOjbect (or correctly reference it) and add a div with the id = “theDivID” (or whatever ID you want for it) and you will have everything working (the SWFObject will replace the div with the embed code).

For more information about it and for much more resources here are some great places to start at:

Posted in Javascript, PHP, cool, development, resources | Tagged: , , , , | 2 Comments »

Javascript Smart element setter

Posted by mcloide on December 14, 2008

This is a small function to help anyone that uses a lot of  the infamous “document.getElementById(‘id’)” in Javascript coding and with some small modification you can make this function even better.

The function will get an id as parameter and return the document element refering that id. Is simple as that and it can make your code more readable and easier to work. The only detail is, do not use it if you is already using JQuery or any other Javascript framework that have a similar method.

<script type=”text/javascript”>

function $(id){
var element;
if(null != document.getElementById(id)){
element = document.getElementById(id);
return element;
}
return false;
}

</script>

A small use for this function would be something like this:

<input type=”text” id=”text1″ name=”text1″ value=”" />
<input type=”file” id=”file1″ name=”file1″ value=”" onchange=”$(‘text1′).value = $(‘file1′).value;” />

Have fun.

Posted in Ajax, Javascript, development | Tagged: , , , | Leave a Comment »

JQuery

Posted by mcloide on November 18, 2008

I have been working with JQuery for a while and it is by far one of the easiest and strongest Javascript Frameworks that I have worked with.

The process is simple:

  • include the JQuery js files (all that you might need)
  • Work with Javascript as it was never so easy

Let’s take an example (a very simple one, but pratical – almost everyone that I know have to work with AJAX).

Consider that we need a function to request (AJAX) an information from a helper file (a PHP script that will perform whatever you need it to do) and print it’s results on a div box.

The function would be something like this:

<script>

function getHelloWorld(input1,input2){

/* Changing the current content with something new */
$(“#theDiv”).html(“Wait while loading the requested information”);
/* How about changing the css a bit */
$(“#theDiv”).css(“height”,”300px”);

/* Performing the AJAX request that will get the helper result and place it inside the “theDiv”  innerHTML */
$.post(“helpers/loadNewInfo.php”,{action:’new’,input1:input1,input2:input2},function(result){$(“#theDiv”).html(result); alert(‘cool it worked’); $(“#theDiv”).css(“height”,”500px”); } );

}

</script>

Now let me give a little bit of a “zoom” at the AJAX request.

$.post(
“helpers/loadNewInfo.php”,
{action:’new’,input1:input1,input2:input2}, /* the post variables and it’s values that will be sent to the loadNewInfo.php file */
function(result){
$(“#theDiv”).html(result); /* callback function body */
alert(‘cool it worked’);
$(“#theDiv”).css(“height”,”500px”); /* playing a bit with the css, maybe we could place it yellow background */
}
); /* Here the $.post is ending */

As you can see working with JQuery is very simple. You will access the elements by $(“#elementID”) (or name I really don’t remember right now) and every property from it as an object modifier preceeded by a dot.

With inputs you can work the attributes from it using the attr clause.

Anyway, I’m far from being an expert from this, but It’s a simple example for those who are starting with JQuery. Right now I’m using JQuery to work with a Shopping Cart. It’s a nice way to paginate and display products without having the user post back every time and the best of all I can control CSS elements with it.

For more reference, go to: JQuery Code

P.S. If you are used to perform hard core Javascript DOM manipulation, JQuery will be a piece of cake for you.

Posted in Ajax, Javascript, PHP, development, resources | Tagged: , , , , | 2 Comments »

JS Coding and Compressing

Posted by mcloide on October 16, 2008

Creating a JS code seems very easy, even more when you program javascript for a while, but not everything works in the way that it should when you are trying to compress a script.

Today I had the simple task of converting a insane huge javascript into a compacted JS file and I got to admit that the fight against the compressor was much harder than I tough.

Anyway to make everyone life easier, here are 2 links that will help you convert you Javascript code into a compressed JS file.

Have fun and don’t be upset for what JsLint will say about your code. It’s just a harmless cold machine that is returning what is wrong.

Posted in Javascript, development, resources | Tagged: , , , | Leave a Comment »

Google Maps in a tabbed profile

Posted by mcloide on August 22, 2008

Consider that you have a profile page, tabbed, and in one of the tabs you have a Google Map with the pinpoint of the user. When the page loads, it will load the map aplication, but the map div will not be visible at that point.

When you hit the map tab, you will see the map loaded, but, with some areas missing or acting really weird.

What is happening is when the tab loads, the map is not fully loaded and the main document finishs to load before the map loads, so, it understands that the map area is smaller than really is and shows it like that, funny.

How to fix it? Simplier than you think. If you search around you are going to find some stuff like map force redraw, but there’s a simplier way to do it.

Add a setTimeout to load the map.

Here’s the whole process. Remove the onLoad=”loadThis()” from the body and inside the map tab, just after the map div, put the a javascript like this: setTimeout(‘loadThis()’,1000);

That’s all you need and your map will have more than enought time to load all info and display correctly.

Have fun.

Posted in Ajax, Google Maps, Javascript, development | Tagged: , , , , , , , | 7 Comments »