9 Simple Ajax Snippets


1. jQuery: Simple Ajax XML Request + Event Handlers

Here is a basic example as to how to set up an Ajax request that will expect an XML return. For you code borrowers, you may have a hard time getting this to work with your own projects without understanding how JS, Ajax, and jQuery work.

[js]
<style type="text/css" media="screen">
.ajaxLoaderCircle{ background: transparent url("http://www.ajaxload.info") top center no-repeat; margin-top: 1em; height: 3em; }
</style>

<!– jQuery 1.3.1 Framework –>
<script type="text/javascript" charset="utf-8" src="http://jqueryjs.googlecode.com/files/jquery-1.3.min.js"></script>

<script type="text/javascript" charset="utf-8">
function getXML( url ){
$.ajax({
url: url,
dataType: "xml",
encoding:"UTF-8",
beforeSend: xmlStart,
success: xmlSuccess,
error: xmlError,
complete: xmlComplete
});
}

function xmlStart( xhrInstance ){
//Clear Any Previously Written HTML
$( "#primary .content" ).html( "" );
//Show Preloader
$( "#primary .content" ).addClass( "ajaxLoaderCSS" );
}

function xmlError( xhrInstance, message, optional ){
$("#primary .content").html("<ul><li>There was an error loading the document.</li></ul>");
}

function xmlComplete( xhrInstance, status ){
$( "#primary .content" ).removeClass( "ajaxLoaderCSS" );
}

function xmlSuccess( data, status ){
//Write your Parse XML Function
parseXML( data );
}

function parseXML( xml ){
// XML Tag identifying each item
var itemTag = "image";
// XML Tag giving the title
var titleTag = "caption";
// XML Tag giving the link
var urlTag = "uri";
// Var for storing the HTML to be displayed
var content = "<ul>";

//Parse the XML and build new <li>’s for each NODE
$( xml ).find( itemTag ).each(function(){
var title = $( this ).find( titleTag ).text();
var url = $( this ).find( urlTag ).text();
content += "<li><a href=\"" + url + "\">" + title + "</a></li>";
});

content += "</ul>";

// Populate the Tertiary div with the content
trace( content );
}
</script>

<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
getXML("http://x-y-z");
}
</script>[/js]

source : http://snipplr.com/view/11880/jquery-simple-ajax-xml-request–event-handlers/

2. JQUERY / AJAX PARSE XML TO TABLE

jQuery Ajax function to load xml data into a table and add class to even rows for striping.

