Gameon's Favourite Blogs >>
Anoop : : GameOn BuZZ ||                     || Hari S R : : Tranquility ||                    || ~==[[[ Abhi ]]]==~ : : Cogito Ergo Sum ||                    || Abhilash Sir : : A Leaf out of Life ||

Programming Simplified

A Freelancers Tips and Tricks On Programming With Php , Ajax , CGI -PEARL ,Javascripting , CSS and GM(grease-monkey)..




Introdction To Ajax

Here I'll try to explain " What Is AJAX" in simple terms , so that budding programmers get a fairly good Basic Knowledge to follow thru and understand AJAX easily.

What Is AJAX

AJAX, is a web development technique used for creating interactive web applications.The name is an acronym standing for Asynchronous JavaScript and XML (Asynchronous JavaScript + XML = AJAX).
AJAX allows you to make a call to an http server (typically an RSS feed or a webpage), get its content and load them into your existing page without having to refresh the whole page. This means that services like email don't have to reload the whole page every time you click a message, saving on bandwidth (loading the header/footer all over again) and making things more efficient.
The Main advantages of using AJAX are that, It provides a mechanism to mix and match xml with xhtml,It significantly reduces having to continually fetch things from a server ),It overcomes some speed bottlenecks that traditional Web development has fallen prey too. In most instances ( I hate to say always ) an Ajax based site will load quicker than a comparable traditional Web site.When done well, it significantly reduces initial load times.
The HAndiness of Ajax is dat it doesnt require a complicated and continuous interaction with the webserver.This is Obtained By putting a JavaScript (and usually tucked away in a hidden frame) between the user and the server .{ advanced program geeks call it an Ajax engine,but for time being we call it jus javascripting becose the engine is nothing but a collection of javascript code}
These javascripts are responsible for both rendering the interface the user sees and communicating with the server on the user’s behalf.
the advantage here is that the user does not wait for any response from the sever after asigning any tasks.
The core of Ajax is the xmlhttprequest object and its Microsoft's activeX equivalent. It is this object that allows data to be transferred asynchronously (ie it can handle processes independently from other processes).

To give you A brief example of Ajax,see this simple code. This code goes between the [head] [/head] tags. {replace [ and ] with < and > respectively }


[code start]

function loadurl(dest) {



try {

xmlhttp = window.XMLHttpRequest?new XMLHttpRequest(): new ActiveXObject("Microsoft.XMLHTTP");

} catch (e) {



}


xmlhttp.onreadystatechange = triggered;

xmlhttp.open("GET", dest);

xmlhttp.send(null);

}
function triggered() {

if ((xmlhttp.readyState == 4) && (xmlhttp.status == 200)) {

document.getElementById("output").innerHTML = xmlhttp.responseText;

}

}

[code end]

Now to Call it on An Html Page use this >>

[body] [div id="output" onclick="loadurl('/testdir/helloworld.txt')"]click here to See " Hello World " in this div[/div] [/body]

Note : In this Html code , Replace " [ " and " ] " with ' < ' and ' > ' respectively.

here "helloworld.txt" is a Text file on the directory "testdir".
Now remmember to put the destination url (here >> /testdir/helloworld.txt) in the same domain, otherwise errors may come.

What The Above code does is that while clicking the link on the div, The contents of the text file "helloworld.txt" will be displayed on the same web page without refreshing.

Introduction to Java-Scripting

What is JavaScript?

Javascript is an easy-to-use programming language that can be embedded in the header of your web pages. It can enhance the dynamics and interactive features of your page by allowing you to perform calculations, check forms, write interactive games, add special effects, customize graphics selections, create security passwords and more.

What's the difference between JavaScript and Java?

Actually, the 2 languages have almost nothing in common except for the name. Although Java is technically an interpreted programming language, it is coded in a similar fashion to C++, with separate header and class files, compiled together prior to execution. It is powerful enough to write major applications and insert them in a web page as a special object called an "applet." Java has been generating a lot of excitment because of its unique ability to run the same program on IBM, Mac, and Unix computers. Java is not considered an easy-to-use language for non-programmers.

