Email address string loses the '+"' when using AJAX

My ajax code has been working well in most cases, but when I tried using it for updating user details on my page, I noticed that the ""+"" symbol was getting lost if used in an email address (such as

<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f98d9c8a8dd28d9c8a8db98d9c8a8dd79a9694">[email protected]</a>
showing up as
test <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="394d5c4a4d794d5c4a4d175a5654">[email protected]</a>
in my PHP file.

function prefUpdate() {
    let ytTog = document.getElementById("togBtn").checked;
    let unameNew = document.getElementById("uname").value;
    let usnameNew = document.getElementById("usname").value;
    let emailNew = document.getElementById("email").value;
    let params = "ytTog="+ytTog+"&unameNew="+unameNew+"&usnameNew="+usnameNew+"&emailNew="+emailNew;
    let xhr = new XMLHttpRequest();
    xhr.open('POST', 'pref_update.php', true);
    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
    xhr.onreadystatechange = function() {
        if(xhr.readyState == 4 && xhr.status == 200) {
            let return_data = xhr.responseText;
            if(return_data) {
               <do stuff>
            }
        }
    }
    xhr.send(params);
}

Essentially, I am fetching a button, first and last name, along with the email address, passing them to a php file which returns some data for further processing.

I suspect that the issue might be with the

'application/x-www-form-urlencoded'
, but my searches haven't provided me with a solution yet.

[edit] I did try replacing

application/x-www-form-urlencoded
with multipart/form-data, but that ended up breaking things completely.

Answer №1

To ensure secure data transmission during an ajax call, it is essential to encode your data correctly. Utilizing a URLSearchParams object can simplify this process for you.

let params = new URLSearchParams({username, password, email});
...
xhr.send(params);

Answer №2

Correct, when using Content-Type: application/x-www-form-urlencoded, any '+' symbols represent spaces. To properly encode these, utilize the function encodeURIComponent().

let params = Object.entries({ username, password, email })
  .map(pair => pair.map(encodeURIComponent).join('='))
  .join('&');

Referencing the MDN documentation:

For application/x-www-form-urlencoded, it is necessary to replace spaces with + signs, so it may be helpful to perform an additional replacement of %20 with + after using encodeURIComponent().

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 organizing JSON information in ReactJS

Could someone lend a hand with sorting JSON data in ReactJs? I'm having trouble getting it to work properly. Also, if I want to sort by title, would it be the same process? Thanks! This is what I've tried so far: componentDidMount() { ...

Using Ajax (Jquery) to send data to a PHP script

Currently, I am working on an application where users can click a checkmark to complete a task. When this action is taken, a popup window appears (created using bootstrap), prompting the user to enter their hours worked on the task. After entering the hour ...

I'm having trouble using Discord.js to set up a custom role with specialized permissions for muting users

module.exports = { name: "mute", description: "This command is used to mute members in a server", execute: async function (msg, arg) { const muteRole = await msg.guild.roles.cache.find((r) => r.name == "Mute ...

The state variables of React components do not always retain their most recent value

Currently, I am working on implementing the functionality of an event based library called powerbi-client-react. The first step involves retrieving the component using getEmbeddedComponent and storing it in the variable report. Then, I need to utilize the ...

Creating visualizations by overlaying shapes onto images using specified coordinates in jQuery

I have a web application in development that integrates with the skybiometry API. Their demo showcases a fantastic user feedback system displayed after facial recognition, similar to the one shown below. I am currently working on implementing a similar fe ...

Combining FusionCharts with PHP and Ajax

Currently making use of FusionCharts Free to display some data in a chart. In the main.php: <html> <head> <script language="JavaScript" src="FusionCharts/FusionCharts.js" ></script> <script ...

Using Unicode JSON in Laravel blade to pass data to React components, encountering an issue with JSON parsing

I currently have a JSON object stored in the database: { "ui": {}, "title": "Hola mundo 2", "values": {}, "properties": {}, "description": "descripcion" } Within the Laravel controller, ...

How to change the focus on a Material UI input field

I am facing an issue with resetting/clearing an input field using a button click: Take a look at the code here for reference. const searchInput = useRef(null); const clearInput = () => { searchInput.current.value = ''; searchInput ...

"Troubleshooting: Why is the onError event not triggering

Has anyone else experienced issues with using a third-party API to fetch YouTube thumbnails with higher resolution, sometimes resulting in a code 404 error? I've been trying to replace the image source with a default YouTube thumbnail retrieved from i ...

php utilizing ajax for handling multiple data requests

I'm encountering an issue with fetching multiple data using ajax. Whenever I try to increase the quantity of items in my cart, it crashes. It works fine with a single data parameter, but when I attempt to use multiple parameters, I get strange large ...

Unique alphanumeric code following the inclusion of a JavaScript file

I'm encountering an issue with a webpage that incorporates two JavaScript files. When inspecting it using firebug, I noticed that every time the page loads, these two files are included with the prefix ?_=someRandomNumber I'm unsure about the or ...

Randomly, an AJAX request sent from Internet Explorer 11 to a node.js server operating behind an Apache proxy may abruptly terminate

When using angular on a webpage, a get request is initiated to retrieve json data after a user action. The issue arises when attempting this request on Internet Explorer 11, as it fails randomly while working smoothly on Firefox. Below is a screenshot of t ...

Tips for effectively utilizing MeteorPad: (Note: ensure to use at home instead of at work due to potential firewall or proxy issues)

UPDATE: It's possible that the issue is related to a firewall or proxy. MeteorPad doesn't work at my workplace, but it works fine at home. I've been attempting to use MeteorPad () but I'm encountering some difficulties. The bottom are ...

Implementing a Javascript solution to eliminate the # from a URL for seamless operation without #

I am currently using the pagepiling jQuery plugin for sliding pages with anchors and it is functioning perfectly. However, I would like to have it run without displaying the '#' in the URL when clicking on a link like this: www.mysite.com/#aboutm ...

What is the best way to apply a mask to a textbox to format the date as MM/yyyy using a mask

In my asp.net application, I have a TextBox for entering Credit card date (month & year only). I tried using the 'TextBox with masked edit extender' and set Mask="99/9999" with Mask Type="Date. However, it is not working as expected - it only wor ...

The total height of an HTML element, which takes into account the margin of the element itself

Is there a way to accurately calculate the height of an element including margins, even when dealing with child elements that have larger margins than their parents? HTMLElement.offsetHeight provides the height excluding margin, while this function from ...

Tips for extracting HTML entities from a string without altering the HTML tags

I need assistance with removing HTML tags from a string while preserving html entities like &nbps; & é < etc.. Currently, I am using the following method: stringWithTag = "<i> I want to keep my ->&nbsp;<- element space, bu ...

Is it possible to determine if a selected date falls within the current week using JavaScript?

Currently facing an issue with JavaScript. I have multiple dates retrieved from a database, and I need to extract the date that falls within the current week. ...

Adding a unique key to every element within a JavaScript array

I am working with the array provided below which contains simple values. My goal is to add a key id before each value in the array, resulting in something like this: ["id:a", "id:b","id:c","id:d"]. Is there an easy way to achieve this? Any assistance would ...

Strategies for re-rendering a React component when the useState value remains the same or retains its previous value

I am currently using a useState hook to store the value of selectFolderId: const [selectFolderId, useSelectFolderId] = React.useState(documentStore.id) Despite trying to update selectFolderId with the new value from DocumentStore by using a useEffect hook ...