Monday 1 July 2013

How to get multiple value in AJAX success using json Encode

json.php

 <script type="text/javascript" language="javascript" src="jquery.js" ></script> // jQuery library   
  <script>   
  $(document).ready(function(){   
  $('#fname').change(function(){ // will be trigger when you select value in selectbox   
   var id = $(this).val(); // store selected value in 'id' variable   
   var ajax_value_file="search.php"; // process file   
   $.ajax // ajax call   
     ({   
      type: "POST",   
      url: ajax_value_file,   
      dataType: "json", // must be defined to use json   
      data: "id="+id,   
      success: function(mydata) // "mydata" will be return from search.php as a json encoded string.   
       {   
       $('#lname').val(mydata.lname); // use mydata as object and get data from string and place it wherever you want. in this case it'll be stored in an input with an ID "lname"   
       $('#mobile').val(mydata.mobile);   
       }   
     });   
  });   
  });   
  </script>   
  <form name="test">   
  First Name : <select id="fname" name="fname">   
  <option value="">Select to get details</option>   
  <option value="1">Test 1</option>   
  <option value="2">Test 2</option>   
  <option value="3">Test 3</option>   
  </select><br/>   
  Last Name : <input type="text" name="lname" id="lname"value=""/><br/> //will be come after select any of first name...   
  Mobile No :<input type="text" id="mobile" name="mobile" value=""/>   
  <input type="button" onclick="javascript:alert('bingo....dude..You`ve made it')" value="Check" />   
  </form>  

search.php

 <?php   
  include_once('config.php'); // Your configuration file path. To connect with database   
  if($_POST['id']!="") {   
  $id=$_POST['id'];   
  $select = "select * from jason where id='".$id."'";   
  $data=$db->select($select);   
  $lname = $data[0]['lname'];   
  $mobile = $data[0]['mobile'];   
  echo $html= json_encode(array("lname" =>$lname,"mobile " => $mobile));  // It will convert this array in json string   
  }   
  ?>   

Thursday 2 May 2013

Formatted snippet to show code

I’ve seen a very nice effect on a number of blogs where code snippets were formatted and (somewhat) syntax highlighted.

I finally got a chance to do some digging and turned up the very cool javascript package called dp-highlighter.

In a nutshell, you put the dp-highlighter files in a folder on your website, then add the following code toward the bottom of any page that needs code highlighted:

<link type="text/css" rel="stylesheet" href="./dphighlighter/SyntaxHighlighter.css"></link>
<script language="javascript" src="dphighlighter/shCore.js"></script>
<script language="javascript" src="dphighlighter/shBrushVB.js"></script>
<script language="javascript" src="dphighlighter/shBrushXml.js"></script>
<script language="javascript">
    dp.SyntaxHighlighter.ClipboardSwf = 'dphighlighter/clipboard.swf';
    dp.SyntaxHighlighter.HighlightAll('code');
</script>
 
 
Make sure you change the shBrushVB.js to whichever language parser you want to use. Just be sure to update the paths above.

Finally, for code you want to highlight, just stick it in a <PRE> tag, and add NAME=”code” CLASS=”VB”, if php then put CLASS="PHP" like this...

<pre name="code" class="vb">

Upload files and rename


We have faced some issue like file duplication or replacing image or file with same name when using upload function. 

Here is the tested script which checks exists files with being uploaded file and check if the same name is exists or not. If any file with the same name exist in your UPLOAD directory then it will rename your files with numeric post fix, that escape you from overwritten existing files. Hope it helps


<form name="form1" method="post" action="" enctype="multipart/form-data">
<label>Upload files : </label><input type="file" name="file" value="" />
<input type="submit" name="submit" value="submit" />
</form>

<?php


$path = "upload/";
if($_POST['submit'])

{
$name = $_FILES['file']['name'];
$name = if_exist_rename($name,$path);
if(move_uploaded_file($_FILES['file']['tmp_name'],"upload/".$name))
    {

        echo "File uploaded successfully";
    }else
    {
        echo "Problem in Upload";
    }

}

function if_exist_rename($name,$path)   
{
$actual_name = pathinfo($name,PATHINFO_FILENAME);
$original_name = $actual_name;
$extension = pathinfo($name, PATHINFO_EXTENSION);

$i = 1;
while(file_exists($path.$actual_name.".".$extension))
    {          
       $actual_name = (string)$original_name.'-'.$i;
       $name = $actual_name.".".$extension;
       $i++;
    }
    return $name;
}
?>

Tuesday 30 April 2013

Youtube Embed code with URL parsing with REGEX validation

<?php

        if($_REQUEST['submit']){
        echo "Your submitted URL : ".$url = $_POST['link']."<br/>";

      /* regex check for youtube link */

 
      $rx = '~
       ^(?:https?://)?              # Optional protocol
       (?:www\.)?                  # Optional subdomain
       (?:youtube\.com|youtu\.be)  # Mandatory domain name
       /
       (?:watch\?v=)?              # Optional
       ([^&]+)           # URI with video id as capture group 1
       ~x';

      $has_match = preg_match($rx, $url);
      if($has_match){
      echo "matched";    //if url matched
      echo "<br/>";


      /* Embed code goes here */   

     $url = $_POST['link'];
     //$url='www.youtube.com/watch?v=ntHYVy7lWoc'; // example link 1
     //$url='http://youtu.be/Z19vR1GldRI'; // example link 1
 

      $url = substr($url,-11); // to get the last 11 character from the link to put in our embed code

     echo <<<EOF
    <object width="700" height="400">
    <param name="movie" value="http://www.youtube.com/v/{$url}&hl=en&fs=1"></param>
    <param name="wmode" value="transparent"></param>   
    <param name="allowFullScreen" value="true"></param>
    <param name="allowscriptaccess" value="always"></param>
    <embed src="http://www.youtube.com/v/{$url}&hl=en&fs=1" wmode="transparent"
           type="application/x-shockwave-flash"
           allowscriptaccess="always"
           allowfullscreen="true"
           width="700"
           height="400"></embed>
</object>
EOF;

    }
    else
    {
    echo "Enter valid url";        // if url doesn't match
    }
}
?>

<form name="form" method="post">
<input type="text" value="" name="link" />
<input type="submit" value="submit" name="submit" />
</form>

Friday 22 March 2013

Improving web performance with Apache and htaccess


Compress content

Compression reduces response times by reducing the size of the HTTP response.
It’s worthwhile to gzip your HTML documents, scripts and stylesheets. In fact, it’s worthwhile to compress any text response including XML and JSON.
Image and PDF files should not be gzipped because they are already compressed. Trying to gzip them not only wastes CPU but can potentially increase file sizes.
To compress your content, Apache 2 comes bundled with the mod_deflate module.
The mod_deflate module provides the DEFLATE output filter that allows output from your server to be compressed before being sent to the client over the network.
Enable gzip compression for text responses:


# BEGIN Compress text files
<ifModule mod_deflate.c>
  AddOutputFilterByType DEFLATE text/html text/xml text/css text/plain
  AddOutputFilterByType DEFLATE image/svg+xml application/xhtml+xml application/xml
  AddOutputFilterByType DEFLATE application/rdf+xml application/rss+xml application/atom+xml
  AddOutputFilterByType DEFLATE text/javascript application/javascript application/x-javascript application/json
  AddOutputFilterByType DEFLATE application/x-font-ttf application/x-font-otf
  AddOutputFilterByType DEFLATE font/truetype font/opentype
</ifModule>
# END Compress text files



Enable browser cache

Web page designs are getting richer and richer over time, which means more scripts, stylesheets and images in the page. A first-time visitor to your page will make several HTTP requests to download all your sites files, but by using the Expires and Cache-Control headers you make those files cacheable. This avoids unnecessary HTTP requests on subsequent page views.
Apache enables those headers thanks to mod_expires and mod_headers modules.
The mod_expires module controls the setting of the Expires HTTP header and the max-age directive of the Cache-Control HTTP header in server responses.
To modify Cache-Control directives other than max-age, you can use the mod_headers module.
The mod_headers module provides directives to control and modify HTTP request and response headers. Headers can be merged, replaced or removed.





# BEGIN Expire headers
<ifModule mod_expires.c>
  ExpiresActive On
  ExpiresDefault "access plus 5 seconds"
  ExpiresByType image/x-icon "access plus 2592000 seconds"
  ExpiresByType image/jpeg "access plus 2592000 seconds"
  ExpiresByType image/png "access plus 2592000 seconds"
  ExpiresByType image/gif "access plus 2592000 seconds"
  ExpiresByType application/x-shockwave-flash "access plus 2592000 seconds"
  ExpiresByType text/css "access plus 604800 seconds"
  ExpiresByType text/javascript "access plus 216000 seconds"
  ExpiresByType application/javascript "access plus 216000 seconds"
  ExpiresByType application/x-javascript "access plus 216000 seconds"
  ExpiresByType text/html "access plus 600 seconds"
  ExpiresByType application/xhtml+xml "access plus 600 seconds"
</ifModule>
# END Expire headers








# BEGIN Cache-Control Headers
<ifModule mod_headers.c>
  <filesMatch "\.(ico|jpe?g|png|gif|swf)$">
    Header set Cache-Control "public"
  </filesMatch>
  <filesMatch "\.(css)$">
    Header set Cache-Control "public"
  </filesMatch>
  <filesMatch "\.(js)$">
    Header set Cache-Control "private"
  </filesMatch>
  <filesMatch "\.(x?html?|php)$">
    Header set Cache-Control "private, must-revalidate"
  </filesMatch>
</ifModule>
# END Cache-Control Headers


Disable HTTP ETag header

ETags were added to provide a mechanism for validating entities that is more flexible than the last-modified date.
The problem with ETags is that they typically are constructed using attributes that make them unique to a specific server hosting a site.
ETags won’t match when a browser gets the original component from one server and later tries to validate that component on a different server.
In Apache, this is done by simply adding the FileETag directive to your configuration file:


# BEGIN Turn ETags Off
FileETag None
# END Turn ETags Off

Tuesday 5 February 2013

Back button. Page expired problem

On IE when user hits back button they get the classic IE "webpage has expired" message.

I have found that setting the following in my php.ini has solved this.
 
'session.cache_limiter=private'

or

You can try this. working for all browser

ini_set("session.cache_limiter", "must-revalidate");

This might help you out...

Tuesday 29 January 2013

Cache problem when downloading file with same name


If you want to be 100% sure that files you update frequently, always show changes made to them right away... use cache busting. You may even have a member site that you allow members to change their files on. If so they may not see updated changes right away unless you cache bust some files. If you are not able to use PHP to cache bust, you can do the same thing using Javascript.

Browser Cache

Browser caching is used to speed up internet browsing by storing files so people do not re-download files they have already downloaded. If you make a change to a file and somebody has the old version cached for that file name, they will not see your new changes in that file.

A user on the internet has a browser in which they use to surf the web. Under normal browser settings while surfing their browser will cache (store) the files from your web site as they browse. Meaning that if they go to your homepage and they see 5 pictures or a flash file, those files get cached so the next time they come to your homepage those elements do not have to re-download to display. They are served up from the user's browser cache if they are detected there.

Cache Busting Files

Cache Busting a file is when we add a random string or number to the end of a URL that we have defined on our pages or in our code. You should not Cache Bust every single page and file on your web site, just the ones you are going to make frequent changes on and you would like for people to always see the most recent design or version of a file.

On any file of your site that you always want the newest version of an image or any file to show, you can append a random number to the end of the URL... this way it has to download new to the user's browser cache... always showing newest file.Examples of Cache Busting Popular File Types Using PHP

Simply put a question mark [ ? ] and then a random number or string on the end of your URLs to those files

Cache Bust an image file

myPicture.jpg?<?php echo rand(); ?>
Cache Bust a Style Sheet

myStyle.css?<?php echo rand(); ?>
Cache Bust an SWF file

myFlash.swf?<?php echo rand(); ?>
Cache Bust an MP3 file

mySong.mp3?<?php echo rand(); ?>
Cache Bust a Style Sheet

myWholePage.html?<?php echo rand(); ?>