1

I've got post ajax request in vanilla javascript, all works well, but I need to add an variable to form_data, which will be send to php. For example variable apple = 1 is already in form_data. I need to add orange = 2, but I can't do it in my html form. My js code is below:

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);
   }

To sum up: I want to add orange=1 to form_data. Anyone knows how to do it? My primary intention was to add information which button was clicked to differentiate ajax functions in php. My HTML code is below:

 <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"/>
gileneusz
  • 1,435
  • 8
  • 30
  • 51

1 Answers1

3

Add it using append() function like:

//form_data.append(name, value);

form_data.append('orange',2);

Hope this helps.

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
  • Is appending form data, better practice than using hidden input fields? they seem to both do the exact same thing. Hidden Input Fields: https://stackoverflow.com/questions/7324950/whats-the-point-of-having-hidden-input-in-html-what-are-common-uses-for-this – Nick Timmer Oct 23 '17 at 16:28
  • That depend on the case.. If the value will be statically added or passed from server side – Zakaria Acharki Oct 23 '17 at 16:29
  • I used hidden input fields, but I cannot use them in this case. I've got a form, which has 3 buttons: "publish", "delete", "show", and I need to differentiate ajax action for each one in js functions – gileneusz Oct 23 '17 at 16:32
  • Add the HTML code to the question please and try to describe more which values you want to pass .. – Zakaria Acharki Oct 23 '17 at 16:35