In my current project, I have a text input field that passes a value through JS to fetch filtered data of names from a JSON file using OData query parameters.
However, I've encountered an issue where if a name contains an apostrophe, it results in a bad request when the URL is passed.
I've researched and found that apostrophes should be properly escaped by double quoting. While I attempted this approach, the request ended up with two apostrophes which did not match the data, leading to no results being returned.
Here's a brief overview of the code I'm working with:
JSON
{
"value": [{
"Title": "John O'Smith"
}]
}
HTML
<input type="text" value="John O'Smith" />
<button>Search</button>
JS
var term = $('input').val();
var searchTerm = term.replace(/'/g, "''");
var serviceURL = "/api/service?&$filter=contains(Title,'" + searchTerm + "')";
$('button').on('click', function(){
$.get( serviceURL, function( data ) {
// Code to display filtered JSON data
});
});
When I make the AJAX call with the serviceURL
, the URL shows up as:
/api/service?&$filter=contains(Title,'John O''Smith')
The request is successful but comes back with two apostrophes causing a mismatch with the JSON object.
If I don't use the replace method, I receive a Bad Request
error.
I have also tried escaping the apostrophes using other methods like ('\'', encodeUriComponent) without success.
Any suggestions on how to fix this issue or what I might be missing?
Update
Unfortunately, it seems there was either a separate issue or heavy caching involved, as now everything above is functioning as expected.