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

The functionality of a switch statement relies on the presence of a React-Router

Is there a way to dynamically change the text in a paragraph based on which Route is currently enabled? I tried using a switch statement, but I'm unsure of how to implement it. Any suggestions or ideas? import React from 'react'; import &ap ...

Tips for passing navigator reference to React Native's <Drawer/> component?

Utilizing react-native-drawer ( https://github.com/root-two/react-native-drawer ) in my index.ios.js file, I have the following setup where I am attempting to pass the 'navigator' reference into the <DrawerPanel /> of <Drawer /> compo ...

Apple Safari 14.0.3 restricts JavaScript from setting a cookie expiry date beyond one week from the current date

This is my second time reaching out with this question, but after plenty of trial and error experimentation, I have gathered much more information to share. I have been attempting different methods to set a cookie in Safari using JavaScript 'document ...

When sending strings through an ajax call, spaces are getting converted to "'+'"

In my attempt to utilize AJAX for sending a POST request with multiple strings as parameters, I encountered an issue. The strings I am sending sometimes contain spaces. However, upon receiving the POST on the C# server side, I noticed that the string com ...

I am eager to retrieve the outcome once all the queries have been completed within the loop (using express.js, react.js, and MySQL)

Currently, I am engaged in a personal project that involves using React and Express. The task at hand is to retrieve data spanning 7 days for a specific item from my database and present it in a search list. To achieve this, I attempted the following: U ...

Gatsby: A guide on inserting unadulterated HTML within the head section

Is it possible to insert raw HTML into the <head></head> section of every page in a Gatsby.js project? I need to add a string of HTML for tracking purposes, including inline and external script tags, link tags, and meta tags. For example, here ...

There seems to be a limitation in JS/JQuery where it is unable to append HTML that spans

I am encountering an issue with retrieving data in a div element. It seems that the function provided does not work correctly for files larger than a single line of code or even possibly a string. What can be done to resolve this? <ul class="dropdo ...

Is there a way in JavaScript to convert a web page into a string?

I'm looking for a way to retrieve the HTML content of a webpage using JavaScript, even if it's on a different domain. Similar to what wget does but in JavaScript. I intend to use this for web crawling purposes. Could anyone guide me on how to fe ...

Using CakePHP to transfer information from a view to a controller through AJAX

Recently delving into cakephp, I've been attempting to create a straightforward ajax request to dynamically modify a section of the screen. Although I've come across numerous examples online, I'm struggling to amalgamate them seamlessly! Upo ...

How can we reset multiple selected values (mui chips) in a React Material-UI Autocomplete field when changing the value in a different field?

Is there a way to clear the mui-chips in Material UI Autocomplete TextField when the value in another field is changed? I have been struggling with clearing the subtype value when the Type value changes. Although I can update the drop-down options based on ...

Implementing a switch to trigger a JavaScript function that relies on a JSON object retrieved from a GET request

Having some trouble using a toggle to convert my incoming Kelvin temperature to Celsius and then to Fahrenheit. It loads properly as default Celsius when the page first loads, but once I try toggling the function outside of locationLook, it doesn't se ...

Leveraging Python for JSON Operations

Upon running this code, an error occurred: Traceback (most recent call last): File "/Users/ccharest/Desktop/PCC/remember_me_2.py", line 7, in <module> username = json.load(f_obj) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/py ...

Problem with jQuery datetimepicker plugin not being identified as a date by Date() object wrapper

I have a component that allows users to select a date and time using the datetimepicker plugin found at this link. Here is my current configuration: $('#startDate').datetimepicker({ format: 'Y-m-d\\TH:i:s', }); When I c ...

Enhance your React project by incorporating Material-UI card media elements with the ability to add

I am trying to figure out how to create an opaque colored overlay on top of an image using Material-UI. While it is possible with plain HTML, CSS, and JavaScript, I am facing some challenges with Material-UI. <Card> <CardMedia> <im ...

What is the best way to retrieve a JSP parameter dynamically or how can one create a JSP parameter on the

Currently learning JSP and ajax simultaneously. In the process of creating a dynamic tab that can be added or removed using these steps. Looking to pass parameters from controller to the content area of the newly added tab. 1. When clicking on the &apos ...

Adding shadows to a ShaderMaterial in three.js: A step-by-step guide

My current challenge involves using a customized shader to incorporate gradient colors onto a model. However, I have noticed that the shader lacks clarity when it comes to displaying shadows with well-defined edges (as shown in the first image). It seems t ...

"Is there a way to transfer a value from one list box to another without needing to refresh the page, by utilizing AJAX,

Is there a way to automatically load Related Course levels in the Course Level Listbox when selecting a Course from the Course list? <script type="text/javascript" src="js/jquery.js"></script> <div>Course:<select name="course_id" id= ...

Guide to sending a reference to a child input element using VueJs

I am currently attempting to pass a ref in order to retrieve the value of the input (base-input component) upon submission. The two components are listed below. Despite having a console.log statement in handleSubmit, the email variable always appears as un ...

Ajax call in Spring Boot using Thymeleaf successfully receives a response, however, the data is not being displayed on

After countless attempts to find a solution, my quest for an answer has led me all over the web. However, I'm still unable to make the response display on the page. Here's the code snippet where Thymeleaf loops through a list: <div id="c ...

The current context does not have a reference to TextBox

I am encountering an issue with my simple aspx page. Despite not using Master Content Page, I am seeing the following error: The name 'txtFirstName' does not exist in the current context Here is my Markup: <%@ Page Language="C#" %> &l ...