Saturday, March 30, 2013

5 Ways to Make Ajax Calls with jQuery

What is AJAX

 AJAX stands for asynchronous JavaScript and XML. If you see another term XHR, which is shorthand for XML HTTP request, it’s the same thing. Don’t be afraid of this jargon; AJAX is not rocket science.

The key to AJAX’s concept is “asynchronous”. This means something happens to the page after it’s loaded. Traditionally, when a page is loaded, the content remains the same until the user leaves the page. With AJAX, JavaScript grabs new content from the server and makes changes to the current page. This all happena within the lifetime of the page, no refresh or redirection is needed.

Caching AJAX

For static content, we may want the response cached. But for dynamic content, which can change in a second’s time, caching AJAX becomes a bug, right? It should be noted that Internet Explorer always caches AJAX calls, while other browsers behave differently. So we’d better tell the browser explicitly whether or not AJAX should be cached. With jQuery, we can accomplish this simply by typing:

  1. $.ajaxSetup ({  
  2.     cache: false  
  3. }); 
  • load(): Load a piece of html into a container DOM.
  • $.getJSON(): Load a JSON with GET method.
  • $.getScript(): Load a JavaScript.
  • $.get(): Use this if you want to make a GET call and play extensively with the response.
  • $.post(): Use this if you want to make a POST call and don’t want to load the response to some container DOM.
  • $.ajax(): Use this if you need to do something when XHR fails, or you need to specify ajax options (e.g. cache: true) on the fly.

1. load(): Load HTML From a Remote URL and Inject it into the DOM

    $.ajaxSetup ({
        cache: false
    });
    var ajax_load = "<img src='img/load.gif' alt='loading...' />";
   
//    load() functions
    var loadUrl = "ajax/load.php";
    $("#load_basic").click(function(){
        $("#result").html(ajax_load).load(loadUrl);
    });

2. $.getJSON(): Retrieve JSON from a Remote Location

//    $.getJSON()
    var jsonUrl = "ajax/json.php";
    $("#getJSONForm").submit(function(){
        var q = $("#q").val();
        if (q.length == 0) {
            $("#q").focus();
        } else {
            $("#result").html(ajax_load);
            $.getJSON(
                jsonUrl,
                {q: q},
                function(json) {
                    var result = "Language code is \"<strong>" + json.responseData.language + "\"";
                    $("#result").html(result);
                }
            );
        }
        return false;
    });

 

3. $.getScript(): Load JavaScript from a Remote Location

//    $.getScript()
    var scriptUrl = "ajax/script.php";
    $("#getScript").click(function(){
        $("#result").html(ajax_load);
        $.getScript(scriptUrl, function(){
            $("#result").html("");
        });
    });

4. $.get(): Make GET Requests

 //    $.get()
    $("#get").click(function(){
        $("#result").html(ajax_load);
        $.get(
            loadUrl,
            {language: "php", version: 5},
            function(responseText){
                $("#result").html(responseText);
            },
            "html"
        );
    });

5. $.post(): Make POST Requests

//    $.post()
    $("#post").click(function(){
        $("#result").html(ajax_load);
        $.post(
            loadUrl,
            {language: "php", version: 5},
            function(responseText){
                $("#result").html(responseText);
            },
            "html"
        );
    });

Finally… $.ajax():
Up to this point, we’ve examined five commonly used jQuery AJAX functions. They bear different names but, behind the scenes, they generally do the exact same job with slightly different configurations. If you need maximum control over your requests, check out the $.ajax() function.
 

 


 

 

Tuesday, March 26, 2013

PDFKit for ruby on rails