Javascript is much simpler to use than Java. With Javascript, if I want check a form for errors, I just type an if-then statement at the top of my page. No compiling, no applets, just a simple sequence.

What is Object Oriented Programming?

Everyone that wants to program JavaScript should at least try reading the following section. If you have trouble understanding it, don't worry. The best way to learn JavaScript is from the examples presented in this tutorial. After you have been through the lessons, come back to this page and read it again.

OOP is a programming technique (note: not a language structure - you don't even need an object-oriented language to program in an object-oriented fashion) designed to simplify complicated programming concepts. In essence, object-oriented programming revolves around the idea of user- and system-defined chunks of data, and controlled means of accessing and modifying those chunks.

Object-oriented programming consists of Objects, Methods and Properties. An object is basically a black box which stores some information. It may have a way for you to read that information and a way for you to write to, or change, that information. It may also have other less obvious ways of interacting with the information.

Some of the information in the object may actually be directly accessible; other information may require you to use a method to access it - perhaps because the way the information is stored internally is of no use to you, or because only certain things can be written into that information space and the object needs to check that you're not going outside those limits.

The directly accessible bits of information in the object are its properties. The difference between data accessed via properties and data accessed via methods is that with properties, you see exactly what you're doing to the object; with methods, unless you created the object yourself, you just see the effects of what you're doing.

Other Javascript pages you read will probably refer frequently to objects, events, methods, and properties. This tutorial will teach by example, without focusing too heavily on OOP vocabulary. However, you will need a basic understanding of these terms to use other JavaScript references.

Source code encryption

Firstly go to http://www.iwebtool.com/html_encrypter

Next put your HTML in the top textarea and click encrypt
(This can take time depending on amount of HTML)

after its encrypted put it in your old HTML e.g index.html

IMPORTANT: ALWAYS MAKE A BACK UP COPY

http://www.iwebtool.com contains other things E.G meta tag maker
but you can only use them 5 times per hour apart form Source code encryption and another tip is to put it all the way down make it look like
that its not there put comments at the top saying something like this:

SOURCE CODE PROTECTED

NOTE: The only real reason you would use this is to protect your images

the source code encrypter uses Javascript to make it unreadable to humans

Visitor Tracker

This is a Simple script to log visitors of your site.

[code start]
//User Tracker
//Check refered page
if (!$_SERVER['HTTP_REFERER']) {
$ref = 'None';
} else {
$ref = $_SERVER['HTTP_REFERER'];
}

$date = date('d/m/Y H:i:s');
$ip = $_SERVER['REMOTE_ADDR'];
$data = 'IP Address: '. $ip. ' - ';
$data .= 'Date: '. $date. ' - ';
$data .= 'Referer: '. $ref. "\n";

// Write information to a log file, Append mode.
// Pointer placed below the record.
file_put_contents('./track.log', $data, FILE_APPEND)
or die ('Oopsy error on writing... You may go this time... Sorry :)');
?>

[code end]

how to use>>

Just copy it to your homepage then overwrite your homepage in your server.
This code records visit time, and Referrers to a text file.

Php Basics

You don't know PHP you say? Neither do I but i know a bit. Want to make your website easy to update and update something on every page without having to change every page? Well here's how!

1)first off i suggest you make a directory called modules ( you can name it whatever you want but i did this )
2)Choose what thing(s) you want to make editable. Like your title, footer, news, menu's, etc.
3) Now open up Notepad( or whatever you would like ) and cut what you want to make editable on your site from your site and paste it to the NotePad.
4)Now put in place of what you cut out (Now lets just call it menu.php because just say we are making a editable menu) and of course save that notepad as menu.php
5) upload the new menu.php file to the modules directory. and upload the index and you must save it as a *.php file or the 6) Well enjoy the new editable section of your Website! Now all you have to do is edit the menu.php file and it will do it on every page that has on it!

Although if you do no PHP im sure you know this but i just thought i would share it with those who don't know ^_^

[MYSQL]functions/queries list

