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.


What is the difference between null and undefined in JavaScript?

In JavaScript, undefined means a variable has been declared but has not yet been assigned a value, such as:

var TestVar;
alert(TestVar); //shows undefined
alert(typeof TestVar); //shows undefined

null is an assignment value. It can be assigned to a variable as a representation of no value:

var TestVar = null;
alert(TestVar); //shows null
alert(typeof TestVar); //shows object

From the preceding examples, it is clear that undefined and null are two distinct types: undefined is a type itself (undefined) while null is an object.


HTML Button Close Window

When in the onclick attribute you do not need to specify is javascript.

<button type="button" onclick="'', '_self', ''); window.close();">Discard/<button>

This should do it. In order to close it your page need to be opened by the script, hence the Here is an article explaining this in detail:


How to send a JSON object using html form data?

Get complete form data as array and json stringify it.

var formData = JSON.stringify($("#myForm").serializeArray());

You can use it later in ajax. Or if you are not using ajax; put it in hidden textarea and pass to server. If this data is passed as json string via normal form data then you have to decode it using json_decode. You’ll then get all data in an array.

  type: "POST",
  url: "serverUrl",
  data: formData,
  success: function(){},
  dataType: "json",
  contentType : "application/json"