http://stackoverflow.com/questions/68569/text-watermark-on-website-how-to-do-it
<style type="text/css"> #watermark { color: #d0d0d0; font-size: 200pt; -webkit-transform: rotate(-45deg); -moz-transform: rotate(-45deg); position: absolute; width: 100%; height: 100%; margin: 0; z-index: -1; left:-100px; top:-200px; } </style> <div id="watermark"> <p>This is the test version.</p> </div> http://stackoverflow.com/questions/5399458/render-to-string-does-not-find-partials-pdfkit-controller-response respond_to do |format| format.html format.pdf { html = render_to_string(:layout => false , :action => "constitution.pdf.haml") kit = PDFKit.new(html) kit.stylesheets << "#{Rails.root}/public/stylesheets/pdf.css" send_data(kit.to_pdf, :filename => "#{@organisation_name} Constitution.pdf", :type => 'application/pdf', :disposition => 'inline') return } end http://metaskills.net/2011/03/20/pdfkit-overview-and-advanced-usage/ /* Page Breaks */ .pb_before { page-break-before:always !important; } .pb_after { page-break-after:always !important; } .pbi_avoid { page-break-inside:avoid !important; } # My with authentication (sending session cookie name and value) kit = PDFKit.new(model_url(@model), 'margin-left' => '10mm', 'margin-right' => '10mm', page_size: 'A5', cookie: "#{Rails::Application.config.session_options[:key]} #{cookies[Rails::Application.config.session_options[:key]]}") file = kit.to_file("#{Rails.root}/tmp/invoices/#{@invoice.id}.pdf") # My way, rendering file # config/initializers/mime_types.rb Mime::Type.register 'application/pdf', :pdf #Controller def show @invoice = Model.find(params[:id]) respond_to do |format| format.html { render layout: 'invoice' } format.pdf { unless File.exist?("#{Rails.root}/tmp/model/#{@model.id}.pdf") file = pdf_kit.to_file("#{Rails.root}/tmp/model/#{@model.id}.pdf") end send_file "#{Rails.root}/tmp/model/#{@model.id}_pre.pdf", :type => 'application/pdf' } format.xml { render :xml => @invoice } end end private def pdf_kit html = render_to_string(action: :show, layout: 'invoice') kit = PDFKit.new(html, 'margin-left' => '10mm', 'margin-right' => '10mm', page_size: 'A5',) kit.stylesheets << "#{Rails.root}/public/stylesheets/model_pdf.css kit end

Tuesday, March 12, 2013

PostgreSQL installation in Ubuntu 12.04

PostgreSQL is a powerful and reliable object-relational database system. It’s a great alternative for MySQL. It is as easy to set up, performs better and offers far more features.

1. Make sure you already have install python-software-properties
$sudo apt-get install python-software-properties

2.Add PPA repository to my Ubuntu.
$sudo add-apt-repository ppa:pitti/postgresql

3. After adding PPA, update your system apt:
$sudo apt-get update

4.Finally install postgresql-9.1:
$sudo apt-get install postgresql
if you having any error, make sure you already install libpq-dev.The libpq-dev package is for compiling wrappers/clients against libpq.

$sudo apt-get install postgresql-9.1 libpq-dev
5.Now check it out installation is successful or…..

$ locate postgresql
6. If done!!!, Cheers …………..                      Check the install version.

$psql -V
7.Now let’s take look to postgres console

$su postgres

7(a) Setup Root User ‘posrgres’
$sudo passwd postgres
 
give the postgres user a (unix) password,Now we can switch to the user postgres using command 
 
$ su postgres 
 
8. create user
     create user <username> with password '<password>';
   to create user as super user run this
     alter user <username> superuser;
   now quite from postgres console by
     \q

9. now restart your postgres
     $sudo service postgresql restart

Friday, February 8, 2013

System configuration for ruby on rails

INSTALL GIT CURL RVM RUBY HEROKU POSTGRES

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
                                           INSTALL GIT CURL RVM RUBY
#LINK:     https://rvm.io/rvm/install/
#LINK:     http://stackoverflow.com/questions/9056008/installed-ruby-1-9-3-with-rvm-but-command-line-doesnt-show-ruby-v/9056395#9056395

# Above 2 links used to install RVM.
           
# If Previously tried to install rvm or Then first remove (purge) it else start from step 5.

  1.  apt-get --purge remove ruby-rvm
  2.  rm -rf /usr/share/ruby-rvm /etc/rvmrc /etc/profile.d/rvm.sh
  3.  exit

#Open new Terminal (ctrl+shift+T)

  4.  env | grep rvm
  5.  curl -L get.rvm.io | bash -s stable --auto
  6.  exit

#Open new Terminal (ctrl+shift+T)

  7.  curl -L https://get.rvm.io | bash -s stable --ruby
  8.  source /usr/local/rvm/scripts/rvm
  9.  rvm requirements
