I want to send a few variables and a string with the POST
method from JavaScript.
I get the string from the database, and then send it to a PHP page. I am using an XMLHttpRequest
object.
The problem is that the string contains the character &
a few times, and the $_POST
array in PHP sees it like multiple keys.
I tried replacing the &
with \&
with the replace()
function, but it 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+="§iune="+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);
The String is:
<span class="style2">"Busola"</span>
This question is related to
javascript
ajax
string
post
xmlhttprequest
The preferred way is to use a JavaScript library such as jQuery and set your data option as an object, then let jQuery do the encoding, like this:
$.ajax({
type: "POST",
url: "/link.json",
data: { value: poststr },
error: function(){ alert('some error occured'); }
});
If you can't use jQuery (which is pretty much the standard these days), use encodeURIComponent.
You can pass your arguments using this encodeURIComponent function so you don't have to worry about passing any special characters.
data: "param1=getAccNos¶m2="+encodeURIComponent('Dolce & Gabbana')
OR
var someValue = 'Dolce & Gabbana';
data: "param1=getAccNos¶m2="+encodeURIComponent(someValue)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
You might want to use encodeURIComponent().
encodeURIComponent(""Busola""); // => %26quot%3BBusola%26quot%3B
Ramil Amr's answer works only for the & character. If you have some other special characters, you should use PHP's htmlspecialchars()
and JS's encodeURIComponent()
.
You can write:
var wysiwyg_clean = encodeURIComponent(wysiwyg);
And on the server side:
htmlspecialchars($_POST['wysiwyg']);
This will make sure that AJAX will pass the data as expected, and that PHP (in case your'e insreting the data to a database) will make sure the data works as expected.
You need to url-escape the ampersand. Use:
var wysiwyg_clean = wysiwyg.replace('&', '%26');
As Wolfram points out, this is nicely handled (along with all the other special characters) by encodeURIComponent.
encodeURIComponent(Your text here);
This will truncate special characters.
Source: Stackoverflow.com