How can I send the “&” (ampersand) character via AJAX?


I want to send a few variables and a string with POST method from JavaScript. I get the string from the database, and then send it to a PHP page. I am using XMLHttpRequest object. The problem is that the string contains the character “&” few times, and $_POST array in PHP sees it like multiple keys. I tried replacing the “&” with “\&” with replace() function, but doesn’t seem to do anything. Can anyone help?

The javascript code and the string looks like this:

var wysiwyg = dijit.byId("wysiwyg").get("value");
var wysiwyg_clean = wysiwyg.replace('&','\&');

var poststr = "act=save";

String is:

<span class="style2">&amp;quot;Busola&amp;quot;</span>

You can use encodeURIComponent().

It will escape all the characters that cannot occur verbatim in URLs:

var wysiwyg_clean = encodeURIComponent(wysiwyg);

In this example, the ampersand character & will be replaced by the escape sequence %26, which is valid in URLs.


jQuery Ajax error handling, show custom exception messages

If making a call to, this will return the error message title:

I didn’t write all of formatErrorMessage myself but i find it very useful.

function formatErrorMessage(jqXHR, exception) {

if (jqXHR.status === 0) {
return (‘Not connected.\nPlease verify your network connection.’);
} else if (jqXHR.status == 404) {
return (‘The requested page not found. [404]’);
} else if (jqXHR.status == 500) {
return (‘Internal Server Error [500].’);
} else if (exception === ‘parsererror’) {
return (‘Requested JSON parse failed.’);
} else if (exception === ‘timeout’) {
return (‘Time out error.’);
} else if (exception === ‘abort’) {
return (‘Ajax request aborted.’);
} else {
return (‘Uncaught Error.\n’ + jqXHR.responseText);

var jqxhr = $.post(addresshere, function() {
.done(function() { alert("second success"); })
.fail(function(xhr, err) {

var responseTitle= $(xhr.responseText).filter(‘title’).get(0);
alert($(responseTitle).text() + "\n" + formatErrorMessage(xhr, err) );