It turns out that by jQuery.ajax()
stepping through data
a value containing the character +
multiple times. When receiving it with $_POST
in the PHP file these characters are no longer there.
JavaScript code:
var ejemplo = "esto+ es un ejem+plo";
var postData = 'ejemplo='+ejemplo;
$.ajax({
url: "ejemplo.php",
type: "POST",
data: postData,
success: function(data, status, xhr){
// Els inputs de tipus cam:contacte esborraran el seu value
$('input[tipus=camp_contacte]').val('');
$('#btn_close').click();
},
error: function(jqXhr, status, errorThrown){
console.log("POST " + status + " -> " + errorThrown);
}
});
PHP code:
$texto = $_POST['ejemplo'];
I save the variable $texto
in a database and it is inserted without the +
. I have checked by doing a INSERT
directly and it does let me save +
.
It is just in the POST that I receive them without the +
. I have also verified that ajax()
he sends it well with a console.log(postData)
and they also appear there.
In the encoding of URLs/URIs (the one that is also used in the data sent in the forms) the symbol
+
represents a blank space. To send a+
real, the percent encoding used in URLs/URIs must be used.If you want to send a plus symbol you must correctly encode the data in javascript by using, for example
URLSearchParams
:The result is
ejemplo=esto%2B+es+un+ejem%2Bplo
. As you may have seen, the symbols+
are encoded into entities%2B
that represent the ASCII code of the+
.If you send that text from javascript to PHP you will see that now the information is received correctly.
Below I show you several ways to send the content of the variable
ejemplo
throughjQuery.ajax()
.Sending a string with
URLSearchParams
Using the explanation above, your code would look like this:
Directly submitting a form
FormData
We can also use
FormData
instead:Direct delivery
In the property
data
we can pass as a parameter an object with index/value pairs that will arrive in fields$_POST['índice'] = valor
:Since the property name and variable name are the same, we can omit the property name: