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

[Origin]: http://stackoverflow.com/questions/11294107/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";
poststr+="&titlu="+frm.value.titlu;
poststr+="&sectiune="+frm.value.sectiune;
poststr+="&wysiwyg="+wysiwyg_clean;
poststr+="&id_text="+frm.value.id_text;     
xmlhttp.open("POST","lista_ajax.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(poststr);

String is:

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

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.

shareedit
Advertisements

jQuery Ajax error handling, show custom exception messages

http://stackoverflow.com/questions/377644/jquery-ajax-error-handling-show-custom-exception-messages

If making a call to asp.net, 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() {
alert("success");
})
.done(function() { alert("second success"); })
.fail(function(xhr, err) {

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

shareedit