0

I am trying to send a string via ajax using the GET method but whenever that string contains some punctuation characters those characters do not appear when I use the echo in php.

For example if I send a string "sub + 12" the php will echo "sub 12" If I send "&()*", php will echo an empty string.

Why does this happen? Are there any special characters that the string cannot contain?

2
  • 2
    Can you show the relevant code please ?
    – JazZ
    Commented May 31, 2017 at 17:20
  • 1
    show your code which you try Commented May 31, 2017 at 17:20

2 Answers 2

1

you encodeURIComponent(). this is demo code which you can check

something like this encodeURIComponent(yourtext)

first this html code . in text filed enter your text and check this output, this is onkeyup so enter text and check result

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>PHP, jQuery search demo</title>
<link rel="stylesheet" type="text/css" href="my.css">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
    $("input").keyup(function () {
        $('#results').html('');
        var searchString = $("#search_box").val();
        var data = 'search_text=' + encodeURIComponent(searchString);
        if (searchString) {
            $.ajax({
                type: "GET",
                url: 'edit.php',
                data: data,
                dataType: 'text',
                async: false,
                cache: false,
                success: function (result) {
                    $('#results').html(result);
                    //window.location.reload();

                }
            });
        }
    });
});
 </script>

</head>
<body>
<div id="container">
<div style="margin:20px auto; text-align: center;">
<form method="post" action="do_search.php">
    <input type="text" name="search" id="search_box" class='search_box'/>
    <input type="submit" value="Search" class="search_button"/><br/>
</form>
</div>
<div>

<div id="searchresults">Search results :</div>
<ul id="results" class="update">
</ul>

</div>
</div>

</body>
</html>

then create edit.php file

<?php 

$searchquery = $_GET['search_text']; 
echo $searchquery;
?>

then check result . which is working

Output is

Search results :

  &()*
1
  • Thank you very much, encodeURIcomponent was all I needed! Commented Jun 1, 2017 at 8:38
1

Use encodeURI() before sending the request.

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.