Search code examples
htmlapacheurlapostrophe

Apostrophe (Smart Quote) in search throws Apache 400 Bad Request


I have a search form in my web application that throws an Apache 400 Bad Request error when you search using an apostrophe (smart quote, i.e. not '). This happens when someone copy and pastes from Microsoft Word (which automatically converts tick marks to smart quotes).

search box

The form causes a GET request which puts the search string in the URL. Even when I encode the string, it causes this error. What should I do to get this to work?

<script type="text/javascript">

function zend_submit_main() {

    var query = $('#search_field').val();

    if(query != '') {
        var search_field = '/query/' + escape(query);
        var url = '/search/results' + search_field + '/active-tab/contacts';
        window.location = url;
    }

    return false;
}

</script>

<form id="search_form" method="GET" onsubmit="zend_submit_main(); return false;">
    <input type="text" value="search by contact name" onFocus="if (this.value=='search by contact name') { this.value=''; }" onBlur="if (this.value=='') { this.value='search by contact name'; }" name="search_field" id="search_field" style="width:160px;" />
    <input type="submit" value="Go" />
</form>     

Solution

  • Use encodeURIComponent instead of escape:

    var search_field = '/query/' + encodeURIComponent(query);
    

    escape is not a standard function and does not encode the value according to the Percent-encoding as specified by RFC 3986. for example is encoded as "%u2019.