Simple ajax form using javascript no jQuery
Asked Answered
W

9

25

I'm working with a form for which the mark-up I can't change & can't use jQuery. Currently the form post the results to a new window. Is it possible to change this to an ajax form so that the results displays on submit instead without altering any mark-up? Pulling the results (mark-up) from the results page back to the form page.

Here is the mark-up for the form.

<form class="form-poll" id="poll-1225962377536" action="/cs/Satellite" target="_blank">
<div class="form-item">
    <fieldset class="form-radio-group">
        <legend><span class="legend-text">What mobile phone is the best?</span></legend>
                <div class="form-radio-item">
                    <input type="radio" class="radio" value="1225962377541" name="option" id="form-item-1225962377541">
                    <label class="radio" for="form-item-1225962377541">
                        <span class="label-text">iPhone</span>
                    </label>
                </div><!-- // .form-radio-item -->
                <div class="form-radio-item">
                    <input type="radio" class="radio" value="1225962377542" name="option" id="form-item-1225962377542">
                    <label class="radio" for="form-item-1225962377542">
                        <span class="label-text">Android</span>
                    </label>
                </div><!-- // .form-radio-item -->
                <div class="form-radio-item">
                    <input type="radio" class="radio" value="1225962377543" name="option" id="form-item-1225962377543">
                    <label class="radio" for="form-item-1225962377543">
                        <span class="label-text">Symbian</span>
                    </label>
                </div><!-- // .form-radio-item -->
                <div class="form-radio-item">
                    <input type="radio" class="radio" value="1225962377544" name="option" id="form-item-1225962377544">
                    <label class="radio" for="form-item-1225962377544">
                        <span class="label-text">Other</span>
                    </label>
                </div><!-- // .form-radio-item -->
    </fieldset>
</div><!-- // .form-item -->
<div class="form-item form-item-submit">
    <button class="button-submit" type="submit"><span>Vote now</span></button>
</div><!-- // .form-item -->
<input type="hidden" name="c" value="News_Poll">
<input type="hidden" class="pollId" name="cid" value="1225962377536">
<input type="hidden" name="pagename" value="Foundation/News_Poll/saveResult">
<input type="hidden" name="site" value="themouth">

Any tips/tutorial is much appreciated. :)

Widgeon answered 9/8, 2011 at 2:14 Comment(0)
C
21

The following is a far more elegant solution of the other answer, more fit for modern browsers.

My reasoning is that if you need support for older browser you already most likely use a library like jQuery, and thus making this question pointless.

/**
 * Takes a form node and sends it over AJAX.
 * @param {HTMLFormElement} form - Form node to send
 * @param {function} callback - Function to handle onload. 
 *                              this variable will be bound correctly.
 */

function ajaxPost (form, callback) {
    var url = form.action,
        xhr = new XMLHttpRequest();

    //This is a bit tricky, [].fn.call(form.elements, ...) allows us to call .fn
    //on the form's elements, even though it's not an array. Effectively
    //Filtering all of the fields on the form
    var params = [].filter.call(form.elements, function(el) {
        //Allow only elements that don't have the 'checked' property
        //Or those who have it, and it's checked for them.
        return typeof(el.checked) === 'undefined' || el.checked;
        //Practically, filter out checkboxes/radios which aren't checekd.
    })
    .filter(function(el) { return !!el.name; }) //Nameless elements die.
    .filter(function(el) { return el.disabled; }) //Disabled elements die.
    .map(function(el) {
        //Map each field into a name=value string, make sure to properly escape!
        return encodeURIComponent(el.name) + '=' + encodeURIComponent(el.value);
    }).join('&'); //Then join all the strings by &

    xhr.open("POST", url);
    // Changed from application/x-form-urlencoded to application/x-form-urlencoded
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

    //.bind ensures that this inside of the function is the XHR object.
    xhr.onload = callback.bind(xhr); 

    //All preperations are clear, send the request!
    xhr.send(params);
}

The above is supported in all major browsers, and IE9 and above.

Clodhopping answered 24/10, 2014 at 21:12 Comment(5)
Some people can't use jQuery for performance reasons, the question isn't pointless.Snath
That should be "application/x-www-form-urlencoded", not "application/x-form-urlencoded". Found this problem because my servers CORS implementation rejected it based on this header. Additionally, params seems to be coming up blank for some reason, but I haven't debugged that.Jocelin
@Jocelin feel free to edit, or wait for me to do it later todayAlphard
Shouldn't it be !el.disabled?Quinquereme
Yes, There is a typo in this. It should be !el.disabled. This code wasn't passing on the csrfmiddlewaretoken in my form either.. Needs tweaks.Macknair
E
14

Here's a nifty function I use to do exactly what you're trying to do:

HTML:

<form action="/cs/Satellite">...</form>
<input type="button" value="Vote now" onclick="javascript:AJAXPost(this)">

JS:

function AJAXPost(myself) {
    var elem   = myself.form.elements;
    var url    = myself.form.action;    
    var params = "";
    var value;

    for (var i = 0; i < elem.length; i++) {
        if (elem[i].tagName == "SELECT") {
            value = elem[i].options[elem[i].selectedIndex].value;
        } else {
            value = elem[i].value;                
        }
        params += elem[i].name + "=" + encodeURIComponent(value) + "&";
    }

    if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    } else { 
        // code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.open("POST",url,false);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.setRequestHeader("Content-length", params.length);
    xmlhttp.setRequestHeader("Connection", "close");
    xmlhttp.send(params);

    return xmlhttp.responseText;
}
E answered 9/8, 2011 at 3:34 Comment(6)
.elements returns only input nodes for FORM?Kwh
Yes the .elements of a form object return only input nodesEcumenism
This solution will send unchecked radio buttons and checkboxes.Alphard
@AlainBeauvois— element returns all controls in the form, not just inputs.Starknaked
@E sorry I can't make it work. Can you expand the form example? Are they valid this in the onClick and the myself in the function? Sorry I'm not strong with js. this looks referred to the button itselfIrremissible
@Irremissible Try putting alert(params); after the for loop. That will tell you what your params are. this is the button, but myself.form is the form, myself.form.elements is all the elements of the form for the button. elem may include all HTML tags, so you might want to filter to inputs.E
D
9

Nowadays using FormData is the easiest method. You construct it with a reference to the Form element, and it serializes everything for you.

MDN has an example of this here -- roughly:

const form = document.querySelector("#debarcode-form");
form.addEventListener("submit", e => {
    e.preventDefault();
    const fd = new FormData(form);
    const xhr = new XMLHttpRequest();
    xhr.addEventListener("load", e => {
        console.log(e.target.responseText);
    });
    xhr.addEventListener("error", e => {
        console.log(e);
    });
    xhr.open("POST", form.action);
    xhr.send(fd);
});

and if you want it as an object (JSON):

const obj = {};
[...fd.entries()].forEach(entry => obj[entry[0]] = entry[1]);
Dap answered 1/3, 2018 at 22:53 Comment(0)
S
3

Expanding on Madara's answer: I had to make some changes to make it work on Chrome 47.0.2526.80 (not tested on anything else). Hopefully this can save someone some time.

This snippet is a modification of that answer with the following changes:

  • filter !el.disabled,
  • check type of input before excluding !checked
  • Request type to x-www-form-urlencoded

With the following result:

function ajaxSubmit(form, callback) {
    var xhr = new XMLHttpRequest();
    var params = [].filter.call(form.elements, function (el) {return !(el.type in ['checkbox', 'radio']) || el.checked;})
    .filter(function(el) { return !!el.name; }) //Nameless elements die.
    .filter(function(el) { return !el.disabled; }) //Disabled elements die.
    .map(function(el) {
        return encodeURIComponent(el.name) + '=' + encodeURIComponent(el.value);
    }).join('&'); //Then join all the strings by &
    xhr.open("POST", form.action);
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.onload = callback.bind(xhr);
    xhr.send(params);
};
Scarecrow answered 15/12, 2015 at 18:13 Comment(2)
Thanks, this worked. I found the x-www problem but not the other two. There's a strange "·" character at the end of this line by the way: "xhr.onload = callback.bind(xhr);·".Jocelin
I love this answer. My only problem with it is that it does not get if a check mark is checked or not and no doubt it will have the same problem with radio. See my answer below for edited version of yours that solves the check mark part of it.Krueger
S
2

The strategy is to serialise the form and send the data using XHR, then do what you want with the response. There is a good set of utilities and help at Matt Krus's Ajax Toolbox and related Javascript Toolbox.

If you are just serialising the form posted, then the following will do the trick. It can easily be extended to include other form control types:

var serialiseForm = (function() {

  // Checkboxes that have already been dealt with
  var cbNames;

  // Return the value of a checkbox group if any are checked
  // Otherwise return empty string
  function getCheckboxValue(cb) {
    var buttons = cb.form[cb.name];
    if (buttons.length) {
      for (var i=0, iLen=buttons.length; i<iLen; i++) {
        if (buttons[i].checked) {
          return buttons[i].value;
        }
      }
    } else {
      if (buttons.checked) {
        return buttons.value;
      }
    }
    return '';
  }

  return function (form) {
    var element, elements = form.elements;
    var result = [];
    var type;
    var value = '';
    cbNames = {};

    for (var i=0, iLen=elements.length; i<iLen; i++) {
      element = elements[i];
      type = element.type;

      // Only named, enabled controls are successful
      // Only get radio buttons once
      if (element.name && !element.disabled && !(element.name in cbNames)) {

         if (type == 'text' || type == 'hidden') {
          value = element.value;

        } else if (type == 'radio') {
          cbNames[element.name] = element.name;
          value = getCheckboxValue(element);

        }
      }

      if (value) {
        result.push(element.name + '=' + encodeURIComponent(value));
      }
      value = '';

    }
    return '?' + result.join('&');
  }
}());
Starknaked answered 9/8, 2011 at 2:50 Comment(0)
A
2

A modern way using fetch would be:

const formData = new FormData(form);
fetch(form.action, {
  method: 'POST',
  body: formData
});

Note browser support and use this polyfil if IE-support is needed

Actinomycin answered 26/3, 2020 at 7:52 Comment(2)
Are you sure that you don't need the content-type that other suggest? That's what I'm doing in my fetch-based npm moduleCommonplace
Probably depends on the server side parsing. I cannot find a default value definition for content-type in the draft. So it is probably better to explicitly set it.Actinomycin
K
0
function ajaxSubmit(form, callback) {
var xhr = new XMLHttpRequest();
var params = [].filter.call(form.elements, function (el) {return !(el.type in ['checkbox', 'radio']) || el.checked;})
.filter(function(el) { return !!el.name; }) //Nameless elements die.
.filter(function(el) { return !el.disabled; }) //Disabled elements die.
.map(function(el) {
    if (el.type=='checkbox') return encodeURIComponent(el.name) + '=' + encodeURIComponent(el.checked);
   else return encodeURIComponent(el.name) + '=' + encodeURIComponent(el.value);
}).join('&'); //Then join all the strings by &
xhr.open("POST", form.action);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onload = callback.bind(xhr);
xhr.send(params);

};

Krueger answered 17/4, 2016 at 9:6 Comment(0)
K
0

I just took Coomie's answer above and made it work for Radio/Checkboxes. I can't believe how simple and clear this is. With a few exceptions, I'm done using frameworks.

    var params = "";
    var form_elements = form.elements;
    for (var i = 0; i < form_elements.length; i++) 
    {
        switch(form_elements[i].type)
        {
            case "select-one":
            {
                value = form_elements[i].options[form_elements[i].selectedIndex].value;
            }break;
            case "checkbox":
            case "radio": 
            {
                if (!form_elements[i].checked)
                {
                    continue; // we don't want unchecked data
                }
                value = form_elements[i].value;
            }break;
            case "text" :
            {
                value = form_elements[i].value;                
            }break;

        }

        params += encodeURIComponent(form_elements[i].name) + "=" + encodeURIComponent(value) + "&";
    }



    var xhr = new XMLHttpRequest();    
    xhr.open('POST', "/api/some_url");
    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            if (xhr.status == 200)
            {

                console.log("xhr.responseText");
            }
            else
            {
                console.log("Error! Status: ", xhr.status, "Text:", xhr.responseText);
            } 
        }
    };

    console.log(params);
    xhr.send(params);
Kassala answered 8/8, 2017 at 15:54 Comment(0)
K
-1

Here's the simplest method I came up with. I haven't found an example that uses this exact approach. The code submits the form using a non-submit type button and places the results into a div, if the form is not valid (not all required fields filled), it will ignore the submit action and the browser itself will show which fields are not filled correctly.

This code only works on modern browsers supporting the "FormData" object.

<script>
function ajaxSubmitForm() {
  const form = document.getElementById( "MyForm" );
  if (form.reportValidity()) {
    const FD = new FormData( form );
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("content_area").innerHTML = this.responseText; } };
    xhttp.open("POST","https://example.com/whatever.php",true);
    xhttp.send( FD );
  }
}
</script>

<div id="content_area">
<form id="MyForm">
  <input type="hidden" name="Token" Value="abcdefg">
  <input type="text" name="UserName" Value="John Smith" required>
  <input type="file" accept="image/jpeg" id="image_uploads" name="ImageUpload" required>
  <button type="button" onclick="ajaxSubmitForm()">
</form>
</div>
Kultur answered 28/5, 2020 at 11:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.