Author

Linjo Joson

Browsing

 What is Regular Expression?

Regular expression(regex) is a specific pattern used to match some texts, its a unique pattern. And by using this pattern we can match texts,strings, numbers,alphabets,symbols or whatever.

 How is it useful?

Regular expression makes your life easy. It extends the normal search procedure to large range of possibilities. Its very much useful in programming, content scraping,linguistics etc. For sure the Google should be using lots of regular expressions to track the content of a website.

   Interesting real life scenarios – Learn Regular Expressions

5 Ineveitable Regexes and its explanations

I’ve given 5 regular expressions and its explanations which we may need to use most of the time in our real life. All these regexes are splitted into sections and have given explanations to the sections.

Regex 1 – To find a particular word and its number of occurrences in a content/page.

 You can block illegal sites, user comments, or spam users by using regular expression. For example check the below link , which is  a live link in gskinner(a tool used to verify a regex). 

Demo:  Regex example selecting the word 

In this example, we are selecting the word “porn” from the whole text content. And after all what we can do is count the number of occurrence of the word and do a filtering based on that.

In this example the regex we’ve used is “porn” (ignore the quotes), which finds out the word porn and its other  occurrence .

Check out how this is useful for a webmaster.

  • Can filter out spam or adult comments, contact form submissions etc.
  • Crawling the sites content and can check how much importance they give to the specific word.
  • Blocking based on ip address ,regarding the searched keyword or other.
  • Suppose that  you need to match a sentence that says about a particular word. Say,          “Apple iphone“, where the mentioned word lies in between the sentence. Consider a  facebook status “I am loving Apple Iphone, its the best phone in the world” . You can match this whole sentence using regex. This would be really helpful in user/product reviews.

Regex 2  – Find all the out going links in a page and image urls

You can easily find out the outgoing links from a page ,so that you can do a filter based on those links. You can even build a Page Link Checker tool too.

Demo :  Find all the hyperlinks using regex

Regex   (?i)]+)>(.+?)

I’ll split this into 4 sections

 (?i)([^>]+)>(.+?)

Consider each color as each section. I’ve explained each sections below

What it does basically is select all the “a” tags case insensitive,                                                          Google will be an example.

  • (?i) – Means its case insensitive -,it will match both upper and lowe cases.
  • ([^>]+)> – You can see that this part ends with “>” which is end part of the a tag                          . So this matches everything until the  closing  “>”tag  . Everything given inside brackets () referes to groups so here we got one group  .  [^>]+ – Square bracket refers to a single character,  and the + followed by that means it will match (or repeat) that single character as much as possible and include in the match . *(star)   also got a similar meaning to +.  . So whats given inside the square  bracket?. ^>  – ^ means a negative match or it means match everything thats not the character followed. Here in our case it will match all the characters which is not a “>” . So in total < a([^>]+)>, means it will match everything starting with a tag and everything in between which is not a > , or in short                       – Match  – Google
  • (.+?) – That section matches everything thats after the closing > tag                                     – Match – Google

Likewise you can match all the img tags and find out the images inside the page.

Regex 3 – Find all the sentences not beginning with a capital letter.

Punctuation is a really important factor to maintain quality in what you write. Its really hard for you to  scan the whole text (say it got 3000 words)  and check for punctuation. By knowing regular expressions, you can solve this tedious task to an extent . For instance, If you need to match all the beginning word of a sentence that doesn’t begin with a capital letter, you can use regexes.

Regex:   \.(\s)*?[a-z]

Demo : Regex to check punctuation- To find the sentence not beginning with capital letter

This regex will find all the starting letter of a sentence which doesn’t begin with a capital letter.

\.(\s)*?[a-z]

  • \.  – Matches a . (dot), the backslash (\) is used to escape a dot, as dot got other meanings in a regex (Its a special character, very much like +,*,/ etc )   . “\.” means its the matching a dot  character.
  • (\s)*? –  This matches as much as spaces after a dot, most of the people puts one or two spaces after the end of a sentence  \s matches a space character the * (star) followed by that means, it will match as much as space characters possible. The question mark (?) followed by that means, the space character matching is optional (Many people don’t use space after the end of a sentence( to begin another sentence) ).
  • [a-z]– Everything given inside a square bracket [ ] represents a single character, and here it means it will match a lower case alphabet. If it was given [A-Z] , it would have matched an upper case alphabet.

Regex 4 – Find a word which you forgot.

Just imagine that you forgot a word, and you want find that particular word from the whole bunch of a bulky text. For instance, you are searching for the movie name
titanic“, and you only know that it begins with t and ends with c, you can find this word using a regex.

 Regex \bt[\w]*c\b 

DemoRegex to match an unknown word

Grouping  the  regex :  \bt[\w]*c\b

Meaning

  • The regex is wrapped in (\b \b) , which means that we are looking for word , placing \b-boundary will  help you to achieve this,it will eliminate all the other matches, for example, this  by putting the boundaries  ,our regex wont match the titanic in the word “titanicosis”  it matches a word, which starts with t  and ends with c.
  • t[\w]*c – means it will match every alphabets after t and before c. [\w] represent a single word character and [\w]*matches multiple occurrence of the the character until c is reached . That means apart from “titanic”, this will also match everything that starts with t and ends in c for example,”tic”,”tac”,  etc. You can make this regex more accurate by modifying the it a little bit.
    Improving this Regular Expression
  • You know that  the word titanic is 7 letters ,of which you know t and c , so whats in between should be 5 letters, we can add that logic too to the regex
  • t[\w]{5}c – {5} means that the single alphabet (\w) should be matched for 5 times until “c” is reached , so it will eliminate words like “tic”, “tac” etc. Check the below link

Demo: Regex to match the word with limited character numbers

Regex 5- Money formatting

Regex is very helpful in money formatting also. Consider that you got a bulk of text with money values entered as $3200, $3,200,$3200.00 $5000, $5,200 etc. What if you want
to remove all the comma separated values to normal values(without commas and the ending zeroes after decimal) for a standardisation?. I bet it would be a herculean task if you use normal search and replace. We can achieve this easily by using a regular expression

Regex\$[0-9],[0-9]{3}(\.[0-9]{2})?

Demo: Regular expression to match money values with formatting

Grouping it :  \$[0-9],[0-9]{3}(\.[0-9]{2})?

Meaning

  • \$[0-9]    –  This matches money values that start with a “$”(dollar) and a single number –          .$ got other meanings in regex, its used to find the end of a string. /a$/  find strings that ends with a. So we need to escape $ sign  with a backslash(\) indicating that we are looking for the $(dollar sign) .Its for this purpose we’ve used \$. – Match – $3,200
  • ,[0-9]{3} – This matches a “,” (comma) and 3 numeric digits  – Match  $3,200.00
  •  (\.[0-9]{2})? – This part of the regex handles the decimal part. The whole expression is placed inside “()”-  brackets  and followed by a question mark (?). Everything placed inside brackets “()” are groups in regular expressions. ? means that the preceding group is optional, or in our case it means , “Its not necessary to match the decimal part, but if there is one, match it”  .Which means it matches all the money values with and without decimal part. Now coming inside to the group \.[0-9]{2} –  The dot(.) has been escaped with a backslash (dot is very much like dollar which is a special character so we need to escape it ). Dot is followed by a two numeric digits which forms the decimal part –  Match – $3,200.00

How to use Regular expression to search and replace in Notepad++? 

notepad search

Notepad++ allows regular expression search, which helps us to search for a word with regex and replace it with some other. To use regular expressions in notepad.

  • Take the find option (CTRL+F).
  • Select the regular expression option.
  • Paste the regex and search.

Using Regular expressions with Javascript

We can use the match() function in javascript to match regular expressions.

example:

var str = "titanic is a ship";
var matches=str.match(/t[\w]{5}c/g);

Here the variable matches will hold the  match “titanic“.

/g : This means this will be searched globally, or all the matches corresponding to the search expression.  With out using /g, it will return a single match.

/i : In javascript, we can use /i along with the regex to make the match case insensitive.

General Regular Expression syntax in Javascript  :  /REGEX/

The two forward slashes /  /   are where we place the regex inside. g , at the end means its a global match, means it matches every occurrences of the particular word.

Using Regular expressions in PHP

We can use this regular expressions in php also. Php provides some great functions to match our regexes.

As like in javascripts, we enclose the regex in forward slashes in php.

General Regular Expression syntax in PHP:  /REGEX/

PHP functions which deals with Regexes

1. preg_match – This is a single match, this will return a single match found from the whole text. General syntax is

preg_match(regex,text,output)

Output:

Array
(
    [0] => titanic
)

2. preg_match_all – This holds the same concept of preg_match , but this matches globally, same as /g which we used in the javascript match.Means it will match every occurrences of the regex, we used. It is very useful to count  the number of times a pattern or word is used in a page. The general syntax is.

preg_match_all(regex,text,output)

Output:

Array
(
    [0] => Array
        (
            [0] => titanic
            [1] => titanic
        )

)

3. preg_replace – This acts as the find and replaces, the general syntax is

preg_replace (find,replace,text).

Output:

Queen Elizabeth was a big ship. Queen Elizabeth hit an iceberg

4. preg_split

General syntax : preg_split(regex,text)

$text="titanic was a big ship. titanic hit an iceberg";
$SplittedText=preg_split("/t[\w]{5}c/",$text);
print_r($SplittedText);

output: 

Array
(
    [0] => 
    [1] =>  was a big ship. 
    [2] =>  hit an iceberg
)

So that deals with all the basics of regex, learn all these regexes and try building new ones by  yourself! We love comments,  If you got some suggestions, thanks or whatever put it as comments 🙂

 

Why PHP developers are in great demand?

According to statistics, the popularity of PHP is increasing day by day. It is getting more powerful and stable with every update. With the current stable version (5.5 ) , php can be considered as one of the powerful scripting languages available to build web based applications. One of the major   factors which influenced the popularity of PHP is opensource softwares built on top of this language.

Highly popular open source softwares like WordPress (used to build Content Management Systems & Blogging websites), Joomla (used to build Content Management Systems) , Magento (used to build high end shopping carts), OpenCart (used to build simple shopping carts) are all built on top of PHP with MySql as database. All these open source softwares have contributed to the increase in popularity of PHP.

WordPress powers millions of websites as per Alexa,14.75% of the top 1 million websites in this world are powered by WordPress. Similarly Magento is a powerful e-commerce application built using Zend Framework (a framework for PHP & MySql) and is used by many popular shopping carts in our world. All these factors has increased the requirement for professionals with good knowledge in PHP & MySql.

Read 6 Best books to learn PHP and Mysql

I have written this article to help freshers & beginners in PHP to land a good job. Many freshers are looking for jobs in php. In this article, I have tried to show you the latest trends in PHP, the highly popular open source applications, which platforms & software’s you should master and such things to get your first good job in PHP.

programmer

For a beginner/fresher like you, I can assure that PHP is one of the easiest language to master! PHP is basically a server side scripting language used to build web based applications. The language is well defined with thousands of library functions for each of your logical requirements. In fact, the availability of this vast library of built in functions makes PHP much simpler to handle compared to other languages . This advantage stands as a drawback for PHP because it creates an easy entry for any one who knows the thorough basics of any other programming language. If you know the basics of programming or some other languages like C or C++ ,understanding & mastering PHP wont be a tedious task.

It’s not about being a Php developer, its all about being the updated trendy Php developer.

Lets begin..- 8 Steps in getting a job as PHP Developer

What all things you should know to be a good php developer? You need to know the basics of some more languages(like Html,Javascript) etc to be a good php developer. As PHP is very much a server side programming language and is mainly used to build web applications  you need to know the basics or as much as you can about the following web technologies (technologies & languages used to build web based applications).

  1. HTML
  2. CSS
  3. JAVASCRIPT & JQUERY
  4. Database- Mysql

Lets begin with PHP,

[steps]1[/steps]

PHP

First of all you need to learn the basic and advanced PHP. PHP is a simple server side programming language. Usually every programming language has two approaches to build a program. They are called:-

  • Procedural methodology 
  • Object Oriented methodology

1 .Procedural programming

Procedural programming is nothing but the normal way of writing a computer program (just like you wrote in your schools). Its a conventional/academic method which is used fr teaching purpose only. Advantage of procedural programming is that its simple to understand, everything is pretty straight forward. When it comes to industries & real jobs, they prefer people who knows Object Oriented Programming methodology (OOP). OOP is an industry standard programming method which has its own advantages over procedural method.

2. Object Oriented Method.


OOP or Object Oriented Programming has several advantages when it comes to use in industries & web application development companies.

  • Code Re-usability – The code you wrote can be used by another programmer and viceversa
  • Facilitates Collaboration/Teamwork – 2 or more people can work together in the same project
  • Easy Maintenance & Iterations – OOP makes it easy to make alterations to the application and release updated versions.
  • Protection of Data & higher security – OOP method provides better data protection (for the flow of data in between many modules of the program) & higher safety standards for the web application you make.

These are some of the many advantages of OOP .  You are highly recommended to learn the Object Oriented method, and I can give you tons of reasons for that.

  • All of the well functioning and established companies use Object oriented method, so that employees can work together in a team. OOP makes your code modular, so that one person can work in his section without disturbing others sections.
  • Most of the frameworks for PHP like YII, Zend, CodeIgnitor are all designed in OOP methodology.

These two reasons are fair enough to make you learn the object oriented concept.

If you are new to PHP & MySql, W3Schools is a great place to begin your learning curve. W3Schools can give you a great idea about the basics of PHP Programming, MySql, JQuery, Javascript, HTML & CSS.

Note: I have written a detailed  beginners guide to PHP-MySQl-JQuery-Ajax & HTML/CSS in a single article using real examples. I recommend you to read this article for getting better at programming & web application development.

[steps]2[/steps]

HTML (Hyper text mark up language) /CSS

 

html 5

You need to know some  HTML too to be a good web application developer. As you may already know, HTML is used to develop web pages for the web browsers . All the heaps of code which you’ve written(in what ever language be it like PHP, ASP, Python or Ruby) will be rendered as HTML in a browser. HTML is the only language which the web browser knows and reads. What ever view you see in a web browser is delivered to you in HTML. Right click on this webpage and select to view source; you can see the complete HTML of a website. To teach you another example; you might have seen input text boxes in a login form – rite?. You need to know HTML to build the login form (or text inputs ) so that the values can be passed to PHP and processed. So understanding HTML is very very important .

CSS or Cascading style sheets are where we  apply the styles to all the html elements. For instance, if we see some content with green color in a page, it should be coming from the css style sheets. We specify styles for each and every HTML element inside the stylesheet file (called as CSS file). Styles are written & saved as CSS files (by default:- stylesheet.css). Every HTML element can be styled like size of heading tags (H1,H2, H3…), font & color of hyperlinks, position of images etc etc.

You can Learn HTML and  CSS from W3Schools. W3Schools is a great place to begin your HTML & CSS basics.

[steps]3[/steps]

Javascript and Jquery

jquery

In fact jquery is a library of  javascript. Both of them are client side (or browser side) languages used for client side interaction. Now a days most of the visual effects you see in a web page  is implemented using Jquery.

If you need to do some calculations with out sending request to a server (that means with out a page reload), you need to use browser side processing language like javascript. For instance, if you want to calculate sum of two values and display it in browser, you can use Javascript to develop the code for the same.

Browser side/Client side languages must be used to solve problems that don’t really need a server side request. For example, take the case of computing the sum of all products added in a shopping cart. You can do this either using a server side language like PHP or by using a browser side language like Javascript/JQuery. In the first case, a request must be sent to the server and the server must acknowledge request, process the request, and return the result to browser. The whole process takes lot of additional time, additional bandwidth and extra usage of resources. But if you are using a browser side language like Javascript to do the same calculation, the whole process of computing will take place inside the browser. There is no additional request sent to a server residing at some other continent, no additional bandwidth required, no need to reload the page & no extra time required. Computing will happen in an instant and the results are much faster than using a server side language. I hope you got the real difference between using a server side language & browser side language. On the other hand, if you need to communicate with a database like MySql (like storing some values into database or reading some values from database), you should use a server side language like PHP.

Jquery is a great client side scripting language which offers great career opportunities. You can take a look at complete reference to jquery to learn more about it.

[steps]4[/steps]

Databases -Mysql

Databases are where we store data. For an example, if we register in a website with username, password and other details, it should be stored some where so that it can be reused later. When we login to the registered website later, PHP verifies the user name, password and succesfully authenticate the user to the website. Mysql is the best and most common database used with PHP. There are other DB’s like oracle, mongodb, PostgreSql and many others. Different databases have different purposes and the choice to use a database varies with requirements of the application to be built. PHP works best with MySql as there are many inbuilt functions in PHP to interact with MySql. When you use PHP with other databases, you will have to develop custom user defined functions to interact with those databases.

When it comes to the working of data bases, we can narrow it down to two basic processes.

  1.  Inserting new data to database and deleting/replacing the already existing data.
  2.  Fetching the Inserted data for displaying/processing.

A record will be inserted, deleted, updated or fetched from database using PHP by executing database queries. There will be differences in how the data is inserted or fetched, and it can be as simple as fetching a single row from a table to as complex as selecting multiple rows from multiple tables.

You can Learn Mysql basics from W3Schools.

[steps]5[/steps]

Ajax

 

Ajax will help you to send request to server with out a page reload. Most of the modern we based applications are built using ajax functionality so that the number page loads will be minimum. You need to be well versed in ajax too to be a respected & knowledgeable web developer. In fact, learning ajax is the easiest thing compared to all other scripting languages described above. You can use Jquery to send an ajax request and to receive a response. Thats all you need to know with ajax , just sending a request to a file and receiving its response . Here is a real life analogy for an Ajax response.

Request: Who is the American President?

Response : Barack Obama.

Lots of different scenarios occur in a request and response that’s all you need to be aware about.

You can Learn Ajax basics  from W3Schools and then consider Learning Jquery Ajax – the easiest method to handle an ajax request.

[steps]6[/steps]

Frameworks

You don’t need to learn all the frameworks, just learn a framework and get in deep into it. These are the popular frameworks in php at present. And you need to learn at least one framework, most of the standard web development companies(which can give you better payment) uses frameworks for development.

If you are a beginner in frameworks for PHP, I would highly recommend to begin with YII as it is a new framework with high flexibility and easy to handle. YII is easy to learn as well.

Advantages of Yii Framework

yii

Laravel is the another php framework which gained great popularity recently.

  • Heaps of support for Jquery, which will help you to add jquery interactions very easily. Yii has got lots of jquery widgets like popup and many other effects and features.
  • Easy to handle very complex database queries. You can write complex database queries (say the mysql JOIN query used to join multiple tables ) which will be more than 5-6 lines of code in normal cases into a single line using Yii.

Learn Yii – Official guides and class rerferences and Larry Ullman’s Yii tutorials – to master this framework and get deep into it.

[steps]7[/steps]

WordPress

 

wordpress

I have written about WordPress in the beginning of this article. 60 million and more websites in the  world is using WordPress to power the website. According to another data source 1 out of  6 websites is running in WordPress. In fact WordPress is simple if you come to know the basic file and database structure.

A WordPress expert usually dont need to go for a job as there are plenty of other options for him to make decent money by freelancing and self made projects. However many people still prefer the comfort of a good & safe job. If you are interested in WordPress, start getting deeper into it and learn as much as you can. Later you can apply for a job in 2 types of companies – 1) companies that provide WordPress customisation services and 2) companies that create WordPress based products like Premium Themes & Premium Plugins.  The demand for wordPress designers & developers are increasing day by day. Check the link below for the official wordPress reference – Learn WordPress

[steps]8[/steps]

Shopping Carts

 

magento

E-commerce is booming everywhere in developing countries like India, Brazil, China & some African countries. In Europe & American countries E-Commerce is refining its shape and going to the next level. You and I are living in the e-commerce era, so why not be a part of it. If you check the graph of the rise in e-commerce websites (use Google Insights) ,it would be exponential in shape. This leads to high demand for professionals with knowledge in open source e-commerce softwares written in PHP.

There are many open source (PHP-MySql based) e-commerce software’s to choose from. I am listing 4 of them below. You can choose any one of them to build your own customized shopping cart.

  1. Magento
  2. Opencart
  3. Woocommerce
  4. PrestaShop
  5. OsCommerce

Out if these 4,   Magento is the best one in the industry which is stable and reliable. Magento is built upon the Zend Framework. People usually say that Magento is hard to learn, but in fact once you learn the basics, you can master Magento just like any other platforms. Qualified Magento developers are in high demand always and they are paid a handsome remuneration.

You can Learn Magento basics from the SiteGround tutorial.

Opencart can be considered as the lightest shopping cart created using PHP & MySql. It is very easy to learn & customize. Many people use opencart for starting small scale online business as it is easy,flexible and fast loading.

The rise of Woocommerce is another noticeable thing, Woocommerce is a powerful WordPress plugin, which enables your WordPress website to act as a shopping cart. Lots of good looking themes are available in Woocommerce that many people prefer woocommerce now a days. Woocommerce is much simpler and light, compared to magento. And in 2015, a much increased demand for woocommerce is seen. Its not at all a bad idea to learn woocommerce, you can definitely land a job by learning woocommerce.

NB: If you are a beginner you’d better learn opencart and then go to magento, so that you can understand the basic working of a shopping cart before advancing.

If you are beginning to learn web development, you can take a look at my Beginners guide to PHP-Ajax-Javascript-Jquery-Html & Css all in  one tutorial which will help you to improve your learning curve and speed. I have written this tutorial with a real life example which will help you to understand concepts better. 

Final Notes…

To land your first good job as a PHP Web Developer, you dont need to master all these languages, frameworks & open source applications. You only need to be really good at PHP, MySql, JQuery & one framework (preferably Yii or Zend) + one open source software (Magento or WordPress). But having a good command over all these languages & platforms is definitely a double edged advantage and you will be an authority in your domain. This kind of authentic knowledge will definitely land you a premium job with a premium payment package.

Php, Ajax,Jquery,Javascript,Html and Css all these languages are very much related. You need to know all these (or atleast the the basics of all these languages to build a website or web application. Many of you might know these stuffs, but atleast some of you might be confused about the clubbing of all these techniques. This tutorial will help you to understand the basics all these languages and the relation between them in a minimum amount of code.

Step1 : Understanding the html part

First name: Capitalize Javascript
Last name:
Interest :
2nd Interest :
My message Port dummy message

Above  code shows a simple HTML form which contains two divisions in it.

  • div with id = names

Every element got a tag name, attribute and value, consider the a tag Here the tag is “a” and the attribute is href and attribute value is ‘#’.

  • div with id= other details

 

Lets have a close look about whats there inside these divisions.
div names In this div there are two input text boxes into which we can input values. You can check the type attribute for the input boxes has been given as “text”, which makes them text input boxes.  In line no   17(in the second div), the input type is  “submit”, which means its supposed to be a submit button (This submit button helps us to submit the form) .You might also have checked the “a” tag in line number 3,

  Capitalize Javascript

“a” tag generates a hyperlink, this specific “a” tag is very much related to javascript so I will explain this in that section.

div otherdetails

In the second div, there are two select boxes, one text input box and a submit button.The first select box  allows us to select an interest, vehicles or fruits

The second select box is part of our ajax , so I will explain it later , in the ajax section

Step2 :Understanding CSS -Style Sheets

Anything given in the style tags refers makes up the styles for the html, the purpose of using css is to style what we build using html. For instance, adding a color to paragraph.


This style sheet brings up the entire style for the html shown above.  Style sheets are very simple to understand, there are selectors and  properties in stylesheets. We select a particular element from the html and applies the css properties into it, for instance

#names input {
border: 2px solid grey;
margin-left: 24px;
margin-top: 12px;
}

“#” (hash) are for selecting id and “.” (dot) are for selecting a class
css selector
Here we are selecting the element with id “names”. If we give a close look to the html code, we can see that it is selecting the first division with id “names”. #names input, means that we are selecting all the “input” html elements inside the names division.
We can select html elements using the attributes given also.

#otherdetails input[type=submit]

Selects the input elements from the div otherdetails which has attribute type=submit. So, for sure, its selecting the submit button.
Css Properties
Now we are applying the properties to the selected html elements , going above.
The style gives a 2 px grey border to the input boxes and a left margin and right top margin to each and every input elements in the division names.

For the submit button, background-color: #E3E138; property gives the color to the submit button.
Generalizing, Css selectors and properties should have a general format

selector{
property name: property value;
}

Have a look at the different types of css properties

