IMPORTANT!

Snipt is going open source. We've toyed with this idea for quite a while, and have finally decided it's the right way to move forward.

A few things:
  • The entire Snipt source code will be released on GitHub under the 3-clause BSD License on Friday, September 10th.
  • While we'd like to think we're perfect, we realize we're only human. By open sourcing the software that runs this website, certain bugs or security flaws may be discovered that could compromise the privacy of your snipts.
  • Only the Lion Burger team will be able to push commits to the Snipt.net site. Contributors should send a pull request to add new features or submit patches.
  • By using this site, you agree not to be too angry or take any legal action against Lion Burger should this whole thing go up in flames some day.
  • Follow us on Twitter for updates.
I agree, close this message
Sign up to create your own snipts, or login.

Latest 100 public snipts » ajax The latest public ajax snipts.

showing 1-20 of 22 snipts for ajax
  • Detect an AJAX Request in PHP
    <?php
    /* decide what the content should be up here .... */
    $content = get_content(); //generic function;
    
    /* AJAX check  */
    if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    	/* special ajax here */
    	die($content);
    }
    
    /* not ajax, do more.... */
    ?>
    

    copy | embed

    0 comments - tagged in  posted by toannk on Aug 13, 2010 at 6:38 a.m. EDT
  • How to Install Node.js on a Mac
    git clone git://github.com/ry/node.git
    cd node
    ./configure
    make
    sudo make install
    

    copy | embed

    0 comments - tagged in  posted by viatropos on Aug 10, 2010 at 4:39 p.m. EDT
  • ajax state switcher
    YUI({combine: true, timeout: 10000}).use("io",
    
    	function(Y) {
    
    		//Get a reference to the Node that we are using
    		//to report results:
    		//var div = Y.Node.get('#content');
    
    		//A function handler to use for successful requests:
    		var handleSuccess = function(ioId, o, arguments){
                        var div = Y.Node.get('#'+arguments.get("id"));
                        Y.log("Id?" + arguments.get("id"));
                        Y.log("The success handler was called.  Id: " + ioId + ".", "info", "example");
    
                        if(o.responseText !== undefined){
                            div.set("innerHTML", o.responseText);
                        }
    		}
    
    		//A function handler to use for failed requests:
    		var handleFailure = function(ioId, o){
                        Y.log("The failure handler was called.  Id: " + ioId + ".", "info", "example");
                        div.set("innerHTML", "Error");
    		}
    
    		//The URL of the resource to which we're POSTing data:
    		var sUrl = "/admin/services/vswitch";
    
    		//Handler to make our XHR request when the button is clicked:
    		function makeRequest(e){
    
                        pId = undefined;
                        pId = e.currentTarget.get("parentNode");
                        var div = Y.Node.get('#'+ pId.get("id"));
                        div.set("innerHTML", "Y");
                        tId = e.currentTarget.get("id").split("-");
    
                        //Subscribe our handlers to IO's global custom events:
                        Y.on('io:success', handleSuccess, this, pId);
                        Y.on('io:failure', handleFailure, this, pId);
    
                        id = tId[1];
                        type = tId[0];
                        /* Configuration object for POST transaction */
                        var cfg = {
                                method: "POST",
                                data: "data[id]=" + id + "&data[which]=" + type,
                                headers: { 'X-Transaction': 'POST Example'},
                                arguments: {
                                    success: tId
                                }
                        };
    
                        var request = Y.io(sUrl, cfg);
    
                        Y.log(pId.get("id"), "info", "services");
                        //Y.log("Initiating request; Id: " + request.id + ".", "info", "example");
    
    		}
    
    		// Make a request when the button is clicked:
    		Y.on("click", makeRequest, ".state-switch");
    
    	}
    );
    

    copy | embed

    0 comments - tagged in  posted by iamDuncan on Jul 26, 2010 at 2:39 a.m. EDT
  • General helper extract
    <?php
    class GeneralHelper extends AppHelper {
    
        public $helpers = array('Html','Javascript','Form');
    
    
        /**
         * Shows a tick or cross from a boolean value
         * @param boolean $value The current value of the field.
         * @param string $id Id of the record ($model['Model']['id']).
         * @param string $type This can be used when creating an id of the returned element.
         * @return string Image link of a tick if 1, or cross if 0
         */
        function ajaxTC($value, $id, $type = null) {
            if($value == 0) return '<span id="'.$type.'-'.$id.'" class="state-switch astop">'.$this->Html->image('icons/icon_sprite.png', array('alt' => __('No',true))).'</span>';
            elseif($value == 1) return '<span id="'.$type.'-'.$id.'" class="state-switch agreenTick">'.$this->Html->image('icons/icon_sprite.png', array('alt' => __('Yes',true))).'</span>';
            else return __('Data Error');
        }
    
        function incAjaxTC(){
            return $this->output($this->Javascript->includeScript('admin/ajaxTC'));
        }
    }
    ?>
    

    copy | embed

    0 comments - tagged in  posted by iamDuncan on Jul 26, 2010 at 2:37 a.m. EDT
  • Google AJAX Search restricted to multiple domains
    /*
    *  How to restrict a search to a specific website.
    */
    
    google.load('search', '1');
    
    function OnLoad() {
      // Create a search control
      var searchControl = new google.search.SearchControl();
    
      // Add in a WebSearch
      var webSearch = new google.search.WebSearch();
    
      // Add the searcher to the SearchControl
      searchControl.addSearcher(webSearch);
    
      // tell the searcher to draw itself and tell it where to attach
      searchControl.draw(document.getElementById("content"));
    
      // execute an inital search
      searchControl.execute('"site:poynter.org OR site:newsu.org Dunlap"'); }
    
    google.setOnLoadCallback(OnLoad);
    ?
    

    copy | embed

    0 comments - tagged in  posted by gotoplanb on Jul 15, 2010 at 3:24 p.m. EDT
  • JS: prepend ajax text to url
    function addAjax(origHref)
    {
        //var origHref = $('.add-student').attr('href');
        var urlArray = origHref.split(/[\/]/);
        if (urlArray.length > 1)
        {
            var filename = urlArray.pop();
            // if there's a trailing slash, get the next iteration
            if (filename.length < 1) filename = urlArray.pop();
            filename = "/ajax-" + filename;
            return urlArray.join("/") + filename;
        }
        return origHref;
    }
    

    copy | embed

    0 comments - tagged in  posted by robertbanh on Jun 22, 2010 at 10:50 a.m. EDT
  • Funcion Ajax
    function objetoAjax()
    	{
    		var xmlhttp=false;
    		try 
    			{
    				xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    			} 
    		catch (e) 
    			{
    				
    				try 
    					{
    					   xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    					} 
    				catch (E) 
    					{
    						xmlhttp = false;
    					}
    			}
    	
    		if (!xmlhttp && typeof XMLHttpRequest!='undefined') 
    			{
    				xmlhttp = new XMLHttpRequest();
    			}
    		return xmlhttp;
    	}
    

    copy | embed

    0 comments - tagged in  posted by Aldogeno on Jun 09, 2010 at 5:27 a.m. EDT
  • AJAX avatar upload
    $(document).ready(function(){
    
    	var thumb = $('img#thumb');	
    
    	new AjaxUpload('imageUpload', {
    		action: $('form#newHotnessForm').attr('action'),
    		name: 'image',
    		onSubmit: function(file, extension) {
    			$('div.preview').addClass('loading');
    		},
    		onComplete: function(file, response) {
    			thumb.load(function(){
    				$('div.preview').removeClass('loading');
    				thumb.unbind();
    			});
    			thumb.attr('src', response);
    		}
    	});
    });
    

    copy | embed

    1 comment - tagged in  posted by mkelly12 on Feb 24, 2010 at 8:25 p.m. EST
  • AJAX in Joomla 1.5
    <?php
    	/*
    	/com_mycomponent
    	|-/views
    	|  |-/response
    	|     |-/tmpl
    	|     |  |-default.php
    	|     |  |-index.html
    	|     |-view.raw.php
    	*/
    ?>
    
    <?php
    	//default.php
    	defined('_JEXEC') or die('Restricted access');
    	echo $this->response;
    ?>
    
    <?php
    	//view.raw.php
    	defined('_JEXEC') or die('Restricted access');
    
    	jimport( 'joomla.application.component.view');
    
    	class MycomponentViewResponse extends JView{
    		public function plain($tpl=null){
    			$this->setLayout('default');
    			parent::display($tpl);
    		}
    		public function json($tpl=null){
    			$this->response = json_encode($this->response);
    			$this->setLayout('default');
    			parent::display($tpl);
    		}
    	}
    ?>
    
    
    <?php
    	//somewhere in a controller
    	public function check(){
    		$view = &$this->getView('response','raw');
    		$view->response = 'OK';
    		$view->plain();
    	}
    ?>
    
    In your ajax call use the following base URL:
    
    index.php?option=com_mycomponent&format=raw&
    
    Then append the right controller & task parameters to the url, like:
    
    index.php?option=com_mycomponent&format=raw&controller=mycontroller&task=check
    

    copy | embed

    0 comments - tagged in  posted by dukeofgaming on Jan 18, 2010 at 5:07 p.m. EST
  • CW AJAX Dersleri (PrototypeJS) Ders 4
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    	<head>
    		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    		<title>CW PrototypeJS Dersleri. Ders D</title>
    		<script type="text/javascript" src="/jslibs/prototype.js"></script>
    		<script type="text/javascript">
    		
    		function serkan_showclearcode()
    		{
    			var resultdiv = $('clearcode');
    			var htmlcode = $('htmlcode').value.stripTags();
    			
    			resultdiv.innerHTML = htmlcode;
    		}
    		
    		</script>
    		<style type="text/css">
    			.legend { border:1px solid black; font-family:"Helvetica"; width: 400px;}
    			.fieldset {font-family: "Helvetica"; width: 400px;}
    		</style>
    	</head>
    	<body onload="$('htmlcode').focus();">
    		<fieldset class="fieldset">
    			<legend class="legend">Form</legend>
    			<b>HTML Code:</b><br>
    			<textarea rows="5" cols="50" id="htmlcode"></textarea>
    			<input type="button" value="Show clear code" onclick="serkan_showclearcode();" />
    			<hr>
    			<div id="clearcode"></div>
    		</fieldset>
    	</body>
    </html>
    

    copy | embed

    0 comments - tagged in  posted by srknyldz on Dec 28, 2009 at 5:34 p.m. EST
  • CW AJAX Dersleri (PrototypeJS) Ders 3
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    	<head>
    		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    		<title>CW PrototypeJS Dersleri. Ders 3</title>
    		<script type="text/javascript" src="/jslibs/prototype.js"></script>
    		<script type="text/javascript">
    		
    		function serkan_showHide(divID)
    		{
    			$(divID).toggle();
    		}
    		</script>
    		<style type="text/css">
    		
    		* {margin: 0px; padding: 0px;}
    		.protoCSS {border:1px solid black, 
    		margin-bottom:20px; }
    		</style>
    	</head>
    	<body>
    		<div id="serkan" class="protoCSS">
    			Serkan Yildiz
    		</div>
    		<input type="button" onclick="serkan_showHide('serkan');" value="Show/Hide">
    		<div id="cwlodos" class="protoCSS">
    			Mustafa IREN
    		</div>
    		<input type="button" onclick="serkan_showHide('cwlodos');" value="Show/Hide">
    		<div id="zafer" class="protoCSS">
    			Zafer Korucu
    		</div>
    		<input type="button" onclick="serkan_showHide('zafer');" value="Show/Hide">
    	</body>
    </html>
    

    copy | embed

    0 comments - tagged in  posted by srknyldz on Dec 28, 2009 at 5:22 p.m. EST
  • CW AJAX Dersleri (PrototypeJS) Ders 2
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
       "http://www.w3.org/TR/html4/strict.dtd">
    
    <html>
    <head>
    	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    	<title>CW Prototype Dersleri (ders 2)</title>
    	<meta name="author" content="Serkan">
    	<script src="/jslibs/prototype.js" type="text/javascript" charset="utf-8"></script>
    	<script type="text/javascript">
    		function serkan_addToList()
    		{
    			value = $("text").value;
    			if(value != '')
    			{
    				$("appleList").insert('<li>'+value+'</li>');
    			}
    		}
    	</script>
    </head>
    <body>
    	<ul id="appleList">
    		<li>Macbook</li>
    		<li>Macbook Pro</li>
    		<li>iPhone</li>
    	</ul>
    	<input type="text" id="text" />
    	<input type="button" value="Listeye Ekle" onClick="serkan_addToList();" />
    	
    </body>
    </html>
    

    copy | embed

    0 comments - tagged in  posted by srknyldz on Dec 26, 2009 at 11:14 p.m. EST
  • CW AJAX Dersleri (PrototypeJS)
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    	<head>
    		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    		<title>CW PrototypeJS Dersleri.</title>
    		<script type="text/javascript" src="/jslibs/prototype.js"></script>
    		<script type="text/javascript">
    		
    		function serkan_settext()
    		{
    			var inputValue = $('inputvalue').value;
    			var hangiDiv = $('testdiv');
    			hangiDiv.innerHTML = inputValue;	
    		}
    		</script>
    	</head>
    	<body>
    		<fieldset style="width:300px;">
    			<legend>Ders</legend>
    			
    			<input type="text" id="inputvalue" />
    			<input type="button" value="Goster" onclick="serkan_settext();" />
    			<br>
    			<div style="border:1px solid black; padding:2px; width: 280px;" id="testdiv"></div>
    		</fieldset>
    	</body>
    </html>
    

    copy | embed

    0 comments - tagged in  posted by srknyldz on Dec 26, 2009 at 11:03 p.m. EST
  • jquery ajax reload page
    $(document).ready(function(){
     setInterval(function(){
       $("#page_load").load(location.href+"#page_load>*","");
     }, 30000);
    });
    

    copy | embed

    0 comments - tagged in  posted by weldan on Dec 01, 2009 at 9:52 p.m. EST
  • Busca de CEP com Jquery e republica virtual
    <html>
    <head>
    
    <script type="text/javascript">
    // Função única que fará a transação
    	function getEndereco() {
    
       // Se o campo CEP não estiver vazio
    if($.trim($("#cep").val()) != ""){
    /*Para conectar no serviço e executar o json, precisamos usar a função
    getScript do jQuery, o getScript e o dataType:"jsonp" conseguem fazer o cross-domain,
    os outros dataTypes não possibilitam esta interação entre domínios diferentes Estou
    chamando a url do serviço passando o parâmetro "formato=javascript" e o CEP digitado no
    formulário http://cep.republicavirtual.com.br/web_cep.php?formato=javascript&cep="+$("#cep").val()*/
    
    $.getScript("http://cep.republicavirtual.com.br/web_cep.php?formato=javascript&cep="+$("#cep").val(), function(){
    // o getScript dá um eval no script, então é só ler!
    //Se o resultado for igual a 1
    //se o tipo de logradouro for direfente de nulo
    					
    if (resultadoCEP["tipo_logradouro"] != '') {
    	if (resultadoCEP["resultado"]) {
    	// troca o valor dos elementos
    $("#rua").val(unescape(resultadoCEP["tipo_logradouro"]) + ": " + unescape(resultadoCEP["logradouro"]));
    $("#bairro").val(unescape(resultadoCEP["bairro"]));
    $("#cidade").val(unescape(resultadoCEP["cidade"]));
    $("#estado").val(unescape(resultadoCEP["uf"]));
    //dá o foco no numero
    $("#numero").focus();
    		}
    					
    	}	
    					
        });
     }
    }
    
    
    </script> 
    
    
    </head>
    <body>
    <form>
    <fieldset>
      <legend>Formulário de exemplo</legend>
      <label for="cep">CEP:</label>
    <input id="cep" maxlength="8" name="cep" size="9"  onBlur="getEndereco()"/>
    
      <label for="rua">Logadouro:</label>
    <input id="rua" name="rua" size="50" />
    
      <label for="bairro">Bairro:</label>
    <input id="bairro" name="bairro" size="30" />
    
      <label for="cidade">Cidade:</label>
    <input id="cidade" name="cidade" />
    
      <label for="estado">Estado</label>
    <input id="estado" maxlength="2" name="estado" size="2" />
    
      </fieldset>
    </form>
    </body>
    </html>
    

    copy | embed

    0 comments - tagged in  posted by rochacbruno on Oct 20, 2009 at 7:13 a.m. EDT
  • GWT Base64
    /*
    Copyright (c) 2009, Mark Renouf
    All rights reserved.
    
    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are met:
        * Redistributions of source code must retain the above copyright
          notice, this list of conditions and the following disclaimer.
        * Redistributions in binary form must reproduce the above copyright
          notice, this list of conditions and the following disclaimer in the
          documentation and/or other materials provided with the distribution.
        * Neither the name of the <organization> nor the
          names of its contributors may be used to endorse or promote products
          derived from this software without specific prior written permission.
    
    THIS SOFTWARE IS PROVIDED BY Mark Renouf ''AS IS'' AND ANY
    EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
    DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY
    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    */
    /**
     * Custom Base64 encode/decode implementation suitable for use in
     * GWT applications (uses only translatable classes). 
     */
    public class Base64 {
    
        private static final String etab =
            "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    
        private static byte[] dtab = {
            -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
            -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
            -1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,-1,-1,63,52,53,54,
            55,56,57,58,59,60,61,-1,-1,-1,64,-1,-1,-1, 0, 1, 2,
             3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15,16,17,18,19,
            20,21,22,23,24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,
            31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
            48,49,50,51,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
        };
    
        public static String decode(String data) {
            StringBuffer out = new StringBuffer();
            
            // length must be multiple of 4 (with padding)
            if (data.length() % 4 != 0)
                return "";
    
            for (int i = 0; i < data.length();) {
                byte e0 = dtab[data.charAt(i++) & 0x7f];
                byte e1 = dtab[data.charAt(i++) & 0x7f];
                byte e2 = dtab[data.charAt(i++) & 0x7f];
                byte e3 = dtab[data.charAt(i++) & 0x7f];
                
                // Invalid characters in input
                if (e0 == -1 || e1 == -1 || e2 == -1 || e3 == -1)
                    return "";
                
                byte d0 = (byte) ((e0 << 2) + ((e1 >>> 4) & 0x03));
                byte d1 = (byte) ((e1 << 4) + ((e2 >>> 2) & 0x0f));
                byte d2 = (byte) ((e2 << 6) + (e3 & 0x3f));
                
                out.append(Character.toString((char) d0));
                if (e2 != 64)
                    out.append(Character.toString((char) d1));
                if (e3 != 64)
                    out.append(Character.toString((char) d2));
            }
            return out.toString();
        }
        
        public static String encode(String data) {
            StringBuffer out = new StringBuffer();
            
            int i = 0;
            int r = data.length();
            while (r > 0) {
                byte d0, d1, d2;
                byte e0, e1, e2, e3;
                
                d0 = (byte) data.charAt(i++); --r;
                e0 = (byte) (d0 >>> 2);
                e1 = (byte) ((d0 & 0x03) << 4);
                
                if (r > 0) {
                    d1 = (byte) data.charAt(i++); --r;
                    e1 += (byte) (d1 >>> 4);
                    e2 = (byte) ((d1 & 0x0f) << 2);
                }
                else {
                    e2 = 64;
                }
                
                if (r > 0) {
                    d2 = (byte) data.charAt(i++); --r;
                    e2 += (byte) (d2 >>> 6);
                    e3 = (byte) (d2 & 0x3f);
                }
                else {
                    e3 = 64;
                }
                out.append(etab.charAt(e0));
                out.append(etab.charAt(e1));
                out.append(etab.charAt(e2));
                out.append(etab.charAt(e3));
            }
    
            return out.toString();
        }
    }
    

    copy | embed

    0 comments - tagged in  posted by tweakt on Sep 26, 2009 at 9:22 p.m. EDT
  • jQuery Ajax Request
    $.ajax({
    	type: "POST",
    	url: "handler.php",
    	data: "",
    	success: function(response) {
    
    	}
    });
    

    copy | embed

    0 comments - tagged in  posted by Sirupsen on Sep 24, 2009 at 3:16 p.m. EDT
  • Fix tabbing index issue with ajax update panels.
     protected void Page_PreRender(object sender, EventArgs e)
            {
                ScriptManager _scriptManager = (ScriptManager)Master.FindControl("ScriptManager1"); //get scriptmanager from master page
          
    
                if (_scriptManager != null && _scriptManager.IsInAsyncPostBack)
                {
                    Control ctrlWhichRaisedAsyncPostBack = Page.FindControl(_scriptManager.AsyncPostBackSourceElementID);
                    if (ctrlWhichRaisedAsyncPostBack != null)
                    {
                        _scriptManager.SetFocus(ctrlWhichRaisedAsyncPostBack.ClientID);
                    }
                } 
            }
    

    copy | embed

    0 comments - tagged in  posted by cbreier on Sep 14, 2009 at 4:55 p.m. EDT
  • Execute javascript from codebehind with ajax
    UpdatePanel panel = GetPanel().
    
    ScriptManager.RegisterClientScriptBlock(panel, typeof(UpdatePanel), "jscript", "alert('executed');", true);
    

    copy | embed

    0 comments - tagged in  posted by shukri on Sep 08, 2009 at 8:58 a.m. EDT
  • Adobe AIR HTML/AJAX Database Wrapper Class
    /**
     * Adobe AIR HTML/AJAX Database Wrapper Class v1.0.0
     * Copyright (c) 2009 Calvin D. Hill
     * Date: 2009-05-06 (Wed, 6 May 2009)
     * @author: Calvin D. Hill
     * @contact calvin.hill at gmail.com
     */
    function AIRdb() {
    	var d = {};
    
    	/**
    	 * Database filename and extension
    	 */
    	d.filename;
    
    	/**
    	 * Holds our insert id
    	 */
    	d.insert_id;
    
    	/**
    	 * Database API instances
    	 */
    	d.connection;
    	d.sql;
    	d.sql_file;
    
    	/**
    	 * Holds our error message(s)
    	 */
    	d.error;
    
    	/**
    	 * Holds our query results
    	 */
    	d.results;
    
    	/**
    	 * Opens a database connection
    	 */
    	d.open = function(filename) {
    		d.connection = new air.SQLConnection();
    		d.filename = filename;
    		sql_file = air.File.applicationStorageDirectory.resolvePath(filename);
    
    		try {
    			d.connection.open(sql_file);
    		} catch (error) {
    			d.error = 'Error message: ' + error.message + '\nDetails: ' + error.details;
    			d.fail();
    		}
    	}
    
    	/**
    	 * Abort all current sql statements
    	 */
    	d.cancel = function() {
    		d.connection.cancel();
    	}
    
    	/**
    	 * Close connection
    	 */
    	d.close = function() {
    		d.connection.close();
    	}
    
    	/**
    	 * Attempt to get our insert id
    	 */
    	d.get_insert_id = function() {
    		var sql_statement = "SELECT last_insert_rowid();";
    		d.query(sql_statement, d.on_sql_success);
    	}
    
    	/**
    	 * Perform a SQL database query, using current database connection
    	 * @param {string} sql_query
    	 * @param {string} callback
    	 * @param {string} fail_callback
    	 * @return unknown
    	 */
    	d.query = function(sql_query, callback, fail_callback) {
    		sql_query = (sql_query || "").replace(/^\s+|\s+$/g, "");
    		sql = new air.SQLStatement();
    		sql.sqlConnection = d.connection;
    		sql.text = sql_query;
    
    		sql.addEventListener(air.SQLEvent.RESULT, ((callback != null) ? callback : d.on_sql_success));
    		sql.addEventListener(air.SQLErrorEvent, ((fail_callback != null) ? fail_callback : d.fail));
    
    		try {
    			sql.execute();
    		} catch (error) {
    			d.handle_errors(error, sql);
    		}
    
    		//if this was an insert, get our insert id
    		if (sql.text.toLowerCase().indexOf('insert') != -1) {
    			this.insert_id = d.connection.lastInsertRowID;
    		}
    	}
    
    	/**
    	 * Common SQL command: select all entries in database table
    	 * @param {string} table_name
    	 * @param callback
    	 * @param fail_callback
    	 */
    	d.select_all = function(table_name, callback, fail_callback) {
    		var sql_statement = "SELECT * FROM " + table_name + ";";
    		d.query(sql_statement, (typeof(callback) != "undefined" ? callback : null), (typeof(fail_callback) != "undefined" ? fail_callback : null));
    	}
    
    	/**
    	 * Common SQL command: delete all entries in database
    	 * @param {string} table_name
    	 * @param callback
    	 * @param fail_callback
    	 */
    	d.delete_all = function(table_name, callback, fail_callback) {
    		var sql_statement = "DELETE * FROM " + table_name + ";";
    		d.query(sql_statement, (typeof(callback) != "undefined" ? callback : null), (typeof(fail_callback) != "undefined" ? fail_callback : null));
    	}
    
    	// ------- HANDLERS -------//
    
    	/**
    	 * Method to handle successful calls
    	 * @param event
    	 */
    	d.on_sql_success = function(event) {
    		d.results = sql.getResult();
    	}
    
    	/**
    	 * Error handler
    	 */
    	d.handle_errors = function(error, sql_statement, callback, fail_callback) {
    		d.error = "Error message: " + error.message + "\nDetails: " + error.details + sql_statement.text;
    
    		if (fail_callback != null) {
    			fail_callback();
    		} else {
    			d.fail();
    		}
    	}
    
    	/**
    	 * Handler for failed calls
     	 */
    	d.fail = function() {
    		air.trace(d.error);
    		d.close();
    	}
    
    	return d;
    }
    

    copy | embed

    0 comments - tagged in  posted by calvinhi on May 28, 2009 at 12:47 p.m. EDT
Sign up to create your own snipts, or login.