Sending data using AJAX's XMLHttpRequest POST request

I've successfully used XMLHttpRequest in the past with the GET method, but I'm currently facing challenges trying to implement it using POST.

Here's the code snippet:

var req = null;
if (window.XMLHttpRequest)
{// for modern browsers like IE7+, Firefox, Chrome, Opera, Safari
    req = new XMLHttpRequest();
}
else
{// for old versions like IE6, IE5
    req = new ActiveXObject("Microsoft.XMLHTTP");
}

var url = "http://www.example.com/api.php";
var params = "data=someData";
req.open("POST", url, true);
req.send(params);

This code essentially triggers a PHP script which then inserts data into a database.

Answer №1

Don't forget to explicitly set the Content-type header when making POST requests.

xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

Remember to use encodeURIComponent to properly encode your parameters, for example:

var params = "var=" + encodeURIComponent("1");

In some cases, encoding may not be necessary, but using special characters like + without proper encoding can lead to issues.

Update – It's important to replace all occurrences of %20 with +, such as:

var params = params.replace(/%20/g, '+');

Answer №2

Success! I was able to resolve the issue.

It seems the problem could be related to sandbox security measures. Instead of using the full URL address, I simply utilized the relative path to the file, which resolved the issue successfully.

Thank you to everyone for your assistance.

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

What are some tips for using copy and paste with Protractor on a Mac using Chrome?

Is there a way to utilize copy and paste functionality with Protractor on a MAC using Chrome? newInput.sendKeys(protractor.Key.chord(browser.controlKey, "a")); newInput.sendKeys(protractor.Key.chord(browser.controlKey, "c")); newInput.sendKeys(protractor. ...

Once the hidden DIV is revealed, the Youtube video within it begins to load

I currently have a hidden DIV on my website that contains a YouTube clip. My goal is to load the video in the background once the page has fully loaded, so that it's ready to play when the user clicks the button to reveal the DIV. However, at the mo ...

Issue with carousel functionality being disrupted by resizing of the window

I have lined up a series of 3 divs floating to the left in a straight line, each spanning the width of the page. Here is an example of the HTML structure: <div class="Horizontal-Wrapper"> <div class="Horizontal-Section"> <div ...

JavaScript call to enlarge text upon click

I'm struggling to figure out why my font enlargement function isn't working as expected. Below is the code for my font enlargement function: <script type="text/javascript> function growText() { var text = document.getElementBy ...

Unexpected behavior with Ember.js Ajax request

I recently started using the Ember.js framework. While attempting to make an AJAX call from the framework, I encountered unexpected results. Below is the code snippet on the page - Link to the first AJAX call, which is functioning as intended. {{#linkT ...

Issue encountered post minification of AngularJS. Error message: [$injector:unpr] Provider "eProvider" is not recognized: e <- makeErrorsDirective

After using Gulp to minify all my js files, I encountered the following error: [$injector:unpr] Unknown provider: eProvider <- e <- makeErrorsDirective. Within my controller file, I had a custom directive. var myhubdashboardControllers = angular.m ...

Display all dates within a specific range using the indexOf method

I am working on creating a datepicker in vue3. As part of this, I want the days between two selected dates to be highlighted when hovered over. I have attempted to achieve this using the "indexOf" method, but unfortunately, I am not getting the desired res ...

Response not being retrieved from JSON following AJAX request

CODE SNIPPETS $("#submit_login").click(function() { var username = $('input[name=user_email]').val(); var password = $('input[name=user_password]').val(); $.ajax({ type: "POST", dataType: "json", u ...

What is the best approach to managing undefined properties retrieved from the html in my Angular application prior to obtaining data from my controller?

Every time my Angular component HTML renders, I encounter numerous errors that all look similar to this ERROR TypeError: Cannot read properties of undefined (reading 'someProperty') Throughout my HTML page, there are many bindings that follow ...

Browser hangs due to the success of ajax request

Whenever there is a change in the input, an ajax call is triggered and upon successful completion, around 80% of the content on the page gets modified. It seems that handling 2 to 3 request responses is okay, but after that, the browser hangs until the su ...

Issues with closing Foundation 6 off-canvas feature

Here is a link that I have: If you click on the skip button in the middle, it will take you to the next slide where Foundation 6 off-canvas is implemented. The header containing the toggle button for the off-canvas menu is located outside of the menu its ...

I'm noticing that the dropdown content for all my buttons is identical. What could be causing this

I have encountered an issue with the two buttons placed inside my header. Whenever I click on either button, the content displayed remains the same. https://i.sstatic.net/fk4V8.png https://i.sstatic.net/TCL7H.png It seems that when I click on one button, ...

Check if an array includes a specific value, and then either update it if found, or create it

I'm currently working with a Cart object in Javascript and I need to check if a specific item is present in the cart. Here's my approach: If the item is already in the cart, update its quantity. If it's not in the cart, add it to the items ...

Retrieve a Spring Bean for each Ajax request

I have a spring bean that contains three Maps, all of which need to be populated incrementally. The first Map is a project list The second Map is a team members list The third Map is a hobby for team member list All the maps are connected to <form:se ...

Searching with the LIKE operator in Moongose MongoDB allows for more flexible and powerful

Having reviewed some solutions for using the "LIKE" operator in Mongoose: Mongoose.js: Find user by username LIKE value How to query MongoDB with "like"? Mongodb dynamic like operator I have implemented this code snippet to replicate "SQL LIK ...

Halt the execution of a function upon clicking a div element

I'm currently working on a function that needs to be stopped when a div with the class "ego" is clicked. This function toggles the visibility of the header based on the scroll position and should only run by default. Below is the code snippet: $("#e ...

What is the best way to restrict the selection of specific days of the week on an HTML form date input using a combination of JavaScript, React, and HTML?

I need help customizing my Forms Date Input to only allow selection of Thursdays, Fridays, and Saturdays. I've searched for a solution but haven't been successful so far. Is there any JavaScript or HTML code that can help me achieve this? Below ...

Is it advisable to employ multiple websocket connections for achieving parallel communication?

Imagine one person is in charge of managing a substantial amount of chart data. Meanwhile, another individual is responsible for updating user information. Is this arrangement suitable? I am uncertain how the concept of JavaScript being single-threaded w ...

Using ANT to swap out values in JavaScript code

My HTML page includes a <script> tag with the following code: <script type="text/javascript"> window.location ="THIRD PARTY URL" </script> The code above functions correctly. Now, I need to change the value of the Third Party URL f ...

What is the best way to divide my value sets using jQuery?

Within a given string such as 28_34/42/34,23_21/67/12,63_5/6/56, I am seeking to split or eliminate sets based on the ID provided. For example, if the ID is 23, then the set 23_21/67/12 should be removed. To achieve this, I am checking the value after the ...