- CORS requires that the server that responds to an ajax request, must first have served the html file making the request.
- Ajax POSTs are not idempotent
- The browser will automatically call for a favicon
- CORS requires that the server that responds to an ajax request, must first have served the html file making the request.
- Ajax POSTs are idempotent
- The browser will automatically call for a favicon
- CORS requires that the server that responds to an ajax request, must first have served the html file making the request.
- Ajax POSTs are not idempotent
- The browser will automatically call for a favicon
'use strict';
const host = 'localhost';
const http = require('http'); // VSCode shows 3 dots under "require" and says something about NodeRequire???
const fs = require('fs').promises;
const port = 8000;
const requestListener = function (req, res) {
switch (req.url) {
case "/test_ajax_post_json_sans_form.html": // serve an intial html file
fs.readFile(__dirname + '/test_ajax_post_json_sans_form.html')
.then(contents => {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(contents);
})
.catch(err => {
res.writeHead(500);
res.end(err);
return;
});
break
case '/test_ajax_post_json_sans_form.html/ajaxTest1': // receive json, process, then return other json
let body = '';
req.on('data', (data) => {
body += data;
});
req.on('end', () => {
console.log(body); // to show all data has arrived
// here we will check or errors, create a complex return-object, stringify it, and send it back
const objToReturn = {data1: 'Test message from server', data2: 'could be a complex json object'};
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(objToReturn));
});
break
case '/favicon.ico':
// browser will call favicon automatically. This satisfies the request (though its failing
// won't keep the ajax from working).
fs.readFile(__dirname + '/favicon.ico')
.then(contents => {
res.writeHead(200, {'Content-Type': 'image/x-icon'});
res.end(contents);
})
.catch(err => { // lacking favicon will not impact test
res.writeHead(200, {'Content-Type': 'image/x-icon'});
res.end();
});
break
default:
res.writeHead(404);
res.end(JSON.stringify({error:'Resource not found'})); // in production, might load a not-found page here
}
}
const server = http.createServer(requestListener);
server.listen(port,host, () => { // binds the server object to a newtwork address
console.log(`Server is running on http://${host}:${port}. (^c to cancel)`);
});
<!DOCTYPE html><body>
<button type="button" id="submitButton">Send and then Receive JSON</button>
<br>After clicking the button, the JSON string sent from the browser to the server will show in the console.
<br>Then the JSON response string from the server will replace what is below.
<br><br>
<div id='messageArea'>
innerHTMLMessage to replace via ajax.
</div>
<script>
'use strict';
asyncconst functionsubmitButton exchangeJSON= document.getElementById('submitButton') {;
const messageArea = document.getElementById('submitButton''messageArea').disabled;
= true; async function exchangeJSON() {
try {
submitButton.disabled = true;
// here can build a complex object to send
const objToSend = {message1: 'Test message from browser', message2: 'could be a complex JSON string'};
const response = await fetch('test_ajax_post_json_sans_form.html/ajaxTest1', {
method: 'POST',
body: JSON.stringify(objToSend)
});
if (response.ok) {
const jsonResponse = await response.json();
// here can parse, update screen, etc.
document.getElementById('messageArea')messageArea.textContent = JSON.stringify(jsonResponse);
}
//throw new Error('Test error in ExchangeJSON'); // uncomment for testing
} catch (error) {
document.getElementById('messageArea')messageArea.textContent = error;
} finally {
document.getElementById('submitButton') submitButton.disabled = false;
}
}
document.getElementById('submitButton')submitButton.addEventListener('click',exchangeJSON);
</script>
</body></html>
'use strict';
const host = 'localhost';
const http = require('http'); // VSCode shows 3 dots under "require" and says something about NodeRequire???
const fs = require('fs').promises;
const port = 8000;
const requestListener = function (req, res) {
switch (req.url) {
case "/test_ajax_post_json_sans_form.html": // serve an intial html file
fs.readFile(__dirname + '/test_ajax_post_json_sans_form.html')
.then(contents => {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(contents);
})
.catch(err => {
res.writeHead(500);
res.end(err);
return;
});
break
case '/test_ajax_post_json_sans_form.html/ajaxTest1': // receive json, process, then return other json
let body = '';
req.on('data', (data) => {
body += data;
});
req.on('end', () => {
console.log(body); // to show all data has arrived
// here we will check or errors, create a complex return-object, stringify it, and send it back
const objToReturn = {data1: 'Test message from server', data2: 'could be a complex json object'};
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(objToReturn));
});
break
case '/favicon.ico':
// browser will call favicon automatically. This satisfies the request (though its failing
// won't keep the ajax from working).
fs.readFile(__dirname + '/favicon.ico')
.then(contents => {
res.writeHead(200, {'Content-Type': 'image/x-icon'});
res.end(contents);
})
.catch(err => { // lacking favicon will not impact test
res.writeHead(200, {'Content-Type': 'image/x-icon'});
res.end();
});
break
default:
res.writeHead(404);
res.end(JSON.stringify({error:'Resource not found'})); // in production, might load a not-found page here
}
}
const server = http.createServer(requestListener);
server.listen(port,host, () => { // binds the server object to a newtwork address
console.log(`Server is running on http://${host}:${port}. (^c to cancel)`);
});
<!DOCTYPE html><body>
<button type="button" id="submitButton">Send and then Receive JSON</button>
<br>After clicking the button, the JSON string sent from the browser to the server will show in the console.
<br>Then the JSON response string from the server will replace what is below.
<br><br>
<div id='messageArea'>
innerHTML to replace via ajax
</div>
<script>
'use strict';
async function exchangeJSON() {
document.getElementById('submitButton').disabled = true;
try {
// here can build a complex object to send
const objToSend = {message1: 'Test message from browser', message2: 'could be a complex JSON string'};
const response = await fetch('test_ajax_post_json_sans_form.html/ajaxTest1', {
method: 'POST',
body: JSON.stringify(objToSend)
});
if (response.ok) {
const jsonResponse = await response.json();
// here can parse, update screen, etc.
document.getElementById('messageArea').textContent = JSON.stringify(jsonResponse);
}
//throw new Error('Test error in ExchangeJSON'); // uncomment for testing
} catch (error) {
document.getElementById('messageArea').textContent = error;
}
document.getElementById('submitButton').disabled = false;
}
document.getElementById('submitButton').addEventListener('click',exchangeJSON);
</script>
</body></html>
'use strict';
const host = 'localhost';
const http = require('http'); // VSCode shows 3 dots under "require" and says something about NodeRequire???
const fs = require('fs').promises;
const port = 8000;
const requestListener = function (req, res) {
switch (req.url) {
case "/test_ajax_post_json_sans_form.html": // serve an intial html file
fs.readFile(__dirname + '/test_ajax_post_json_sans_form.html')
.then(contents => {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(contents);
})
.catch(err => {
res.writeHead(500);
res.end(err);
return;
});
break
case '/test_ajax_post_json_sans_form.html/ajaxTest1': // receive json, process, then return other json
let body = '';
req.on('data', (data) => {
body += data;
});
req.on('end', () => {
console.log(body); // to show all data has arrived
// here we will check or errors, create a complex return-object, stringify it, and send it back
const objToReturn = {data1: 'Test message from server', data2: 'could be a complex json object'};
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(objToReturn));
});
break
case '/favicon.ico':
// browser will call favicon automatically. This satisfies the request (though its failing
// won't keep the ajax from working).
fs.readFile(__dirname + '/favicon.ico')
.then(contents => {
res.writeHead(200, {'Content-Type': 'image/x-icon'});
res.end(contents);
})
.catch(err => { // lacking favicon will not impact test
res.writeHead(200, {'Content-Type': 'image/x-icon'});
res.end();
});
break
default:
res.writeHead(404);
res.end(JSON.stringify({error:'Resource not found'})); // in production, might load a not-found page here
}
}
const server = http.createServer(requestListener);
server.listen(port,host, () => { // binds the server object to a newtwork address
console.log(`Server is running on http://${host}:${port}. (^c to cancel)`);
});
<!DOCTYPE html><body>
<button type="button" id="submitButton">Send and then Receive JSON</button>
<br>After clicking the button, the JSON string sent from the browser to the server will show in the console.
<br>Then the JSON response string from the server will replace what is below.
<br><br>
<div id='messageArea'>
Message to replace via ajax.
</div>
<script>
'use strict';
const submitButton = document.getElementById('submitButton');
const messageArea = document.getElementById('messageArea');
async function exchangeJSON() {
try {
submitButton.disabled = true;
// here can build a complex object to send
const objToSend = {message1: 'Test message from browser', message2: 'could be a complex JSON string'};
const response = await fetch('test_ajax_post_json_sans_form.html/ajaxTest1', {
method: 'POST',
body: JSON.stringify(objToSend)
});
if (response.ok) {
const jsonResponse = await response.json();
// here can parse, update screen, etc.
messageArea.textContent = JSON.stringify(jsonResponse);
}
//throw new Error('Test error in ExchangeJSON'); // uncomment for testing
} catch (error) {
messageArea.textContent = error;
} finally {
submitButton.disabled = false;
}
}
submitButton.addEventListener('click',exchangeJSON);
</script>
</body></html>
html with client code image ORIGINAL (SEE snippet for update): enter image description here
I included the code in snippets, but it requires node.js to run, so you'd have to copy it to a computer with node.js. (HTML UPDATED per suggestions 10/11):
'use strict';
const host = 'localhost';
const http = require('http'); // VSCode shows 3 dots under "require" and says something about NodeRequire???
const fs = require('fs').promises;
const port = 8000;
const requestListener = function (req, res) {
switch (req.url) {
case "/test_ajax_post_json_sans_form.html": // serve an intial html file
fs.readFile(__dirname + '/test_ajax_post_json_sans_form.html')
.then(contents => {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(contents);
})
.catch(err => {
res.writeHead(500);
res.end(err);
return;
});
break
case '/test_ajax_post_json_sans_form.html/ajaxTest1': // receive json, process, then return other json
let body = '';
req.on('data', (data) => {
body += data;
});
req.on('end', () => {
console.log(body); // to show all data has arrived
// here we will check or errors, create a complex return-object, stringify it, and send it back
const objToReturn = {data1: 'Test message from server', data2: 'could be a complex json object'};
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(objToReturn));
});
break
case '/favicon.ico':
// browser will call favicon automatically. This satisfies the request (though its failing
// won't keep the ajax from working).
fs.readFile(__dirname + '/favicon.ico')
.then(contents => {
res.writeHead(200, {'Content-Type': 'image/x-icon'});
res.end(contents);
})
.catch(err => { // lacking favicon will not impact test
res.writeHead(200, {'Content-Type': 'image/x-icon'});
res.end();
});
break
default:
res.writeHead(404);
res.end(JSON.stringify({error:'Resource not found'})); // in production, might load a not-found page here
}
}
const server = http.createServer(requestListener);
server.listen(port,host, () => { // binds the server object to a newtwork address
console.log(`Server is running on http://${host}:${port}. (^c to cancel)`);
});
<!DOCTYPE html><body>
<button type="button" id="idSubmitButton">Sendid="submitButton">Send and then Receive JSON</button>
<br>After clicking the button, the JSON string sent from the browser to the server will show in the console.
<br>Then the JSON response string from the server will replace what is below.
<br><br>
<div id='idDisplay'>id='messageArea'>
innerHTML to replace via ajax
</div>
<script>
'use strict';
async function exchangeJSON() {
idSubmitButtondocument.getElementById('submitButton').disabled = truetrue;
// assure post isn't sent again prior to a response try {
// here can build a complex object could beto builtsend
const testObjToSendobjToSend = {message1: 'Test message from browser', message2: 'could be a complex JSON string'};
const xhrresponse = newawait XMLHttpRequestfetch();'test_ajax_post_json_sans_form.html/ajaxTest1', {
xhr.onreadystatechange = function () { method: 'POST',
if (xhr.readyState == 4 && xhr.status == 200) {body: JSON.stringify(objToSend)
});
// this is where the received responseText can be manipulated to update theif page(response.ok) {
documentconst jsonResponse = await response.getElementByIdjson('idDisplay').innerHTML;
= xhr.responseText; // demonstrate json arrived
// here can parse, update screen, idSubmitButtonetc.disabled = false // post completed, so enable posting again
document.getElementById('messageArea').textContent = JSON.stringify(jsonResponse);
}
}
xhr.open('POST', 'test_ajax_post_json_sans_form.html/ajaxTest1', true);
//throw new Error('Test error in ExchangeJSON'); // uncomment for testing
xhr.setRequestHeader('Content-Type', 'application/json');
} catch xhr.send(JSON.stringify(testObjToSend)error);
{
}
const idSubmitButton = document.getElementById('idSubmitButton''messageArea');.textContent = error;
idSubmitButton.addEventListener('click', function () { }
exchangeJSONdocument.getElementById('submitButton').disabled ;= false;
}
document.getElementById('submitButton').addEventListener('click',exchangeJSON);
</script>
</body></html>
html with client code image: enter image description here
I included the code in snippets, but it requires node.js to run, so you'd have to copy it to a computer with node.js:
'use strict';
const host = 'localhost';
const http = require('http'); // VSCode shows 3 dots under "require" and says something about NodeRequire???
const fs = require('fs').promises;
const port = 8000;
const requestListener = function (req, res) {
switch (req.url) {
case "/test_ajax_post_json_sans_form.html": // serve an intial html file
fs.readFile(__dirname + '/test_ajax_post_json_sans_form.html')
.then(contents => {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(contents);
})
.catch(err => {
res.writeHead(500);
res.end(err);
return;
});
break
case '/test_ajax_post_json_sans_form.html/ajaxTest1': // receive json, process, then return other json
let body = '';
req.on('data', (data) => {
body += data;
});
req.on('end', () => {
console.log(body); // to show all data has arrived
// here we will check or errors, create a complex return-object, stringify it, and send it back
const objToReturn = {data1: 'Test message from server', data2: 'could be a complex json object'};
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(objToReturn));
});
break
case '/favicon.ico':
// browser will call favicon automatically. This satisfies the request (though its failing
// won't keep the ajax from working).
fs.readFile(__dirname + '/favicon.ico')
.then(contents => {
res.writeHead(200, {'Content-Type': 'image/x-icon'});
res.end(contents);
})
.catch(err => { // lacking favicon will not impact test
res.writeHead(200, {'Content-Type': 'image/x-icon'});
res.end();
});
break
default:
res.writeHead(404);
res.end(JSON.stringify({error:'Resource not found'})); // in production, might load a not-found page here
}
}
const server = http.createServer(requestListener);
server.listen(port,host, () => { // binds the server object to a newtwork address
console.log(`Server is running on http://${host}:${port}. (^c to cancel)`);
});
<!DOCTYPE html><body>
<button type="button" id="idSubmitButton">Send and then Receive JSON</button>
<br>After clicking the button, the JSON string sent from the browser to the server will show in the console.
<br>Then the JSON response string from the server will replace what is below.
<br><br>
<div id='idDisplay'>
innerHTML to replace via ajax
</div>
<script>
'use strict';
function exchangeJSON() {
idSubmitButton.disabled = true // assure post isn't sent again prior to a response
// here a complex object could be built
const testObjToSend = {message1: 'Test message from browser', message2: 'could be a complex JSON string'};
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
// this is where the received responseText can be manipulated to update the page
document.getElementById('idDisplay').innerHTML = xhr.responseText; // demonstrate json arrived
idSubmitButton.disabled = false // post completed, so enable posting again
}
}
xhr.open('POST', 'test_ajax_post_json_sans_form.html/ajaxTest1', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify(testObjToSend));
}
const idSubmitButton = document.getElementById('idSubmitButton');
idSubmitButton.addEventListener('click', function () {
exchangeJSON() ;
});
</script>
</body></html>
html with client code image ORIGINAL (SEE snippet for update): enter image description here
I included the code in snippets, but it requires node.js to run, so you'd have to copy it to a computer with node.js. (HTML UPDATED per suggestions 10/11):
'use strict';
const host = 'localhost';
const http = require('http'); // VSCode shows 3 dots under "require" and says something about NodeRequire???
const fs = require('fs').promises;
const port = 8000;
const requestListener = function (req, res) {
switch (req.url) {
case "/test_ajax_post_json_sans_form.html": // serve an intial html file
fs.readFile(__dirname + '/test_ajax_post_json_sans_form.html')
.then(contents => {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(contents);
})
.catch(err => {
res.writeHead(500);
res.end(err);
return;
});
break
case '/test_ajax_post_json_sans_form.html/ajaxTest1': // receive json, process, then return other json
let body = '';
req.on('data', (data) => {
body += data;
});
req.on('end', () => {
console.log(body); // to show all data has arrived
// here we will check or errors, create a complex return-object, stringify it, and send it back
const objToReturn = {data1: 'Test message from server', data2: 'could be a complex json object'};
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(objToReturn));
});
break
case '/favicon.ico':
// browser will call favicon automatically. This satisfies the request (though its failing
// won't keep the ajax from working).
fs.readFile(__dirname + '/favicon.ico')
.then(contents => {
res.writeHead(200, {'Content-Type': 'image/x-icon'});
res.end(contents);
})
.catch(err => { // lacking favicon will not impact test
res.writeHead(200, {'Content-Type': 'image/x-icon'});
res.end();
});
break
default:
res.writeHead(404);
res.end(JSON.stringify({error:'Resource not found'})); // in production, might load a not-found page here
}
}
const server = http.createServer(requestListener);
server.listen(port,host, () => { // binds the server object to a newtwork address
console.log(`Server is running on http://${host}:${port}. (^c to cancel)`);
});
<!DOCTYPE html><body>
<button type="button" id="submitButton">Send and then Receive JSON</button>
<br>After clicking the button, the JSON string sent from the browser to the server will show in the console.
<br>Then the JSON response string from the server will replace what is below.
<br><br>
<div id='messageArea'>
innerHTML to replace via ajax
</div>
<script>
'use strict';
async function exchangeJSON() {
document.getElementById('submitButton').disabled = true;
try {
// here can build a complex object to send
const objToSend = {message1: 'Test message from browser', message2: 'could be a complex JSON string'};
const response = await fetch('test_ajax_post_json_sans_form.html/ajaxTest1', {
method: 'POST',
body: JSON.stringify(objToSend)
});
if (response.ok) {
const jsonResponse = await response.json();
// here can parse, update screen, etc. document.getElementById('messageArea').textContent = JSON.stringify(jsonResponse);
}
//throw new Error('Test error in ExchangeJSON'); // uncomment for testing
} catch (error) {
document.getElementById('messageArea').textContent = error;
}
document.getElementById('submitButton').disabled = false;
}
document.getElementById('submitButton').addEventListener('click',exchangeJSON);
</script>
</body></html>