Here is a lot of the fuctions, queries list.

FUNCTIONS
mysql_query([query]) - execute query [query] with the database
mysql_connect([host],[user],[pass]) - tries to connect you to [host] at username [user] and password [pass]
mysql_select_db([db]) - selects the database [db] and tries to connect with
mysql_num_rows(mysql_query([query)) - counts the amount of results queries in the query [query]
mysql_fetch_assoc([query]) - set all results from the query [query] into a array $var[field]
mysql_fetch_rows([query[) - works same as mysql_fetch_assoc but this one is some slower, more change on fail

QUERIES
SELECT [field] FROM [tabel] WHERE [field] [object] [value] LIMIT [limit] ORDER BY [field] [ordertype] GROUP BY [field] - selects [field] from the table [tabel] and where the field [field] is [object](== / != / ...) to [value], order the found results by the field [field] and order it [ordertype](DESC/ASC) and set it into a group by field [field]
INSERT INTO
([fields])VALUES([values) WHERE [field] [object] [value] - insert the values [values] into the fields [fields] (1st one in the 1st field, 2nd one in the 2nd filled in field, etc.) in the table
, and where [field] is [object] (== / != / ...) [value]
UPDATE
SET [field] [object] [value] WHERE [field] [object] [value] - updates the table
by setting the field [field] [object](== or !== or ...) to [value]
DELETE FROM
WHERE [field] [object] [value] - deletes a row from
where [field] is [object](== or != or ...) [value]

Speed up your scripts by caching mysql data

As you know, the MySQL Server experiencs lots of strain. And When you have a large database, some queries end up taking too long and visitors get the Proxy Error message. Here is a method to modify your site to cache all dynamic data for 1 minute so as to reduce load. By this method your homepage grabs canned data from the server, so that visitors will see something at least. It then waits a while and tries to get an updated copy through AJAX.

(Note that it's a bad idea to cache stuff if your script runs on interaction based on realtime data. Don't do this to your forum, for example. A CMS might be able to benefit somewhat from this. If your site uses ADOdb, it's very simple to tell ADOdb to cache your queries.)

Depending on the nature of your site, you may be able to do the same. Here are some basic PHP functions to help you get started:

// $filename: name of cache file
// $cachetile: how long the cache lasts in seconds
// $data: string data to be cached

function cachefresh($filename,$cachetime) {
if(!file_exists($filename)) $mtime = 0;
else $mtime = filemtime($filename);
$mtime += $cachetime;
if($mtime > time()) return(true);
return(false);
}

function cachedata($filename,$data) {
$fp = fopen($filename,"w+");
fwrite($fp,$data);
fclose($fp);
}

function cachedatacheck($filename,$cachetime,$data) {
if(!cachefresh($filename,$cachetime)) cachedata($filename,$data);
}

cachefresh() returns true if the cached data is still within the time limit. cachedata() puts string data into a file, overwriting original contents. cachedatacheck() puts string data into a file if the cache has expired, overwriting original contents.

One way to use this is:
1) check if cache is fresh. if so, just output the data using readfile() or similar.
2) if not, generate and cache new data before sending it to the browser.

Compress your Javascript

Some ajax sites have to load lot's of javascript, and it might be spoiling your visitor's viewing experience (especially if they use dial-up).

You can compress you javascript easily, and it can be from just removing whitespace, removing empty lines, removing comments, to renaming variables, rewriting your code, and obfuscation.

So how to get started.

Many javascript compressors use regex based systems, or sometimes they strip all newline characters-which could be a problem if you do not use semicolons on every line.
For the best result, I start out with dojo shrinksafe () which compresses your variables (eg. var somerandomlongvariablename; to var _33; and automatically adds semicolons. for compression, it also removes comments etc.

Then you should try using something like or (enable base64 encode, and if you want- you can try shrink variables)

Create your own ajax based slideshow using minishowcase.

Step 1. Go to http://minishowcase.frwrd.net/?download and download the latest version.

Step 2. Edit the config/settings.php file as you see necessary. Use something like wordpad (windows) or textedit (mac) to make any changes. Each of the settings you can change are well commented, so they tell you what they do when you change them. If you have any questions let me know and I will try to help you.

Step 3. One setting I recommend you change is you change $settings['create_thumbnails'] and $settings['cache_thumbnails'] to yes, this will make it so that it creates thumbnails, and that is caches them for faster load times when your website viewers are looking at your galleries.

Step 4. It is now time to create your first gallery! Create a new folder inside the galleries folder. Name it whatever you wish that gallery to be listed as on your website. If you want it to be named Christmas photos 2006 you would name the folder Christmas_photos_2006 notice I used _ for spaces. This is important!

Step 5. Place the photos you want for that gallery inside of your newly made, newly renamed folder.

Step 6. Repeat for each new gallery you wish to create.

Step 7. Upload these to your website!

Basic Ajax Application

This is a simple tutorial that will teach you the basics of AJAX. This is the first application I wrote using the AJAX framework and hopefully will lead to a lot more.

If you want to skip the tutorial and get to the code then click here. You will also find a Demo and Source Code at the bottom of this page.

Lets begin!!

First we must make the html page. Copy the code below to a My_First_Application.html file.



[html]
[head]
[title]First AJAX Application[/title]
[/head]
[body]
[a href="javascript:firstAppl();">Make Text Appear[/a][br/]
[span id="result_here">[/span]
[/body]
[/html]

(plz replace [ and ] from the above code with < and > respectively)



The above code is very simple. If you are trying this tutorial you should understand everything in the html code, but I will explain it. There is a link which when clicked it calls the firstAppl() function. Also there is the span tag which will display the result after all the code is written.

Next you will add javascript code to your .html page. The XmlHttpRequest object a big part of the AJAX framework. Internet Explorer does not support the XmlHttpRequest object and instead uses the ActiveXObject. We must check to see what browser is in use so the code works properly. You will want to paste the following code in the header of My_First_Application.html.



The good part about this code is that you can copy and paste this into any AJAX application.

Next you will want to copy the code below. You will want to paste it right below the getXmlHttpRequestObject() function but before the tag.

var getRequest = getXmlHttpRequestObject();

This code will get a new XmlHttpRequest object and save it to the getRequest variable.

Next we will create the firstAppl() function. This is the function that is called from the html page. Copy can paste the code below right after the code we just created.

function firstAppl() {
//Checks to see if you XmlHttpRequest object is ready.
if (getRequest.readyState == 4 || getRequest.readyState == 0) {
//Makes a call to Display_Text.html with the GET
getRequest.open("GET", 'Get_Text.html', true);
//Call a function that will display the text in the span area on First_Ajax_Application.html
getRequest.onreadystatechange = displayText();
//Makes the request.
getRequest.send(null);
}
}

In this function, you do a couple of things. First, you check to see if the XmlHttpRequest object is ready. If the request is ready, you call the Get_Text.html. After this, you will call the displayText function to display the text on the First_Ajax_Application.html page.

Next we will create the displayText function to display the text after the link is clicked. Copy and paste the text below the firstAppl() function we just created.

function displayText() {
//Check to see if the XmlHttpRequests state is finished.
if (getRequest.readyState == 4) {
//Set the contents of our span element to the result of the asyncronous call.
document.getElementById('result_here').innerHTML = getRequest.responseText;
}
}

In this function, we check to see if the XmlHttpRequest is finished. If if it we print out the text from Get_Text.html on the First_Ajax_Application.html.

Next we will make the Get_Text.html

The page is simple. You just type some text in a document called Get_Text.html. The text I chose was Done with your first AJAX Application.

Next upload these two files to a your web server. You should be able to call the First_Ajax_application.html file and try out your application.

That is all you need for this application! Hope this help you get a start on AJAX.



         

           My Photo

           Gameon


Web This Blog


AddThis Social Bookmark Button

Page copy protected against web site content infringement by Copyscape


XML


Powered by Blogger






© 2007 Programming Simplified | ..:nEo:..
No part of the content or the blog may be reproduced without prior written permission.