Skip to content

Instantly share code, notes, and snippets.

@fliedonion
Last active October 9, 2015 03:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fliedonion/bedb5d85042e9379d72b to your computer and use it in GitHub Desktop.
Save fliedonion/bedb5d85042e9379d72b to your computer and use it in GitHub Desktop.
jQuery-$ajax-sample
Summary jQuery $ajax sample or snippet
Env jQuery

What is this GIST.

This is jQuery $ajax basic usage sample.

Run server to process this sample's ajax requests.

$ node server.js

Open index.html in your brower, and press the buttons. You can find text changing in div#printArea.

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="printArea">press button, display return value here.</div>
<br/>
<button id="postData">post</button>
<br/>
<button id="getData">get</button>
<br/>
<script src="bower_components/jquery/dist/jquery.min.js"></script>
<!--
"dependencies": {
"jquery": "~2.1.4"
}
-->
<script>
function handleError(response){
console.log(response);
alert("error: " + response.status);
}
$(function(){
$('#getData').click(function(){
console.log('getData pressed');
$.ajax({
url: 'http://localhost:3000/get-req',
type: 'get',
dataType: 'json',
data: { id: "get" }
}).then(function success(response){
$('#printArea').text(response.sent);
}, handleError);
});
$('#postData').click(function(){
console.log('postData pressed');
$.ajax({
url: 'http://localhost:3000/post-req',
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ id: "post" })
}).then(function success(response){
$('#printArea').text(response.sent);
}, handleError);
});
})
</script>
</body>
</html>
// "dependencies": {
// "cors": "^2.7.1",
// "body-parser": "^1.14.1",
// "express": "^4.13.3"
// },
// "devDependencies": {
// "nodemon": "^1.7.1"
// },
var express = require('express');
var cors = require('cors');
var bodyParser = require('body-parser');
var app = new express();
app.use(cors());
app.use(bodyParser.json());
app.get('/get-req', function(req, res){
res.json({ret: "get request", sent: req.query.id });
});
app.post('/post-req', function(req, res){
res.json({ret: "post request", sent: req.body.id});
});
app.listen(3000, function(){
console.log('server running on localhost:3000')
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment