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