Skip to content

Instantly share code, notes, and snippets.

@vickonrails
Last active February 4, 2018 22:39
Show Gist options
  • Save vickonrails/5a2b1bba319b1e84743018835c8c88c1 to your computer and use it in GitHub Desktop.
Save vickonrails/5a2b1bba319b1e84743018835c8c88c1 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<meta charset='UTF-8'>
<title>Form page</title>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js'></script>
<style>
*{
margin:0;
padding:0;
box-sizing: border-box;
font-size: 20px;
}
input{
margin:20px;
padding:10px;
}
input[type=”text”],
textarea {
width:200px;
margin:20px;
padding:5px;
height:30px;
display: block;
}
textarea{
resize:none;
height:60px;
}
</style>
</head>
<body>
<div></div>
<form action='/' method='POST'>
<input type='text' name='name' placeholder='name'/>
<textarea name='message' placeholder='message'></textarea>
<input type='submit'/>
</form>
<script>
$('form').on('submit',makeRequest);
function makeRequest(e){
e.preventDefault();
$.ajax({
url:'/',
type : 'POST',
success: function(data){
if(data.message){
$('div').html(data.message);
} else {
$('div').html('Sorry, an error occured');
}
},
error: function(){
$('div').html('Sorry, an error occurred');
}
});
}
</script>
</body>
</html>
//server.js
const express = require('express'),
app = express(),
bodyParser = require('body-parser');
//configuring the body-parser middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
//setting our app port
app.set('port', process.env.PORT || 3000);
//Route for get requests.
app.get('/',(request,response)=>{
response.sendFile(__dirname +'/form.html');
});
//Route to handle POST form requests.
app.post('/',(request,response)=>{
//we check if the request is an AJAX one and if accepts JSON
if(request.xhr || request.accepts('json, html')==='json'){
response.send({message:'Just wanted to tell you. It worked'});
} else {
//Do something else by reloading the page.
}
});
app.listen(3000,()=>{
console.log('Express server started at port 3000');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment