Problem with & Ntilde and $ _POST

1

I have a problem with the Ñ in my program which can be solved by changing Ñ by & Ntilde. The html is in UTF-8. Neither javascript nor html have a problem with & Ntilde and php sometimes. What happens is that if PHP receives from AJAX NU & NTILDEO (NUÑO) everything happens as it should, but if PHP receives from AJAX & NtildeA & NtildeEZ (ÑAÑEZ) what the variable gets is a "" this only happens when what it commands AJAX starts with & Ntilde. To change Ñ a & Ntilde what I do in javascript is.

valor=valor.replace(/[Ñ]/g,"&Ntilde");

If AJAX sends NU & NTILDEO prints NUÑO and if AJAX sends & NTILDEA & NTILDEEZ prints "".

$apellido = $_POST['apellido'];
echo $apellido;

Does anyone know why this happens?

    
asked by jufrfa 10.11.2017 в 16:36
source

1 answer

1

Instead of putting yourself to replace all the UTF-8 characters with all the edge cases you can get, you better encode the string when you send it, and decode when you receive it:

var valor_codificado=encodeURIComponent(valor);
// Esto convierte "ÑAÑEZ" a "%C3%91A%C3%91EZ"

And on the server side

$apellido = urldecode($_POST['apellido']);
echo $apellido;

Edit: Where does the problem come from?

It depends on how you are sending the information to the backend (for example using a form with enctype='application/x-www-form-urlencoded' which is the enctype by default), it could be receiving a string of the type

nombre=juan&apellido=perez&telefono=5552419

Which is parsed as

nombre = 'juan'
apellido = 'perez'
telefono = '5552419'

If one of the parameters starts with ampersand & what the backend receives is

nombre=juan&apellido=&NtildeA&NtildeEZ&telefono=5552419

What the backend pauses is

nombre = 'juan'
apellido = ''
NtildeA = ''
NtildeEZ= ''
telefono = 5552419

This behavior would be different if your form had the attribute enctype='multipart/form-data'

In the same way, if you are making the request by ajax, the attribute contentType of the request can cause the information to pass either to the superglobal $_POST or pass as a payload in the body of the request, in which case you would have to capture it using something like file_get_contents("php://input") or some convenience method offered by the framework in use.

Edit 2

It is worth mentioning that the htmlentity of the Ñ is Ñ finished in a semicolon.

    
answered by 10.11.2017 / 16:51
source