My Blog

contains PHP and other web related content. (Sometimes there are some off topic things - don't freak out!)

Posts Tagged ‘AJAX’

How to handle AJAX errors with jQuery

Tuesday, August 24th, 2010

Many times, the ‘error’ property of the jQuery AJAX call is ignored. Most often, you’ll see just references to the success portion.

The error attribute of the $.ajax() is a callback – and receives three parameters. These are the XMLHttpRequest with the error, a type of error, and an error object, if one is thrown. For the most part, the first two are the only parts.

Now, the error attribute should be used for actual errors, not logical errors. For example, if you are making an AJAX call to log in the current user, and the user does not exist, this should return a success type message instead of some sort of error. Errors are things like 404′s for the AJAX call, or other HTTP issues. In fact, there are 4 types of errors that will be returned: Error – which is an HTTP error, parseerror – which is an xml/json parsing issue, timeout – which is a script that didn’t respond fast enough, and not modified.

I wrote a generic function to handle the errors. This could be name spaced I suppose or added to your standard library. In this case, it just alerts the error. (On some other sites, I generate a new modal box.)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function ajaxError(request, type, errorThrown)
{
	var message = "There was an error with the AJAX request.\n";
	switch (type) {
		case 'timeout':
			message += "The request timed out.";
			break;
		case 'notmodified':
			message += "The request was not modified but was not retrieved from the cache.";
			break;
		case 'parseerror':
			message += "XML/Json format is bad.";
			break;
		default:
			message += "HTTP Error (" + request.status + " " + request.statusText + ").";
	}
	message += "\n";
	alert(message);
}

In this function, an error message is generated based on the error type. The only error that gets extra information is the default type – which is ‘error’. It then retrieves the HTTP Status code and the Status Text.

Here is an example of this in use:
ajax.php

1
2
<?php
header('HTTP/1.1 503 Service Unavailable');

And, here is the test page. When the user clicks the xx link, it will generate a request to ajax.php. This will generate a 503 error and the error handler will take over.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<html>
	<head>
	<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
	</head>
	<body>
		<a href="#" id="test">xx</a>
		<script type="text/javascript">
			$(function(){
				$("#test").click(function(){
					$.ajax({
						url: "ajax.php",
						success: function(){
							alert('retrieved');
						},
						error: ajaxError
					});
 
					return false;
				});
			});
		</script>
	</body>
</html>

Cross Domain AJAX – A quick anatomy of a mashup

Wednesday, September 19th, 2007

So after searching the Internet for some cross domain AJAX stuff, I noticed two interesting articles. The first was the specifics of writing these queries (located here). Then, the next gave a breakdown of how this might be useful in a mash-up collaborative sense (here).

The one missing point was how the collaboration should occur. There is talk about same parent domain but I think everyone’s forgetting about the DNS/webserver changes that need to happen.

In order to prove my concept on my windows box, I set up the examples. In that previous example, domain D had a subdomain of D_s which pointed to E.

I determined what the IP address of E was and entered that into my hosts file (I don’t have access to a DNS server at the moment) followed by the subdomain D_s.

Next, using apache, I found the virtual host for E, and put in ‘ServerAlias D_s’. This will make sure that the incoming connection to that IP will also respond to that sub domain.

I just wanted to jot this down to help fill in the hole I noticed. :)

AJAX Security Research and Findings – Round 2

Friday, July 6th, 2007

Round 2, and the final round, is complete! The previous article here talked about my initial findings. Well, I was able to try some proofs of concepts on my javascript finding, and I put together our top level recommendations for (”the triangle”). Lets see:

First off…

Javascript Object

Well, I had talked about an issue where you could substitute the javascript object across frames. Well I tried this example. Load up javascripttest.html and click the link. Nope, no dice in IE 6 and 7, FF 1.5 and 2. Whew.

javascripttest.html

1
2
3
4
5
6
7
8
9
10
11
12
13
<html>
<body>
<script type="text/javascript">
 
    function Object() {
        this.hacked = 'test2';
    }
    document.Object = Object;
 
