jQuery Topics

jQuery Ajax Validation Use the Remote Rule

I only just found out that the jQuery validation plugins has a validation rule called “remote” which can be used to make an ajax request instead of specifying a custom rule which has an ajax call it in. This will save you heaps of time with those custom validation rules. Example: Checking if a users [...]

Read more

10 Ajax/jQuery Autocomplete Tutorials/Plugins

Today we are sharing you our compilation of best Ajax and jQuery autocomplete and autosuggest tutorials and plugins with examples. People these days want an instant search and for this, search engines like Google are doing just this. Enjoy! Related Posts: 10 jQuery Search Scripts jQuery AutoForm Script Easy Form AutoComplete 1. Ajax-Driven JavaScript ComboBox [...]

Read more

$.getScript mutiple scripts

This is very useful for loading mutiple scripts with a callback function containing code that you want to run only when all of the scripts have been loaded. To load mutiple scripts you need to enhance the AJAX $.getScript() function to handle mutiple scripts then simply add them to an array for the first parameter [...]

Read more

How to Setup A Simple AJAX Loading Image

ajax-loading

This is how you can display a simple loading image while your AJAX requests are being processed. Using the .ajaxStart() and .ajaxStop() functions will ensure the loading image is displayed for all AJAX requests fired off on the web page.

View Demo

The Code

<script type="text/javascript">
$(document).ready(function () {
$('#loading')
    .hide()
    .ajaxStart(function() {
        $(this).show();
    })
    .ajaxStop(function() {
        $(this).hide();
    });
});
</script>

The Loading Image

You can also create your own animated GIF using Online AJAX Image Tools.

CSS Only Version

This is the CSS to setup a CSS loading image while your AJAX request is loading.

#loading {
    position:fixed;
    top:0px;
    right:50%;
    background:#fff;
    width:60px;
    height:20px;
    padding:0px;
    padding:4px;
    -moz-border-radius-topleft: 0px;
    -moz-border-radius-topright: 0px;
    -moz-border-radius-bottomright: 5px;
    -moz-border-radius-bottomleft: 5px;
    border-top-left-radius: 0px;
    border-top-right-radius: 0px;
    border-bottom-right-radius: 5px;
    border-bottom-left-radius: 5px;
    -webkit-box-shadow: 3px 3px 3px #0a0a0a;
    -moz-box-shadow: 3px 3px 3px #0a0a0a;
    box-shadow: 3px 3px 3px #0a0a0a;
    border-right-width: 2px;
    border-bottom-width: 2px;
    border-left-width: 2px;
    border-right-style: solid;
    border-bottom-style: solid;
    border-left-style: solid;
    border-right-color: #CCC;
    border-bottom-color: #CCC;
    border-left-color: #CCC;
    z-index: 999999;
}

Read more

jQuery AJAX Differences Between GET vs POST

Quite a few people have been asking me the question “what is the difference between GET and POST when I am specifying an AJAX request?”. These are the key differences between GET and POST when you are specifying an AJAX request using jQuery.

Related posts:


GET vs POST

  • A GET request is used to get data from the server.
  • A POST request is used for modifying data on the server.

When to use GET

If the processing of a form is idempotent (i.e. it has no lasting observable effect on the state of the world), then the form method should be GET. Many database searches have no visible side-effects and make ideal applications of query forms.

  • Use GET for safe actions and POST for unsafe actions.

Characteristics of GET:

  • GET requests can be cached
  • GET requests can remain in the browser history
  • GET requests can be bookmarked
  • GET requests can be distributed & shared
  • GET requests can be hacked

W3.org GET Method Definition

When to use POST

If the service associated with the processing of a form has side effects (for example, modification of a database or subscription to a service), the method should be POST.

  • Use POST when dealing with long requests – if you’re sending large amounts of data, or sensitive data over HTTPS, you will want to use POST. Some browser such as Internet Explorer place a limit on the URL string so this may break the action of some forms if you use GET.

