Share On Twitter Facebook Google+ LinkedIn Pinterest Tumblr Reddit
Question

javascript send input data by ajax to PHP for special character

Tags: JavaScript Client-Side
Date:
Status:Resolved
Question Id:25

According to I create a chat application and i use ajax to send message to PHP and I have a problem about special character
If user input sing quote and double quote, the ajax will error and can't send to PHP
formdata.append('chat_message', escape($('#chat_message').val()));

I tried to add escape function then it's work, ajax can send to PHP but when PHP show message very strange as this picture
![https://ibb.co/2k2zkhk](https://)

My question is How can I send the special character without escape?
Or Should I fix this problem on PHP part by convert the special code char back to string?

Answer
Date:
Correct:Yes

When using the fetch API and method POST I have no trouble with special characters.
Tested by this code:

    <form>
        <input type="text" name="message" value="'Hi!' & 'Hello!'">
    </form>
    <span id="out"></span>
    <script>
        fetch('testpost-text.php', {
            method: 'post',
            body: new FormData(document.querySelector('form'))
        }).then(res => {
            return res.text();
        }).then(res => {
            console.log(res);
            document.getElementById('out').innerHTML = res;
        });
    </script>

testpost-text.php:

<?php
foreach ($_POST as $key => $item) {
    echo $key . '=' . $item . '<br>';
}
Answer
Date:
Correct:No

Yeah, I was thinking that if the JavaScript was making a "normal" request, PHP should have no issues, but my JavaScript knowledge is way less than my PHP knowledge. 🙂

Your Answer

Review Your Answer