How to pass variable values to JavaScript

Embedding scripts into templates

This is the most straightforward way of passing values: Embed your JavaScript code into the template/view or whatever you call the thing you’re outputting from your server-side script.

Here’s a PHP example:

<?php
$valueFromPhp=’pass value’;
?>

<html>
 <head>
  <script type=”text/javascript”>
   function onload() {
    alert(‘Value from PHP: <?php echo $valueFromPhp; ?>’);
   }
  </script>
 </head>
 <body onload=”onload()”>
  You’ll get an alert with a value from PHP when this page loads
 </body>
</html>

The example shows a very simple function which just alerts a message with a variable’s value.

The pro’s of this approach is of course the simplicity – as long as the script itself is not very complex, this approach is very easy to use and won’t require any special JavaScript coding tricks either.

However, this approach does not lend itself for reusable code. Because your script is written straight into the template, to reuse it elsewhere you need copypasting. Also, with very complex scripts (which are usually also the reusable kind), this does not really work so well.
 

Passing variables in URLs

This is an approach you are probably familiar with from server-side languages: Using GET or POST variables to pass values to scripts.However, due to limitations of JavaScript, you won’t be able to read POST data using it. Also, it doesn’t have any built in methods for easily accessing GET data either, but it’s possible.

 

Since JavaScript can see the current page’s complete URL, you can create a script to manually parse the variables you want from the URL.Here’s a simple approach to extracting get parameters from the URL:

function getQueryParameters() {
  var query = window.location.href.split(‘?’)[1];
 
  //query won’t be set if ? isn’t in the URL
  if(!query) {
    return { };
  }
 
  var params = query.split(‘&’);
 
  var pairs = {};
  for(var i = 0, len = params.length; i < len; i++) {
    var pair = params[i].split(‘=’);
    pairs[pair[0]] = pair[1];
  }
 
  return pairs;
}

Using the above function, you will get a JS object with each GET parameter showing in the URL, quite similar to $_GET in PHP.The main benefit of parsing the URL for parameters like this in JS is that you can do stand-alone
pages that don’t require interference from a server-side language to set parameters.

Export into Excel

 Exporting data into excel from PHP can done easily without including the Excel classes by using the header command as seen below. Here is the code will show you simple export in excel,

                                                                                                                                                                   

 

 

 

 

 

 

 

 

 

 

 

 

 

header(“Content-type: application/vnd.ms-excel”);
  header(“Content-Disposition: attachment; ame=Report.xls/Report.csv”);
  $STATUS = array(‘Blocked/Inactive’, ‘Active’);
 
  echo “<table width=’100%’  border=’0′ cellpadding=’0′ cellspacing=’0′><thead>”;
  echo “<tr><td>ID</td><td>Email Address</td><td>URL</td></tr></thead>”;
  while($row = mysql_fetch_assoc($result))
  {
   echo “<tr><td>”.$row[‘id’].”</td><td>”.$row[’email’].”</td><td>”.$row[‘url’].”</td></tr>”;
     
  }
  echo “</tbody></table>”;

Introduction: JSON

What is JSON?

JSON, or JavaScript Object Notation, has been getting a large amount of attention recently in the IT world. This is mostly powered by its extremely lightweight implementation, its common usage in API responses, and its already native support in JavaScript. JSON isn’t simply a way to code objects in JavaScript, but it is the actual form that a JavaScript engine will map the object to in memory. In short, it is an extremely fast and powerful way of transporting data between two interfaces.

How does it work?

JSON is capable of setting up data constructs for integers, strings, arrays, and booleans – the most essential data building blocks. Using a carefully defined syntactical construct, JSON can be used to outline an object and with the use of javascript’s eval() function, they can be converted to a working object.

But the power does not end there. Other popular programming languages have been implementing native support for JSON, such as PHP and ActionScript. For example, PHP can now convert an associative array of data into a JSON string by using the new json_encode() function, provided in version 5.2+ of the language. For languages without native support, you can find a full range of implementation classes available at the JSON website.