You may consider using POST for the following actions:

  • Posting a message to a bulletin board, newsgroup, mailing list, or similar group of articles
  • Providing a block of data, such as the result of submitting a form, to a data-handling process
  • Extending a database through an append operation
  • Annotation of existing resources

W3.org POST Method Definition

GET vs POST in AJAX calls

Unless you are sending sensitive data to the server or calling scripts which are processing data on the server it is more common to use GET for AJAX calls. This is because when using XMLHttpRequest browsers implement POST as a two-step process (sending the headers first and then the data). This means that GET requests are more responsive – something you need in AJAX environments! Because “Ajax” requests are subject to the same origin policy there is limited security risks when using GET instead of POST. Use GET to “GET” information from the server such as loading a JavaScript file (AJAX shorthand function $.getScript() can be used to do this) or loading a JSON file (AJAX shorthand function $.getJSON() can be used to do this).

jQuery AJAX Functions that use GET as default: $.get(), $.getScript(), $.getJSON(), .load()

jQuery AJAX Functions that use POST as default: $.post()

Example GET AJAX Call – Calling a PHP script to get the number of twitter followers.

$.ajax({
  url: 'getTwitterFollowers.php',
  type: 'GET',
  data: 'twitterUsername=jquery4u',
  success: function(data) {
	//called when successful
	$('#ajaxphp-results').html(data);
  },
  error: function(e) {
	//called when there is an error
	//console.log(e.message);
  }
});

View Demo

Example POST AJAX Call – Submitting a login form.

var $form = $("#myForm");
    var url = $form.attr("action") + "?" + $form.serialize();
    $("#" + id).html(url);

$.ajax({
	type: "POST",
	url: action,
	data: $form,
	success: function(response)
	{
		if(response == 'success')
			$("#myForm").slideUp('slow', function() {
				$("#msg").html("<p class='success'>You have logged in successfully!</p>");
			});
		else
			$("#msg").html("<p class='error'>Invalid username and/or password.</p>");
	}
});

Further Readings

Form Submission Example
This example doesn’t really apply to AJAX as these requests happen behind the scenes but may help you understand further what is happening between the different request types.

When using GET a HTTP request is generated and passes the data to the web server as a set of encoded parameters appended to the URL in a query string.

For instance, it would be a bad idea to use GET for a login form submission as the login details would show in the address bar.

GET /login.php?username=user&password=12345 HTTP/1.1
Host: domain.com

But if we used POST the parameters would be passed within the body of the HTTP request, not in the URL. This would happen behind the scenes between the browser and the web server.

POST /login.php HTTP/1.1
Host: domain.com
username=user&password=12345

GET Caching
GET is intended to be used when you are reading information to display on the page. Browsers will cache the result from a GET request and if the same GET request is made again then they will display the cached result rather than rerunning the entire request.


REST – The “RESTful” Client Server Architecture

HTTP, for example, has a very rich vocabulary in terms of verbs (or “methods”), URIs, Internet media types, request and response codes, etc. REST uses these existing features of the HTTP protocol, and thus allows existing layered proxy and gateway components to perform additional functions on the network such as HTTP caching and security enforcement.

Read about “Representational State Transfer” (REST): http://en.wikipedia.org/wiki/Representational_State_Transfer#RESTful_example:_the_World_Wide_Web


REST – The “RESTful” Web Services (API)

It is a collection of resources, with four defined aspects:
the base URI for the web service, such as http://example.com/resources/
the Internet media type of the data supported by the web service. This is often JSON, XML or YAML but can be any other valid Internet media type.
the set of operations supported by the web service using HTTP methods (e.g., POST, GET, PUT or DELETE).
The API must be hypertext driven.[11]

http://en.wikipedia.org/wiki/Representational_State_Transfer#RESTful_web_services

Conclusion