# rvm requirements will show the requirements of rvm like below in [cmd]       run  cmd.
#    [10. apt-get install build-essential openssl libreadline6 libreadline6-dev curl git-core zlib1g zlib1g-dev libssl-dev libyaml-dev libsqlite3-dev #sqlite3 libxml2-dev libxslt-dev autoconf libc6-dev ncurses-dev automake libtool bison subversion]
  11. exit

#Open new Terminal (ctrl+shift+T)

  12.  source /usr/local/rvm/scripts/rvm
  13.  type rvm | head -1
  14.  rvm -v
  15.  ruby -v
  16.  type rvm | head -1
# It will show RVM is a function.
  17.  rvm list
# It will show list of ruby install on RVM.
  18.  exit
#Open new Terminal (ctrl+shift+T)
  18.  type rvm | head -1
  19.  rvm list
  20.  exit

#Open new Terminal (ctrl+shift+T)
  21.  rvm list
#Above cmd will not work. You have to run 'source /usr/local/rvm/scripts/rvm' cmd every time you open new terminal. [To avoid it change done in .bashrc file]
    22.  gedit ~/.bashrc
# Add [[ -s "/usr/local/rvm/scripts/rvm" ]] && source "/usr/local/rvm/scripts/rvm"         at the end of .bashrc file and save and close.
  23.  source /usr/local/rvm/scripts/rvm
  23.  rvm list
  24.  exit

#Open new Terminal (ctrl+shift+T)

  25.  rvm list





# Now rvm has been completed.
#You can install ruby using rvm.
----------------------------------------------------------------------------------------------------------------------------------
                                                 INSTALL RUBY ON RVM
                                                                               
    1.    rvm install ruby_version
# For example rvm install ruby-1.9.2-p180, rvm install ruby-1.9.2-p320, rvm install 1.8.7 etc.


----------------------------------------------------------------------------------------------------------------------------------
                                                  INSTALLATION of HEROKU

1 => gem install heroku