The Syntax: explained

Declaration

All JSON objects are declared with a pair of curly braces. You can assign them to a variable like you would any other data structure.

    var myObj = {} 

That’s it! While not very powerful, this is all that’s required to create objects using JSON. So let’s start adding some properties to this object.

Strings

We are going make this object represent me, so let’s start by adding my name.

   var myObj = {name: ‘Frank’} 

Let’s take a second to carefully look at what we did here. We wanted to add a property called “name”, and to do so, you simply write the property, “name”. We follow the property label by a colon to separate the property name and its value. To the right of the colon, comes the value. Since we wanted the value to be a string, we put it in quotes.

With the JSON we have put in place, you are now able to access the property by using the dot notation. To access a property, follow the “Variable [dot] property” construct.

      alert(myObj.name) // “Frank” 

Integers

If we wanted to assign a property to the object of an integer data type, there is no need to quote the value.

      var myObj = {} 

Multiple properties are separated by a comma.

      var myObj = {name: ‘Frank’, age: 24}
      alert(“My name is ” + myObj.name + ” and I’m ” + myObj.age);
      // “My name is Frank and I’m 24
 

Booleans

Like integers, booleans are also unquoted
      var myObj = {name: ‘Frank’, age: 24, engaged: true}

Arrays

Arrays can contain a collection of the previously mentioned data types. To define an array, wrap the value in square brackets and separate the values with commas.

Note:
I will now add line breaks and indentation for legibility. It has no bearing on the working order of the object.

      var myObj = { 
          name: ‘Frank’,
          age: 24,
          engaged: true,
          favorite_tv_shows: [‘Lost’, ‘Dirty Jobs’, ‘Deadliest Catch’, ‘Man vs Wild’]
      }

You can access a value in an array in the object by using a combination of the dot notation (to access the objects property) and index notation (to access an indexed value of an array).

      alert(myObj.favorite_tv_shows[1]); // “Dirty Jobs” 

To take the array complexity one step further, an array can also contain other objects.
 
      var myObj = { 
          name: ‘Frank’,
          age: 24, 
          engaged: true,
          favorite_tv_shows: [‘Lost’, ‘Dirty Jobs’, ‘Deadliest Catch’, ‘Man vs Wild’], 
          family_members: [
             {name: “Frank”, age: 57, relation: “father”},  
              {name: “Tina”, age: 26, relation: “sister”}]  
      }

This still requires dot and index notation, with an additional dot notation for accessing the property of the object found in the indexed array value.
 
      alert(myObj.family_members[1].name) // “Tina” 

There is one situation where you will use square brackets to access an objects property and not the dot notation: when you are using a variable as the property name. For example:
  
      var myObj = {  
          name: ‘Frank’,  
          age: 24, 
          engaged: true, 
          favorite_tv_shows: [‘Lost’, ‘Dirty Jobs’, ‘Deadliest Catch’, ‘Man vs Wild’],  
          family_members: [  
              {name: “Frank”, age: 57, relation: “father”},  
              {name: “Tina”, age: 26, relation: “sister”}
          ] 
      }     
 
      var property = “age”
    alert(myObj[property]); // “24”
 

Recap

Take some time experimenting with JSON and you will see that you can pick up the concept and syntax rather quickly. As a caveat that may save you time in the future: certain languages require you to quote the property names, such as ActionScript. If not, it will complain.
 
      myObj = {name: “Frank”} // will complain 
      myObj = {“name”: “Frank”} // will work

Next Auto Increment number in MySql

Fectching the last increment id in MYSQL without using the max() properties can done with the bleow type. while using max() function to get the next auto increment id not an actual value in centralized database. Using below code can get the Auto Increment number on Centralized Server also.

Database Connection Statement,

$tablename = “tablename”;
$next_increment = 0;
$qShowStatus = “SHOW TABLE STATUS LIKE ‘$tablename'”;
$qShowStatusResult = mysql_query($qShowStatus) or die ( “Query failed: ” . mysql_error() . “<br/>” . $qShowStatus );

