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"/>