Enhancing ajax post requests made with vanilla javascript by incorporating variables

I have successfully implemented a post ajax request in vanilla Javascript, but I am facing an issue. I need to include a variable in form_data that will be sent to PHP. For instance, the variable apple = 1 is already part of form_data. Now, I also want to add orange = 2, but I cannot achieve this through my HTML form. Below is my Javascript code:

function button_publish_ajax(variable){
    var form = document.getElementById("form-buttons");
    var form_data = new FormData(form);
        for ([key,value] of form_data.entries()){
        console.log(key + ': '+value);
        }
    var action = form.getAttribute("action");                   
    var xhr = new XMLHttpRequest();
    xhr.open('POST', action, true);
    xhr.overrideMimeType('text/xml; charset=UTF-8');
    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    xhr.onreadystatechange = function (){
    if (xhr.readyState == 4 && xhr.status == 200){
        var result = xhr.responseText;
        console.log("Result:" + result);
    }
    };
    xhr.send(form_data);
   }

In summary, I need to append orange=1 to form_data. Can anyone guide me on how to accomplish this? My main goal is to specify which button was clicked in order to differentiate between ajax functions in PHP. Here's my HTML code:

 <form method="post" action="cms_offers_button.php" id="form-buttons">
  <input type="hidden" name="offer_list" value="12">
    <input name="PublishListItem" type="button" class="btn btn-info offer-publish" value="Publish" id="publish-12" style="display: none;"/>
    <input name="WithdrawListItem" type="button" class="btn btn-info offer-withdraw" value="Withdraw" id="withdraw-12"/>
    <input name="EditListItem" type="button" class="btn btn-default offer-edit" value="Edit" id="edit-12" />
    <input name="DeleteListItem" type="button" class="btn btn-danger offer-delete" value="Delete" id="delete-12"/>

Answer №1

To include it, utilize the append() method in this manner:

// Add data with form_data.append(name, value);

form_data.append('apple', 3);

Trust this guidance is beneficial.

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 could be causing my Discord bot to remain offline even when I run the command node main.js?

After successfully installing node.js, I proceeded to type the command 'npm init' in the command prompt and then installed discord.js. However, upon installation of discord.js, a 'node_modules' folder was not added inside the project, w ...

Troubleshooting: Issues with Jquery's has, find, contains functions

As I check whether an element contains another element, I've previously utilized the jquery element.has(secondElement) function. In my angularjs project, I make use of jquery within a directive where I transclude elements through markup using ng-tran ...

Creating an Ajax request in Angular using ES6 and Babel JS

I have been exploring a framework called angular-webpack-seed, which includes webpack and ES2016. I am trying to make a simple AJAX call using Angular in the traditional way, but for some reason, it is not working. export default class HomeController { ...

Use jQuery to display the user input value in real-time

I am in the process of developing a dynamic calculation program to sharpen my jQuery skills, but unfortunately, I'm facing some challenges. I have managed to store values in variables as shown in the code snippet below. <form> Table of: ...

Invoke the onload event from document.ready using jQuery

Is it possible to trigger the onload event from within jQuery's document.ready function, such as in the example below: $(function() { onloadfunc(param); }); Comparison: <body onload = "onloadfunc(param);"> Do the above two methods achieve th ...

Encountering a DiscordAPIError[10062] when attempting to retrieve user points from the database due to an unknown interaction

content: "Congratulations, you have been successfully verified!", ephemeral: true, }); } } else if (interaction.customId === "giverole") { const userPoints = await findUser(interaction.member ...

Middleware GPS server - store location and transmit information to the server

After encountering a roadblock with my chosen GPS tracker service not supporting iframe plugins to share my car's position on my website, I've come up with the idea of creating a middleware server. The plan is to gather data from my GPS device, s ...

Pass data from controller using Ajax in CodeIgniter

Here is my JavaScript code: $(document).ready(function(){ $("input[type='checkbox']").change(function(){ var menu_id = this.value; if(this.checked) var statusvalue = "On"; else var statusvalue = "Off"; $.ajax( ...

Having trouble shutting down Metro Bundler on Windows?

While working on my React Native development, I regularly use npm start to get things going. However, I've run into an issue recently when trying to stop the process using Ctrl + c. It seems like I can no longer use npm start smoothly: ERROR Metro ...

Integrate actual credentials into S3Client using redux async thunk

My S3-like react application with redux is powered by AWS SDK v3 for JS. The client initialization in my auth.js file looks like this: auth.js export const s3Client = new S3Client({ region: 'default', credentials: { accessKeyId: 'te ...

Submitting a POST request using a Chrome Extension

I am in the process of developing a Chrome extension popup for logging into my server. The popup contains a simple form with fields for username, password, and a submit button. <form> <div class="form-group"> <label for="exampleInputE ...

Sinon causing 'unsafe-eval' error in Chrome extension unit tests

Recently, I've been conducting unit tests on my Chrome extension using Mocha, Chai, and Sinon. However, I encountered an issue when attempting to stub an object from a method: EvalError: Refused to evaluate a string as JavaScript because 'unsafe ...

JavaScript may encounter undefined JSON data after receiving a response from the server

I am facing an issue with my PHP script that is supposed to receive a JSON array. Here is the code I am using: $(function() { $("img").click(function() { auswahl = $( this ).attr("id"); $.get('mail_filebrowser_add2.php?datenID=' + aus ...

Testing React Hook Form always returns false for the "isValid" property

When creating a registration modal screen, I encountered an issue with the isValid value when submitting the form. In my local environment (launched by npm start), the isValid value functions correctly without any issues. However, during unit testing us ...

Angular 2 doesn't reflect changes in component variables in the view until mouseover happens

Since updating from angular2-alpha to the latest version, I've noticed that when a boolean value changes in my *ngIf directive, it doesn't reflect in the view until certain actions are taken. Here is the specific component code: declare var CKE ...

The function is not specified

Currently, I am in the process of implementing a login system using nodejs. My goal is to define a global function outside of a module and then call it multiple times within the module. However, I am encountering an issue where it always returns undefined, ...

Performing a Javascript validation to ensure that a value falls within

How can I check if an input number falls within a specified range? I need to display if it is within the range, higher, or lower than the acceptable range. My current Javascript code seems to be causing an error message stating it is an invalid entry. It ...

Empty Ajax array sent to PHP

I am encountering an issue with my ajax form where the values in an array are coming out as null in my PHP response. I suspect that there may be a mistake in my .ajax call. Can anyone provide suggestions or insights on how to resolve this issue? My code sn ...

Exploring the Significance of jQuery in a Real-

I manage a large website with an extensive amount of jQuery code spread across multiple pages. The total codebase is around 1000 lines, well-optimized and excluding plugins. Despite jQuery being efficient in ignoring listeners for non-existent page elemen ...

The ng-click method on the checkbox input field in AngularJS is not being triggered

I'm trying to trigger a function in a toggle switch using ng-click, but the customerActiveDeactive function isn't being executed. <a title="Active/ Deactivate" > <input type="checkbox" class="js-switch" ng-init="status=True" ng-model ...