Problem arising from apostrophe usage in Javascript OData request

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.

Answer №1

In case there is a space in the name, it must be encoded after doubling the apostrophes:

var person = "Jane O'Neil";
var encodedName = encodeURIComponent(person.replace(/'/g, "''"));

var endpoint = "/api/search?&$filter=contains(Name,'" + encodedName + "')";

The resulting URL will look like this:

/api/search?&$filter=contains(Name,'Jane%20O''Neil')

Answer №2

Switch up the use of double quotes and single quotes in your code for a different effect.

If you're feeling adventurous, you could experiment with linking multiple JavaScript strings using the concat() method. Check out more info here: concat()

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for customizing a single row in v-data-table? [Vuetify]

My goal is to change the background color of a specific row that contains an entry matching the value of lowestEntry. <v-col cols="8"> <v-data-table :loading="loadEntryTable" loading-text="Searching for data..." ...

Using knockoutjs to call a component on the home page

I am currently facing some challenges with knockoutjs components, as I am following the guidance provided in the official knockout component documentation. Could someone please advise me on how to correctly invoke my widget component on the main page? It ...

The Cpanel encounter a PHP Fatal error due to an unknown function `json_decode()`

Despite having the php 5.6 version, I am still encountering this error. While running a codeigniter project through Cpanel, the following error occurred: PHP Fatal error: Call to undefined function json_decode() in/home/ntn/public_html/application/cont ...

Obtain the URL link from Unsplash where the picture is sourced

As I work on a website, I incorporate a link () to display a random photo. However, the photo refreshes periodically and upon loading the site, all that is visible is this default link: . Is there a method to extract the actual source like so: "". Althou ...

Issue with Firefox mobile's camera functionality

I am facing an issue with my web app for mobile devices where I am trying to display the mobile camera using Firefox mobile browser. I am using nodejs with express as a server and connecting to the server via localhost with my smartphone. Although Firefox ...

How can I show a div beneath a row in an HTML table?

Check out the code snippet below: <html xmlns="http://www.w3.org/1999/xhtml"> <head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script> <style type="text/cs ...

Retrieving JSON data using HTTP GET in Flutter

I am struggling with fetching data. As a newcomer to Flutter, I have been trying to resolve this issue despite reading through various articles. While I was able to retrieve the data individually, I faced difficulty in iterating over it using a loop. Below ...

AngularJS $http.post() response function not executing in the correct sequence

When calling a function from my angular controller to make a $http.post() request, the code below the function call is executing before the successFunction(), preventing the code inside the if block from running. How can I ensure the if block executes wi ...

Creating a webcrawler in C# to download a website featuring ajax pages

Recently, I completed a straightforward web crawler project in C# using Microsoft WebCrawler. This project is designed to download the content from a specific website. In order to ensure successful page retrieval, I have set up an event listener for Docum ...

What is the target of the `__proto__` attribute in a constructor function?

I'm taking the time to dive deeper into prototypal inheritance. I know that an instance's __proto__ property points to the constructor function's prototype object, but where does the constructor function's __proto__ property point to? ...

Each time the button is clicked, the settings and values will rotate, creating a new

I'm looking to create a button system that transitions from "unmarked" to "form" and updates the database with each click. I want users to be able to cycle through the buttons, triggering a post request via ajax to update the associated ID in the data ...

Using the spread operator in the console.log function is successful, but encountering issues when attempting to assign or return it in a

Currently facing an issue with a spread operator that's really getting on my nerves. Despite searching extensively, I haven't found a solution yet. Whenever I utilize console.log(...val), it displays the data flawlessly without any errors. Howev ...

Tips for restricting the size of uploaded files or the quantity of files in multer express and effectively managing any errors

I am currently working on a code that requires me to set limits on file size or the number of files that can be uploaded. For instance, I want to restrict users from uploading more than 100 files at once or limit the total upload size to 100 mb. However, ...

utilizing JSON for transferring information

I am looking for a way to send form data to a PHP file and receive the results back in my app without direct access to the PHP file by the user. Although I attempted the following code, I am having trouble passing the data. Even with Chrome's -disabl ...

Tips for pulling out elements from a JSON string using VBA

In my current situation, I am dealing with a JSON string that looks like this: [ { "Features": { "Level": [ { "endDate": "2018-12-11", "minimum": "0.000000000000", ...

What is the recommended sequence for using decorators in NestJS: @Body(), @Params(), @Req(), @Res()?

How can I properly access the res object to send httpOnly cookies and validate the body with DTO? I keep running into issues every time I attempt it. What is the correct order for these parameters? ...

"Unleashing the power of React Native: A single button that reveals three different names

I have a piece of code that changes the name of a button from (KEYWORD) to a different one (KEYNOS) each time it is clicked. How can I modify it to change to a third value (KEYCH), where the default name is (A, B, C... etc), the first click shows Numbers ...

Using React with Typescript: What is the best way to implement useMemo for managing a checkbox value?

I am currently developing a to-do list project using React and Typescript. At the moment, I have successfully implemented the functionality to add new to-do items via a form and delete them individually. Each item includes a checkbox with a boolean value. ...

"Enhance your website with the powerful combination of SweetAlert

I'm having trouble getting my ajax delete function to work with SweetAlert. I can't seem to find the error in my code. Can someone help me figure out how to fix it? function deletei(){ swal({ title: 'Are you sure?', ...

How to Safeguard an AJAX Service Request using jQuery and PHP (with a Session Token)

Currently, I am developing a framework where form submissions are handled through jQuery ajax calls to a .php service file. Here is a snippet of the jQuery code for reference: var dataSerialized = $(form).serialize(); var service = $(form).attr("action") ...