Step 3: Understanding the Php Side

Coming to the php side


First Name :
Last Name :
Message :
Second Interest :

At once we submit the form using the submit button, the form gets submitted or request goes to the server page along with the values we entered inside the input elements . From the code, its clear that the php is printing the values we entered inside the input fields

Step 4: Understanding the Javascript :

Javascripts are very much useful in client side interactions, if we need to do something with php, as it being the server side, request needs to be send to the server where in turn javascript being a client side or browser side language, no request needs to be send to the server or the page doesnt gets reloaded , You saved some of your internet bandwidth right? 🙂
Here is where javascripts can do magic. Imagine that you are building a calculator to sum two values, if you are using php you need to pass both values to server and should get the response from the server (calculated sum ). While in case of javascript, as the sum function is as simple as adding both two values passed, we just need to pass the values to the function to display the result without browser reload or delay.

Here the javascript we are using is two display the value entered in the first name input field to uppercase.

Capitalize Javascript

This “a” tag got an onclick attribute which has a values upper(), which means that it calls the javascript function named upper

Javascripts should be written inside

tags and here in the upper function which we have written,

 var firstname=document.getElementById("fname").value;

Here “document” represents the whole page, getElementById as it means,it gets an element with respect to its id. So as we said about the css selectors, it select the element with id=”fname” which is clearly the first name input field. value is a javascript property which gets the value inserted in that field.

function upper () {
var firstname=document.getElementById("fname").value;
var capitalname= firstname.toUpperCase();
alert(capitalname);
}

So in short variable firstname in the javascript should hold the firstname value which we have entered .
In the second line, we are converting the firstname value to uppercase, using the js function toUpperCase() . After that we are passing that final upper case translated values to the alert function, which displays the transformed name as a popup.

Step 5: Understanding the Jquery Part

Now lets have a close look at how jquery is implemented in this code.

$(document).ready(function(){
$('#dummymessage').click(function(){
$('#otherdetails input[name=message]').val('Hi , How are you?');
});
$("#interest").change(function(){
var datapassed={};
datapassed['interest']=$('#interest').val();
$.post('ajax.php', datapassed,function(response) {
$('#bestinterest').html(response);
});
});
});

This much part deals with the jquery in the entire code.
This can splitted into two sections

1. To port the dummy Message

Use of document.ready

$(document). ready is general for all jqueries, its not necessary if our jquery selectors( same
as css selectors) is selecting an element after its loaded .

Her we are selecting an id equal to “dummymessage” , that is its selecting the a tag next to the
message field,

So with out using the document.ready, we should write the jquery code below that “a”
tag, or else the jquery wont work. Here comes the use of document.ready, this makes sure that,
the jquery functions will be called after loading all the document elements.

Coming back to the jquery, click is a jquery function very much similar to javascript onclick. What happens is that when we click on the “a” tag with the id dummy message, this jquery code gets
executed.

$('#dummymessage').click(function(){
$('#otherdetails input[name=message]').val('Hi , How are you?');
});

Thats what happens inside the function. The above given jquery code is very much similar to the
css generalized syntax except the dollar sign and all.
Generalizing, what we have done above is

$(selector).property(value);

We are selecting the otherdetails div, and the text input field for message in that div.
val() is a jquery propery which deals about the value attribute of an element.

So whats happening in short is, when we click the ‘a tag’, the value, “Hi, How are you “, is inserted
into the message text box.

Step 6: Understanding the Ajax part

2. Ajax request for the dependent drop down

$("#interest").change(function(){
var datapassed={};
datapassed['interest']=$('#interest').val();
$.post('ajax.php', datapassed,function(response) {
$('#bestinterest').html(response);
});
});

You may have seen the dependent drop down in many website to display the state name at once we
select the country name, same is what implemented here.

$("#interest").change

Change is another jquery function which triggers the change of an element. So this jquery function.
gets called once we change the interest dropdown .
datapassed[‘interest’] is a javascript array, into which we ports the value from the interst dropdown.
Lets assume that “vehicles” is the value passed to the array,

Whats written next is the $.post,
this sends a request to the file ajax.php, passes the datapassed array which we made.

Now in ajax.php

  
	 ";
}
else {
?>
	
		
		
	


  • Categories