views:

80

answers:

3

This is a follow-up to a question I asked a few weeks back.

The following:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
       "http://www.w3.org/TR/html4/loose.dtd"&gt;
<html>
<head>
<title>Test</title>
</head>
<body>
<a onclick="start_ajax_request('url.php&key1=val1&key2=val2&key3=val3')">Test</a>
</body>
</html>

will not validate in the W3C validator as HTML 4.01 transitional, wrongly, as far as I can see. It complains about entities and wants each ampersand converted to &amp;. &amp; in the given context however, would be wrong, because my Ajax request needs plain ampersands and will break when fed &amp;.

Is there a way to mask/escape the ampersands in this example so that it's still a valid URL that will pass through the Ajax request, and shuts up the validator?

+1  A: 

Try passing with the JS escape() function and by passing the ampersand as %26 The same way I am sure you see spaces passed as %20

Hope it works

rob - not a robber
This did it for me: urlencode()ing the URL in PHP, and adding unescape() to the JS. Not perfect but works for me, cheers.
Pekka
+1  A: 

You should use the encodeURIComponent() function to send the URL string and then decode it in the reciever. If you're using PHP, you need to do something like this:

utf8_decode(rawurldecode(str));
Gerardo
I don't think this is the point, as the problem is not that URI components are wrognly recognized as a URI, but that the URI is being rejected by the validator. Correct me if I'm wrong.
Pekka
+2  A: 

Alternatively, you could assign the onclick in your JavaScript. This is better because it keeps your markup cleaner. Here's a jquery solution.

$('a').bind('click', function() {
  start_ajax_request('url.php?key1=val1&key2=val2&key3=val3');
});
bic72
Good point, but not doable in my current situation. Still +1
Pekka
Try adding the cdata block. See http://stackoverflow.com/questions/355043/how-do-i-escape-an-ampersand-in-a-javascript-string-so-that-the-page-will-validat
bic72
I don't think cdata will work in an onclick - or will it?
Pekka
It looks like you have a solution, but I was able to get a CDATA block to work in an inline onclick.
bic72