Skip to content

Instantly share code, notes, and snippets.

@ErikPeterson
Last active August 29, 2015 14:07
Show Gist options
  • Save ErikPeterson/cfdbec9ebdbcea1f0f5c to your computer and use it in GitHub Desktop.
Save ErikPeterson/cfdbec9ebdbcea1f0f5c to your computer and use it in GitHub Desktop.
Simple ajax form submit
//right inside of your window.onload function
var formButton = document.querySelector('the_id_of_your_forms_button_here');
formButton.addEventListener('click', function(e){
//stop form from submitting through the browser the default way
e.preventDefault();
var name = document.querySelector('id_of_the_name_field').value;
var address = document.querySelector('id_of_the_address_field').value;
//and so on until you've gotten all the values from the form
var newLi = document.createElement('LI');
//do what you did in your loop before to add the right elements and information to the new li
var list = document.querySelector('id_of_the_list');
list.appendChild(newLi);
//send data to server with POST
var req = new XMLHttpRequest();
req.open("post", '/contacts', true);
req.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
req.send(JSON.stringify({name: name,
addres: adress //and so on
}));
//clear out the form here
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment