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

1 Answer 1

3

Add it using append() function like:

//form_data.append(name, value);

form_data.append('orange',2);

Hope this helps.

Sign up to request clarification or add additional context in comments.

4 Comments

Is appending form data, better practice than using hidden input fields? they seem to both do the exact same thing. Hidden Input Fields: stackoverflow.com/questions/7324950/…
That depend on the case.. If the value will be statically added or passed from server side
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
Add the HTML code to the question please and try to describe more which values you want to pass ..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.