I am running a node server that has no data on it. I want to push data up to the server and then take it down again on a button click.I've tried following other examples but I'm quite new to ajax requests and I want to understand the code that I'm writing this is what I have so far:
***script.js(Client file)***
$(document).ready(function() {
$.ajax({
url: 'http://localhost:8080',
dataType: "jsonp",
data: '{"data": "TEST"}',
type: 'POST',
jsonpCallback: 'callback',
success: function (data) {
var ret = jQuery.parseJSON(data);
console.log(data)
console.log('Success: ')
},
error: function (xhr, status, error) {
console.log('Error: ' + error.message);
},
});
$('#button').click(function(){
$.ajax({
url: 'http://localhost:8080',
dataType: "jsonp",
type: 'GET',
jsonpCallback: "callback",
success: function (data) {
var ret = jQuery.parseJSON(data);
console.log(data)
console.log('Success: Kick Ass!')
},
error: function (xhr, status, error) {
console.log('SOMETHING HAS GONE WRONG :(');
},
});
});
});
***Index.js(Server File)***
var http = require('http');
var util = require('util')
http.createServer(function (req, res) {
console.log('Request received: ');
util.log(util.inspect(req)) // this line helps you inspect the request so you can see whether the data is in the url (GET) or the req body (POST)
util.log('Request recieved:
method: ' + req.method + '
url: ' + req.url) // this line logs just the method and url
res.writeHead(200, { 'Content-Type': 'text/plain' });
req.on('data', function (chunk) {
console.log('GOT DATA!');
});
res.end('callback(\'{\"msg\": \"OK\"}\')');
}).listen(8080);
console.log('Server running on port 8080');
Please help. Thanks so much!