5 => ssh-keygen -t rsa ( Create your system's new ssh key)                                          
 (link: https://devcenter.heroku.com/articles/keys)
6 => heroku keys:add
7 => heroku keys
8 => git clone git@heroku.com:iqglobal.git -o heroku
9 => cd iqglobal/
10 => bundle install
11 => rake db:create
12 => rake db:migrate

----------------------------------------------------------------------------------------------------------------------------------
                                               INSTALLATION of POSTGRES
Require libpg for installing of pg,when we install pg(gem install pg) then this type of problem create.
1 => apt-get install libpq-dev

Installation of postgres and set create user name from root
1 => sudo apt-get install postgresql-8.4
2 => su postgres
3 => sudo -u postgres createuser --superuser $USER
4 create database "iQglobal_development"   (rake db:create)
5 => pg_restore --verbose --clean --no-acl --no-owner -d iQglobal_development database.dump
----------------------------------------------------------------------------------------------------------------------------------

Thursday, February 7, 2013

Plugin to upload video to YouTube directly from your site


Source code and sample available at: https://github.com/prabgupt/youtube_video_upload_plugin
Usage: Please note that sample is available for RoR3 but it can be easily converted for any underlying platform. Refer README in git repo above to know how to run it in RoR3. To see how to tweak code to use it for any other platform, keep reading the post.
Purpose of this Utility: It will upload end user’s video directly to youtube and is easily integratable within your website.
Few Advantage:
  • No need to have storage on server machine as you can now dump/use all videos directly to/from youtube.
  • In case you have youtube channel, can directly organize video uploaded through your site to youtube channel.
  • NO need for end user to login to youtube first to upload video through your site.
Flow to upload video on YouTube
  1. Website requests  token and upload URL from youtube for every new video request. This is needed to avoid having end user logging into his/her YouTube account.
  2. Post your video to URL received in step#1 with parameter ‘nexturl’. ‘nexturl’ is callback url to be called by YouTube with status and video_id once upload operation is completed with failure or success. You need to send token received in step#1 too along with.
  3. Youtube invokes ‘nexturl’ with status and video_id, if upload is successful. Process/store this video_id as this will be key from now onwards based on which you can perform operations on this video directly in YouTube.
Source code contains of following things that you need to know:
youtubeUtilAPIs.py- Python script that uses Google Data Python client library.  This script contains few methods performing certain operation on youtube.
Usage: py [-t <comma separated title and description>] [-u <video_id>] [-s <video_id>] [-d <video_id>]
-t => to get token and url. Input required is comma separated video title and video description
-u => to get youtube URL for that video. Input required is video_id
-s => to get upload status of the video. Input required is video_id
-d => to delete video from youtube. Input required is video_id
Prerequisite:
    • Please refer Getting Started guide. In nutshell, you need to install Python and then google Data Library as specified in the link.
    • Replace following senstive data inside python script; like developer key, password, etc. with that of yours. You will need to sign in for YouTube developer key. Once signed in, register you product and get values for below attributes. ‘source’ and ‘client_id’   will be the name of the product you registered before.
yt_service.developer_key = ‘xxxxxxx’
yt_service.client_id = ‘xxxxxxx’
yt_service.email = ‘xxxxxxx’
yt_service.password = ‘xxxxxxxx’
yt_service.source = ‘xxxxxxxxxx’
  • Since above utility contains some sensitive data, hence for security reasons you would need to introduce a server side handler that will execute above script on client request and can send the required details back to client. In our case, we have introduced method ‘uploadToken’ inside multimedia controller which execute python script and returns back token and url needed to upload video on youtube.
1234567891011
def uploadToken
cmd = Rails.root.to_s + '/public/scripts/youtubeUtilAPIs.py'
title = "Test Video"
description = "Test Video description"
resp = `#{cmd} -t "#{title},#{description}"`
resp = resp.split('::')
response = (resp.length == 2) ? {:uploadUrl => resp[0], :token => resp[1]} : ""
respond_to do |format|
format.js {render :js => response.to_json}
end
end
  • Below is the HTML code you’ll plug into your website to let end user select the video and upload it to youtube. Code just contains a form to have end use select the video and has action, token value blank at render time. If you have already noticed, there is async ajax request present at end of code which fetches upload URL and token from server at time page is loading and populate it inside form once ajax request gets completed.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
<div id="upload_video">
<div class="field">
<form action='' id="youtube_video_upload" method="post" enctype="multipart/form-data">
<input name="file" type="file" class="multimedia_file"/>
<div class="errMsg" style="display:none;color:red">
You need to specify a file.
</div>
<div class="errMsg2" style="display:none;color:red">
Video cannot be uploaded this time. Please try again after sometime.
</div>
<input class= "token" name="token" type="hidden" value=""/>
<input value="Upload Video File" class="upload_button" type="submit" />
</form>
</div><br/>
</div>
<script>
$(document).ready(function(){
$(' #youtube_video_upload .multimedia_file').click(function(){
$(this).siblings('.errMsg').css("display", "none");
$(this).children('.errMsg2').css("display", "none");
});
$('#youtube_video_upload').submit(function(){
if ($(this).children('.multimedia_file').val() == null || $(this).children('.multimedia_file').val() == ""){
$(this).children('.errMsg').css("display", "");
return false;
}else if ($(this).children('.token').val() == null || $(this).children('.token').val() == ""){
$(this).children('.errMsg2').css("display", "");
return false;
}
$('#youtube_video_upload').children('.upload_button').attr('disabled', 'true');
});
$('#video_link').click(function(){
$("#add_link").css("display", "none");
$("#upload_video").css("display","");
});
$('#youtube_link').click(function(){
$("#upload_video").css("display","none");
$("#add_link").css("display", "");
$('.errMsg').css("display", "none");
$('.errMsg2').css("display", "none");
});
// asyn ajax request to fetch upload URL and token from youtube
$.get('<%= url_for(:action => "uploadToken", :controller => "multimedias", :only_path => false)%>',function(data){
if(data != ""){
$('#youtube_video_upload').attr('action', data.uploadUrl + '?nexturl=<%= url_for(:action => "new", :controller => "multimedias", :only_path => false)%>');
$('#youtube_video_upload').children('.token').val(data.token);
$('#youtube_video_upload').children('.errMsg2').css("display", "none");
}else{
}
}, "json");
});
</script>