Well I hope that you have a clear idea of when to use GET and when to use POST. If your still unsure or want to inspect what’s happening behind the scenes of your AJAX calls use a tool like Firebug NET Panel to see where your data is being sent (such as in the header) the type of request. Other than that, happy Ajax’ing!

Read more

5 Online Loading AJAX Spinner Generator Tools

In this post, we’ve collected 10 free online Loading AJAX Spinner Generator Tools to make your own custom AJAX loaders. Easy to create your own simply

  1. Select your spinner type
  2. Choose your colour
  3. Choose your animation speed
  4. Click create

You can also create your own images and use them as loading gif animations, see 10 Online Custom GIF Maker Tools. Enjoy.

1. CSS Load Online Tool

cssload.net is a standard online tool for generating your own Ajax spinner. It has a live preview which is nice and animation speed controls. The primary and secondary colour options give it something special the other tools don’t have or use very well. The beauty of this tool is that it will generate the CSS for you to create a CSS only spinner instead of saving as an image.

css-load

2. Ajax Load Online Tool

ajaxload.info does exactly what is says on the tin, creates you an ajax loader in seconds. Limited to the spinners you can choose but it is always reliable and takes seconds to choose and generate your own coloured spinner with transparent background option.

ajax-load

3. Load Info Online Tool

loadinfo.net offers you 132 spinner images straight up and then after choosing one you can change the colors and size up to 48 by 48. The only drawback is it is slightly slower than the other options but still we’re only talking seconds here. Good option.

load-info

4. Preloaders Online Tool

preloaders.net is probably my pick of the bunch because it has excellent options for choosing custom images.

preloaders

5. Spin.js Online Tool

Spin.js is a plugin which can be used to create your own online tool for Ajax Spinners.

spin-js

Read more

10 Online Custom GIF Maker Tools

In this post, we’ve collected 10 free online gif maker tools to make your own custom AJAX loaders. Easy to create your own simply upload your images to create your own custom animations.

Related posts:

1. gifmake.com

composes with (gif,jpeg,png) pictures an animated GIF.Already animated GIF can also be decomposed.


gifmake.com

Source + Demo

2. gickr.com

Lets you instantly create Animated GIF online, free, right now! Just upload pictures or grab them from your Flickr.


gickr.com

Source + Demo

3. makeagif.com

Creates animated gifs online with free gif animator in just three easy steps. Upload, Customize, Create. Note: You will have to sign up first to use this free tool.


makeagif.com

Source + Demo

4. gifup.com

Your personal GIF animation and avatar generator.


gifup.com

Source + Demo

5. createagif.net

Is a free online animated GIF creator that lets you select images on your computer and turn them into GIF animations. The animation size and speed.


createagif.net

Source + Demo

6. picasion.com

Creates animated GIF online for free.


picasion.com

Source + Demo

7. Animated GIF Maker

Make a GIF free online by uploading your pictures your animated GIF can be used anywhere.


Animated GIF Maker

Source + Demo

8. Gifninja

Creates and splits an Animated Gif.


Gifninja

Source + Demo

9. gifka.com

Your individual GIF animation and avatar creator.


gifka.com

Source + Demo

10. How-to-make-GIF.com

Make a GIF animation online for free! Up to 100 pictures. 100% free gif maker.


How-to-make-GIF.com

Source + Demo

Read more

jQuery.ajax get json code snippet

Just a snippet i use often so thought i would post it for easy access. It basically just grabs a JSON from the same server (remember AJAX only works on the same server, unless you use JSONP or have a Proxy pass in place).

Read more about Ajax and JSON.

(function($) {
	$.ajax({
		type: 'GET',
		url: 'data/data.json',
		async: false,
		datatype: 'JSON',
		success: function(data)
		{
			if (data)
			{
				console.log(data);
			}
		}
	});
})(jQuery);

Read more

jQuery Undetermined String Literal Error

Have you ever come upon this annoying error message: “undetermined string literal”.

undetermined-string-literal