</script>
<iframe src="http://release.local/test.html"></iframe>
</body>
</html>

test.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<html>
<body>
<script type="text/javascript">
    function clicker() {
        var test = {};
        var test2 = new Object();
 
        alert (test.hacked);
        alert (test2.hacked);
    }
</script>
<a href="#" onclick="clicker()">bleh</a>
</body>
</html>

Yah – not an issue with the main browsers I use. I didn’t try it on other ones though – so it might still be an issue… who knows… I was just curious.

The recommendations

I got together a few of my final recommendations (yes, very devoid of anything worthwhile, heh.) This is my own AJAX recommendations I’m going to try to follow too.

My Recommendations

Data Transfer

  • Data should be sent according to the RFC 2616 in regards to GET and POST.
  • Data sent back to the client should be in XML format always except:
    • In cases where JSON is the overall best solution, a javascript based JSON parser should be implemented. Eval() should NEVER be used.
    • Never pass direct dom or javascript commands.
    • In order to preserve separation of view and model, try not to pass any html/css pre-formatted data.
  • AJAX requests should match the security/ssl model of the page they’re on. If the page is SSL, the request must be SSL.

AJAX Processing Script Security

  • An initial token should be initialized and used in every AJAX request. The script should exit immediately if no token is present. A new token does not need to be regenerated each request.
  • Any error checking and validation should be done before the script begins actually processing or including any additional files. Due to the frequency of these requests, do not include additional files until all tests have past.
    • If a test requires an included file to validate the data, it is permissible to skip this step if an error condition already exists. In this case, the error(s) will be returned to the client without the additional validation.
  • If modifying the PHP session, program around conditions that additional asynchronous requests may be modifying the session as well.

AJAX Component Initialization

  • Generally, only two AJAX Request objects should be initialized on a page at any time. The general worker object and the immediate response object. Do not initialize the immediate response object if it is not needed.
  • All non time critical responses should be added to a cache, and then processed FIFO.
  • Time critical responses should create their own object. There shouldn€™t be a time where more than one time critical method is executing with proper planning.

User Interface

  • Always give a visual cue when an AJAX function is activated via a user action. This helps reduce confusion as to why there may be a delay.
    • Only two states are needed – the init and the end state – to provide cues. It is not necessary to change state for each response/state type.
  • Plan for remote script timeouts and display user friendly notifications.
    • If a script times out, every effort to halt the user from invoking that script again should be made. In our environment, most often a timed-out script reflects additional issues that a retry will not fix.

Miscellaneous Notes

  • Javascript Object() overwrite vulnerability existed in certain versions of IE and Firefox but was patched. There appears to still be an issue with Safari. This could be an issue with these AJAX responses. Its been tested on the browsers that we officially support and is not an issue.
  • The recommended library to use for AJAX requests and effects is scriptaculous. This library extends prototype. Yahoo UI libraries are a secondary choice at this time.

AJAX Security Research and Findings – Round 1

Wednesday, June 27th, 2007

(“the triangle”) wants to keep implementing more and more AJAX based systems – but no one ever took time to research into the security issues with this. I did a proof of concept one time with a zip-code function when Big Boy was working there, and from there, they just thought it was amazing. Most recently, some AJAX functionality was proposed for our LIVE public web servers… but I was very hesitant. I don’t know enough about the security and best practices for AJAX requests to be able to securely design and code something for the internet – especially when the end result is connecting to the iSeries and HIPAA data. I requested a research project – and its finally been approved. I’ve spent a few hours and come up with a few ideas and best practices so far. Ok, I’ll be honest, one best practice and 2 ideas – of which I’ll prove/disprove here:

(more…)

  • twitter loader

Follow me on twitter: @aaronsaray

The views on this website are my own and do not reflect the opinions of my employer or clients.
Creative Commons License Home | Open Source | Book | Music | Art | Bio | Resume | Contact
My Baby