$row = mysql_fetch_assoc($qShowStatusResult);
$next_increment = $row[‘Auto_increment’];

echo “next increment number: [$next_increment]”;

Uploading large files using .htaccess

Here is a small tips for you which you can use to upload such a large file using file field of the form and move_uploaded_file() function in PHP.

1) Create a .htaccess file in the root folder of web server.

2) Put the following code in side the .htaccess file and save it.

php_value upload_max_filesize 20M
php_value post_max_size 20M
php_value max_execution_time 200
php_value max_input_time 200

Now you can upload the file-size up-to 20MB in a simple way using file field in your html form and move_uploaded_file() function available in PHP. In the above .htaccess file, uploading capability is increased by the four parameter first one is maximum file size for uploading, second one is maximum size of the post data , third one is maximum time in seconds a script is allowed to run before it is terminated by the parser and last one is maximum time in seconds a script is allowed to parse input data such as like file uploads, POST and GET data.

You can change the above parameter to upload the bigger file size than 20MB.

Note:

Passing 0 to max_execution_time implies unlimited script execution time.

Finding Real IP Address

Are you using $_SERVER[‘REMOTE_ADDR’] to find the the client’s IP address in PHP? Well dude, you might be amazed to know that it may not return the true IP address of the client at all time. If your client is connected to the Internet through Proxy Server then $_SERVER[‘REMOTE_ADDR’] in PHP just returns the the IP address of the proxy server not of the client’s machine. So here is a simple function in PHP to find the real IP address of the client’s machine. There are extra Server variable which might be available to determine the exact IP address of the client’s machine in PHP, they are HTTP_CLIENT_IP and HTTP_X_FORWARDED_FOR.

Here is the code,

function getRealIpAddr()
{
    if (!empty($_SERVER[‘HTTP_CLIENT_IP’]))  
//check ip from share internet
    {
      $ip=$_SERVER[‘HTTP_CLIENT_IP’];
    }
    elseif (!empty($_SERVER[‘HTTP_X_FORWARDED_FOR’]))  
//to check ip is pass from proxy
    {
      $ip=$_SERVER[‘HTTP_X_FORWARDED_FOR’];
    }
    else
    {
      $ip=$_SERVER[‘REMOTE_ADDR’];
    }
    return $ip;
}

$ip=getRealIpAddr();

echo “Real IP is…. “.$ip;

zip and force download the files

In this post, I’ll show you how can you download the multiples files in a zip archive using PHP. I’ve made a function in PHP where you’ve to pass the parameters the array of files to be zipped, the second parameter is file name as which zip archive file has to be downloaded and finally the path of files where files to be zipped are located.(assuming that they are all in same folder).

//function to zip and force download the files using PHP
function zipFilesAndDownload($file_names,$archive_file_name,$file_path)
{
  //create the object
  $zip = new ZipArchive();
  //create the file and throw the error if unsuccessful
  if ($zip->open($archive_file_name, ZIPARCHIVE::CREATE )!==TRUE) {
    exit(“cannot open <$archive_file_name>\n”);
  }

  //add each files of $file_name array to archive
  foreach($file_names as $files)
  {
    $zip->addFile($file_path.$files,$files);
  }
  $zip->close();

  //then send the headers to foce download the zip file
  header(“Content-type: application/zip”);
  header(“Content-Disposition: attachment; filename=$archive_file_name”);
  header(“Pragma: no-cache”);
  header(“Expires: 0”);
  readfile(“$archive_file_name”);
  exit;
}

  $file_names=array(‘test.php’,’test1.txt’);
  $archive_file_name=’zipped.zip’;
  $file_path=dirname(__FILE__).’/’;
  zipFilesAndDownload($file_names,$archive_file_name,$file_path);

Create new table exactly like another one

Lets say you have a table at your mysql. Now you want to create a new table which will have exactly the same table structure of old one. Using the LIKE keyword of mysql you can easily create you desired table.

mysql> CREATE TABLE new_table LIKE old_table;

This will create a table “new_table” which will have exactly the same structure of “old_table”. Remember, the data will not copy to the “new_table”. You have to write other command to do that. The command for creating the table with data will be,

mysql> CREATE TABLE new_table SELECT * FROM old_table;

This will create the “new_table” which will have the same structure “old_table”, and will have all the data into it. You can filter the data with WHERE condition at SELECT query. for example,

mysql> CREATE TABLE new_table SELECT * FROM old_table WHERE id > 10;

You can copy the data using INSERT command after creating a table using LIKE keyword. The mysql query will be,

mysql> INSERT INTO new_table SELECT * FROM old_table;

PHP QUIZ

Simple things of PHP can be just as fun as the advanced things in PHP!
To prove that I wanted to make a small quiz, and here it is.

Below you’ll see 10 pieces of PHP5 code, the goal is to figure out the code and know the output before you actually run it.
Have fun!

Array pointer

What will the output be ?

$array = range(0,5);
next($array);
foreach($array as $v) {
  echo $v;
}

 Ouput:
——-
012345

ArrayAccess and isset fun

isset or not isset, thats the question.
$a          = new ArrayObject;
$a[‘fubar’] = NULL;
$null       = NULL;

if (isset($null)) {
        echo 1;
} else {
        echo 2;
}

if (isset($a[‘fubar’])) {
        echo 1;
} else {
        echo 2;
}

if (array_key_exists(‘fubar’, $a)) {
        echo 1;
} else {
        echo 2;
}

Ouput:
——-
211

Typo?

The output might be confusing..
array(4>’a’)

Ouput:
——-
empty value

References

How many notices will be thrown?
error_reporting(E_ALL);
function a( & $array) {}
function b($array) {}
a($array);
b($array);
OR or || – operator precedence

What will the output be?
echo ( 1 ? 0 : 1 or 1 ), ( 1 ? 0 : 1 || 1 );
 
 Ouput:
——-
10

Nesting structures

Will this error, or not?
if (1):
    echo ‘one’;
    if(2) {
        echo ‘two’;
    }
else:
    echo ‘not one’;
endif;

Ouput:
——-
Parse Error

Comment and closing tag

<?php // What will you see when you run this single line of ?\?> php code
Echo print and get what

<?php
  // What do you expect from this ?
  echo print( 1 ); ?>

Ouput:
——-

What wil eval to true ?

 <?php
  // How many times will we get ‘true’ ?

  $boolean  = false;
  echo ($boolean) ? ‘true’ : ‘false’;

  $boolean  = ‘0’;
  echo ($boolean) ? ‘true’ : ‘false’;

  $boolean  = ’00’;
  echo ($boolean) ? ‘true’ : ‘false’;

Ouput:
——-
 falsefalsetrue

First a cast, then a increment but what is shown?

<?php
  // What number will you get to see?
  $integer = (int) ‘PHP’;
  echo ++$integer;

Ouput:
——-
 1

Float boat

 <?php
        // What number will be output?
        $a = 0.1 + 0.7;
        echo (int) ($a*10) + 1 ;

Ouput:
——-
8

Array key fun

 <?php

        $a[ 1 ] = “The one”;
        $a[“a”] = “The second”;
        $a[“1”] = “The who?”;
        $a[“A”] = “CaSe FuN”;
        $a[“01”]= “The last”;

        echo count($a); // How many do you expect?

Ouput:
——-
Warning: Cannot use a scalar value as an array

Array count

 <?php

        $one    = range(1, 3);
        $two    = 7;
        echo count($one) + count($two); // How much will the be?

Ouput:
——-
4

Array key existence

 <?php

        // Will it be isset?

        $a              = range(10,20);
        $a[11]          = “The one and only”;
        $a[’11’]        = null;

        unset($a[1]);
        if (isset($a[11])) {
                echo “Yes, it’s isset!”;
        } else {
                echo “No, it’s not isset.”;
        }

Ouput:
——-
No, it’s not isset.

Array evil sort

 <?php

        $a      = array(0, 1, 0.1=>’a’, 1.1=>’A’);
        sort($a);

        echo count($a); // Is it what you expected?

Ouput:
——-
2

Array reference voodoo

<?php

        $a = array(‘i’,’b’,’b’,’q’,’b’,’!’);
        foreach($a as &$value)  {}
        foreach($a as $value)   {}

        echo    str_rot13( implode(”, $a) ); // how many letters ?

Ouput:
——-
voodoo

Using CSS and Javascript Codes in a Smarty Template

By default, Smarty parses anything that is inside { and } characters including those used in CSS rules and Javascript functions. Without proper coding and escaping techniques, your page will render into a disaster.

There are four (4) ways to escape from Smarty parsing:

   1.Separate your CSS and Javascript codes into their own files and include them into your template using standard HTML methods.

      Linking a CSS file:

      <LINK REL=STYLESHEET HREF=”style.css” TYPE=”text/css”>

      Including a Javascript file:

      <script type=”text/javascript” src=”popup.js”></script>

   2.Enclose embedded CSS and Javascript code with {literal} and {/literal} tags so Smarty engine would leave them alone.

      Embedding CSS:

      <style type=”text/css”>
      <!–
      {literal}
      p {text-indent: 10pt}
      body {margin:0; padding:0;}
      {/literal}
      –>
      </style>

      Declaring embedded Javascript function:

      <script language=”javascript” type=”text/javascript” >
          <!–
              {literal}
                   function hello_world(){
                          alert(‘Hello Smarty World’);
                        }
              {/literal}
             –>
      </script>

   3.Change Smarty’s $left_delimiter and $right_delimiter to custom delimiter strings so you can use curly braces in your templates. In addition, it would allow you to insert template variable values into your CSS and Javascript codes to make them dynamic on the fly at server side.

      The PHP code:

      <?php
      require ‘Smarty.class.php’;
      
      $smarty = new Smarty;
      
      $smarty->left_delimiter = ‘<!–{‘;
      $smarty->right_delimiter = ‘}–>’;
      
      $smarty->assign(‘title’, ‘The Smarty Template Engine’);
      $smarty->assign(‘element’, ‘h1’);
      $smarty->assign(‘size’, ’36px’);
      $smarty->assign(‘popup’, ‘alert’);
      $smarty->display(‘index.tpl’);
      ?>

      The Smarty Template “index.tpl”:

      <head>
      <style type=”text/css”>
      <!–
      <!–{$element}–> {font-size: <!–{$size}–>}
      –>
      </head>
      <body>
      <<!–{$element}–>><!–{$title}–></<!–{$element}–>>
      <script language=”javascript” type=”text/javascript” >
      <!–
      function show_popup()
      {
        <!–{$popup}–>(‘<!–{$title}–>’);
      }
      //–>
      </script>
      </body>

      The code above will output:

      <head>
      <style type=”text/css”>
      <!–
      h1 {font-size: 36px}
      –>
      </head>
      <body>
      <h1>The Smarty Template Engine</h1>
      <script language=”javascript” type=”text/javascript” >
      <!–
      function show_popup()
      {
        alert(‘The Smarty Template Engine’);
      }
      //–>
      </script>
      </body>

   4.Use {ldelim} and {rdelim} tags in place of { and } in defining your CSS rules and JavaScript functions assuming the default delimiters are set. This is not practical for real-world use and it will break when delimiters are set to other strings.

      Define CSS rules:

      <style type=”text/css”>
      <!–
      p {ldelim}text-indent: 10pt;{rdelim}
      body {ldelim}margin:0; padding:0;{rdelim}
      –>
      </style>

      Will output:

      <style type=”text/css”>
      <!–
      p {text-indent: 10pt;}
      body {margin:0; padding:0;}
      –>
      </style>

« Older entries