Ok, i’ve got 3 occasions were you might run into this error and how to fix it for each specific case.

  1. Multiple Line Strings
  2. Wrong String Format (Bad Characters)
  3. Angle Brackets

Multiple Line Strings

If your trying to assign a string that covers multiple lines to a variable you might see the “Undetermined String Literal” error. To solve this you must use the JavaScript escape character backslash (“\”) after each line to tell the interpreter where the line ends and to join the string together.

Another way is to simply split your string up into bits and add them together.

Wrong String Format (Bad Characters)

If your trying to assign HTML to a variable you might see the “Undetermined String Literal” error. It might be that you loaded the HTML from somewhere else via ajax and are now trying to use/inspect it. Use the following code to clean up the bad characters in the string before trying to assign it.

Angle Brackets

If your trying to use angle brackets (“>” & “<") within a string you might see the "Undetermined String Literal" error when trying to submit the string data via ajax.

var contentQuery = ‘<securequery consumer="abc" engine="abc" template="abc">first 10 location like "abc"</securequery>’;
//note: abc replaces the actual query

It turns out it was the securequery angle brackets creating the error and I had to hack it (as such) by adding in the angle brackets (“<" & ">“) just before encoding and sending the request via AJAX (see below).

$.ajax({
  type: 'POST',
  url: '/ajax/abc',
  data: 'content=' + encodeURIComponent('<'+contentQuery+'>'),
  dataType: 'html',
  success: function(data){
	console.log(data);
	//display results
	$('#results').html(data);
  }
});

This might even be a bug in jQuery, not sure though. When you test in firebug it works though! So maybe not…

var fine = '<securequery consumer="abc" engine="abc" template="abc">first 10 location like "abc"</securequery>';
console.log(fine);

Read more

jQuery Resources

Learn more about jQuery

jQuery News & Links

Live edit functionality in web pages and web apps is all the rage these days but never fun to implement. ...

I only just found out that the jQuery validation plugins has a validation rule called “remote” which can be used ...

jQuery function to check if horizontal scroll is present – hasHScrollBar() – (or vertical check below also, util function to ...

jQuery function to Set any DOM Element to Top View (bring to front) using CSS Z-Index property.

Is it possible to declare arrays in JavaScript object literal notation? Example 1 – this works with arrays Declaration: Storage ...

To get the a variables type using jQuery there is a jQuery function called .type() which returns “array”, “string”, “number”, ...

In this post you can find tutorials which explain step by step different API use cases with jQuery like Google ...

For valuable work on creation of sites you need a good comfortable editor necessarily. There are many requiring paid products ...

Today we are sharing with you a collection of awesome jQuery Camera Photo plugins. They offer a range of image ...

Back in the day, if you saw something that was animated on a website it was automatically assumed to be ...

In this post, we have compiled a list of 10 jQuery HTML5 Audio players available today, most allow native audio ...

jQuery Mobile is a powerful framework for making mobile web applications. But can we use it to convert existing desktop ...

I have jotted a quick post on a Basic JavaScript Regular Expression Example to give beginners out there a taste ...

In April 2012′s edition of Interestingly Random JavaScript, jQuery and Web Development we bring you some very cool stuff such ...

In this post we are sharing you a roundup of 10 really jQuery plugins as of today. Pretty cool plugins ...

As always expected from the jQuery community, the compilation we have for you today are some good and impressive recently ...

A collection of jQuery PNG/JPEG/GIF plugins that enables image animation, cartoon-like background, etc… let them help you design displays for ...

A collection of JavaScript/jQuery Zip/File/Compressor plugins that allows you to minify your JS code and compress your JS files ready ...

Quick jQuery code snippet on how to keep an element in view. For demo scroll down on any page on ...

Here is what I think is the best and most reliable way to load jQuery library and jQuery UI Libraries. ...

More Links & News

Community Resources

Use jQuery and the Google Maps API to create your own map application.

Super cool and easy way to get stylish tooltips with jQuery.

The right way to include the jQuery library in WordPress.

Share a resource