[js]
$(document).ready(function() {
$.ajax({
type: "GET",
url: "data.xml",
dataType: "xml",
success: parseXml
});
function parseXml(xml) {
$(xml).find("location").each(function() {
//find each instance of popupTitle in xml file
var popupTitle = $(this).find("popupTitle").text();
//if blank hide row
if (popupTitle == "") {
$("table#table tbody tr").hide();
} else {
//else add tr and td tags and add alt class for striping
$("table#table tbody").append("<tr>" + "<td nowrap=’nowrap’>" + $(this).find("popupTitle").text() + "</td>" + "<td>" + $(this).find("popupDescription").text() + "</td>" + "</tr>");
$(‘table#table tbody tr:even’).addClass(‘alt’);
}
});
}
});
[/js]

source : http://snipplr.com/view/28423/

3. parse wordpress RSS feed using ajax / jquery

Set your local path to the wordpress install, in my case was: “/blog/feed”. Edit the var contain = make it set to the selector, in my case I’m populated a list tag . Edit the var limit = 5; Set the amount of blog posts you want to display.

[js]
$.ajax({
type: "GET",
url: "/blog/feed",
dataType: "xml",
success: function(xml) {

var contain = $("div.panel ul");
var limit = 5;

$(xml).find(‘item’).each(function(index){
if( index < limit ){
var title = $(this).find(‘title’).text();
var url = $(this).find(‘link’).text();
var pubDate = $(this).find(‘pubDate’).text();
$(‘<li></li>’).html(‘<a href="’+url+’">’+title+’</a>’).appendTo(contain);
return;
}

});//end each
}
});
[/js]

source: http://snipplr.com/view/50152/

4. Simple JQUERY AJAX POST

[js]
<script type="text/javascript">
$(document).ready(function(){
$("form#formId").submit(function() {
inputField = $(‘#inputFieldId’).attr(‘value’);
$.ajax({
type: "POST",
url: "yourpage.php",
cache: false,
data: "inputField ="+ inputField,
success: function(html){
$("#ajax-results").html(html);
}
});
return false;
});
});
</script>
[/js]

source : http://snipplr.com/view/17570/

5. Prevent Stale Ajax Data with jQuery

When running live filters on large, long scripts you can get old, stale results replacing your new, fresh ones. After all, a search for everything containing ‘S” in a large database of city names can take a lot longer than “Seattle”, so your script gets the results for “Seattle”, displays then, then it gets the results for “S” and displays them, replacing the “Seattle” search you really wanted.

This script aborts the previous call before making the new one, effectively preventing that from happening. There are 2 caveats though.

  1. The server may continue to process the request (depending on setup).
  2. The error console logs it as an error, but not a fatal one and no alerts are thrown so the normal end user wont notice.

I have some more information available at the URL.

[js]
function ajax_get(){
if(getting!=”){getting.abort();}
$(‘#loading_animation’).fadeIn();
filter = $.get(‘/path/to/ajax.file’, function(data) {
$(‘#ajax_container’).html(data);
$(‘#loading_animation’).fadeOut();
});
}
[/js]

source : http://fatfolderdesign.com/181/code/prevent-stale-ajax-data-in-jquery

6. Jquery AJAX cross-domain proxy with php

A PHP proxy for jQuery AJAX cross-domain requisitions, created to support friendly-url.

[js]
<?php
$base_url = ‘http://www.yoursite.com/api/’;
$chamada = explode(‘/’, $_SERVER['PHP_SELF']);
$chamada = $chamada[2]; // if this php file is in a subdirectory you may change this key
$url = $base_url.$chamada;
$method = (!empty($_POST)) ? ‘post’ : ‘get’;

$ch = curl_init();

if ($method == ‘get’)
{
if ($_SERVER['QUERY_STRING']) $url .= ‘?’ . $_SERVER['QUERY_STRING'];

curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_URL, $url);
}
else
{
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $_POST);
curl_setopt($ch, CURLOPT_URL, $url);
}

$data = curl_exec($ch);
curl_close($ch);
?>

<!– Example –>
$.get(‘proxy.php/my_api_call’);
$.post(‘proxy.php/my_post_api’, {id:user_id});
[/js]

source : http://snipplr.com/view/41483/

7. jQuery AJAX navigation

[js]
$(document).ready(function() {

// Check for hash value in URL
var hash = window.location.hash.substr(1);
var href = $(‘#nav li a’).each(function(){
var href = $(this).attr(‘href’);
if(hash==href.substr(0,href.length-5)){
var toLoad = hash+’.html #content’;
$(‘#content’).load(toLoad)
}
});

$(‘#nav li a’).click(function(){

var toLoad = $(this).attr(‘href’)+’ #content’;
$(‘#content’).hide(‘fast’,loadContent);
$(‘#load’).remove();
$(‘#wrapper’).append(‘&lt;span id="load"&gt;LOADING…&lt;/span&gt;’);
$(‘#load’).fadeIn(‘normal’);
window.location.hash = $(this).attr(‘href’).substr(0,$(this).attr(‘href’).length-5);
function loadContent() {
$(‘#content’).load(toLoad,”,showNewContent())
}
function showNewContent() {
$(‘#content’).show(‘normal’,hideLoader());
}
function hideLoader() {
$(‘#load’).fadeOut(‘normal’);
}
return false;

});
});
[/js]

source : http://snipplr.com/view/6455/

8. jQuery ajax comment preview

[js]
//$(‘.ukn-search-advanced’).append(‘<em>Looking for:</em><div class="ukn-form-textbox-preview"></div><input class="ukn-search-advanced-submit" type="button" value="Search" onclick="this.form.submit();" />’);
$(‘.ukn-form-textbox-preview’).html($(this).val());
$(this).keyup(function(){
if ($(‘.ukn-form-searchbox’).val() !== "") {
$(‘.ukn-search-advanced-extra’).show();
}
var $comment = ”;
$comment = $(this).val();
$(‘.ukn-form-textbox-preview’).html($comment);
$comment = $comment.replace(/\n/g, "<br />").replace(/\n\n+/g, ‘<br /><br />’).replace(/(\<\/?)script/g, "$1noscript");
})
[/js]

source : http://www.learningjquery.com/2006/11/really-simple-live-comment-preview

9. Set jQuery Ajax Header

[js]
jQuery.ajaxSetup({
‘beforeSend’: function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
})
[/js]

source : http://railscasts.com/episodes/136-jquery




Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>