Having a parameter that contains the characters '&' and '&' can potentially disrupt an AJAX call

Even though there is a similar question here: Parameter with '&' breaking $.ajax request, the solutions provided do not apply to my specific issue. This is because both the question and answers involve jQuery, which I am not familiar with.

I am trying to make an Ajax call with a string parameter that includes a '&', such as "RGR Kabel GmbH & Co. KG".

Here is a simplified version of my AJAX function:

function getData()
{
    var param = "RGR Kabel GmbH & Co. KG";
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function()
    {
        if (xmlhttp.readyState === 4 && xmlhttp.status === 200)
        {
        [... perform some action]
        }
    };
    xmlhttp.open("GET", "../getData.php?q1="+param, true);
    xmlhttp.send();
}

The presence of '&' in the param variable causes the AJAX Call to fail. Instead of one parameter being passed:

q1 : "RGR Kabel GmbH & Co. KG"

It gets split into two parameters:

q1 : "RGR Kabel GmbH "
Co. KG : 

Is there a way to prevent the AJAX call from breaking when using '&' within the parameter?

Any assistance on this matter would be greatly appreciated!

Answer №1

Given that the character & is utilized to separate querystring parameters in a URI, data containing this character must be encoded before being added to the URI. The method encodeURIComponent() can be employed for this purpose.

For example, consider implementing it as follows:

xmlhttp.open("GET", "../getData.php?q1="+encodeURIComponent(param), true);

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 earlier polity of the web page no longer retains the JQuery callback method upon refreshing

Whenever I hit the refresh button on Chrome before my Ajax request succeeds, the callback function complete: function(data){ doSomething()} does not execute. function startMockServer() { $.ajax({ url: "/mocks/[[${id}]]/start", type: "P ...

Bringing in d3js into Angular 2

Is there a way to successfully import d3js into an Angular2 project? I have already installed d3js using npm and added it to my systemJs, but am encountering a traceur.js error. I also attempted to just use the latest cdn in a script tag and tried import * ...

The issue with the $(window).width() property not functioning correctly in Internet Explorer

Currently, I have a Div element with absolute positioning: <div id="target" style="height: 300px; position: absolute; top: 275px;"></div> My goal is to calculate the horizontal resolution of the screen using JavaScript. With this width, I the ...

Incorporate CSS animations prior to removing an element from an array

Before removing an item from my data table, I want to implement a CSS animation. The deletion is initiated by the @click event. I would like to preview the effect of my animation (class delete_animation) before proceeding with the actual removal. var vm ...

Utilize VueJS to pass back iteration values using a custom node extension

Hey there! I'm currently working on a Vue app that generates a color palette based on a key color. The palette consists of 2 lighter shades and 2 darker shades of the key color. To achieve this, I have set up an input field where users can enter a hex ...

What could be causing a react element to fail to update?

I'm currently working on a React component that interacts with a MaterialUi text form. The component utilizes a useState hook to update based on the input received. My goal is to have another variable update when the form is submitted, which will be d ...

Ways to implement a conditional statement to display a div using JavaScript

Looking for a way to utilize Javascript conditions to toggle the visibility of a div in an HTML5 document? Check out this code snippet below: #demo { width: 500px; height: 500px; background-color: lightblue; display: none; } To set the f ...

The outcome of my function designed to calculate the highest possible profit using k transactions is a null array

I have developed a custom function to calculate the maximum profit from a series of stock transactions given a specific number of transactions allowed. Each transaction involves buying at a low price and selling at a higher price, with the rule that you ...

Eliminate any properties with values that exceed the specified number in size

:) I'm trying to create a function that removes properties with values greater than a specified number. I've searched through multiple resources like this question on how to remove properties from a JavaScript object and this one on removing pro ...

The React Vite application encountered an issue: There is no loader configured for ".html" files at ../server/node_modules/@mapbox/node-pre-gyp/lib/util/nw-pre-gyp/index.html

**Encountered errors in a React Vite web app** ** ✘ [ERROR] No loader is configured for ".html" files: ../server/node_modules/@mapbox/node-pre-gyp/lib/util/nw-pre-gyp/index.html ../server/node_modules/@mapbox/node-pre-gyp/lib/node-pre-gyp.js:86 ...

Implement AngularJS to ensure that scripts are only loaded after the page has finished rendering

I am having trouble implementing the TripAdvisor widget on my website. It functions correctly when the page is refreshed, but it does not appear when navigating through links. Additionally, an error message is displayed stating that the document could not ...

I created a custom discord.js-commando command to announce all the channels that my bot is currently active in, however, encountered an unexpected error

const Commando = require('discord.js-commando'); module.exports = class AnnounceCommand extends Commando.Command { constructor(client) { super(client, { name: 'announce', aliases: ['an'], ...

Instead of using a hardcoded value, opt for event.target.name when updating the state in a nested array

When working with a dynamically added nested array in my state, I encounter the challenge of not knowing the key/name of the array. This lack of knowledge makes it difficult to add, update, iterate, or remove items within the array. The problem lies in fun ...

Using Ramda, learn how to transform a flat list into a hierarchical one

Looking to transform the given list into a hierarchical structure with nested children fields. The 'parentId' attribute has been omitted for clarity, as it will be used in the transformation process using Ramda's immutable behavior. const x ...

A mobile device is not utilizing cookies for tracking or storing user data

The mobile authentication detection feature suddenly stopped functioning. Whenever I navigate to a page with a form, the form should make an ajax call to fetch additional information for populating the fields based on user authentication. This process work ...

What is the correct method for downloading an Excel file in a Vue.js application?

I am having difficulty downloading an Excel file in xlsx format using my Vue.js application. The Vue.js application sends a post request to the Node.js application which then downloads the Excel file from a remote SFTP server. The backend application is fu ...

Converting counterup2 to pure vanilla JavaScript: step-by-step guide

Is there a way to convert the counterUp2 jQuery code to vanilla JavaScript? const counters = document.querySelectorAll('.counter'); function count(element) { let currentValue = 0; const targetValue = parseInt(element.innerText); let interv ...

Navigating Users and Routing with Ionic Framework (AngularJS)

Currently, I am using Ionic for a new project and could use some guidance with routing (I'm relatively new to Angular). These are the states I have defined: $stateProvider.state('map', { url: '/map', views: { map: ...

Click the button on your mobile device to open the already installed Android app

After creating a small Android app using jQuery Mobile, I incorporated a button to open another native Android app. Is it feasible for the jQuery Mobile app button to load/open an already installed and functioning native Android app upon click? I would gr ...

Modifying the autocomplete feature to showcase options in a dropdown menu

I have a form that requires country states to be displayed in a dropdown menu. Despite having autocomplete functionality, I am only able to see the response as an array in the console.log when searching for a specific state. I have tried to switch from aut ...