Quantcast
Channel: Active questions tagged html - Stack Overflow
Viewing all articles
Browse latest Browse all 72388

Reload page that posted data via XMTHTTPRequest object

$
0
0

I am in the process of learning web development and am just picking up AJAX; and this quest to learning AJAX is driving me crazy...

I've seen a lot of similar posts on stackoverflow using JQuery, but I am looking to achieve this using plain JS.

My requirement is that, I have an HTML page that posts form data via the XMLHTTPRequest object. The data is sent correctly to the sever (Node). What I would like to achieve is to reload the same page that sent the data with the data that it just posted (Like So).

I know this can be done through JQuery (ie. via a call to location.reload()), however I cannot get this to work simply by using XHMHTTPRequest. Is it even possible to achieve this with XHR? I can see that the xhr's ResponseText has the entire HTML with the desired update (See Ref). How can I then use this html to reload the page.

Any directions are greatly appreciated.

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge, chrome=1"/>

<script>
"use strict";
function submitForm()
{
  var formElement = document.getElementById("myForm");
  var formData = new FormData(formElement);

  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange=function(){
    if (xhr.readyState == 4 && xhr.status == 200)
    {
      alert(xhr.responseText); //xhr.responseText has the entire desired HTML
      window.location.reload; //Does nothing
    }
  }
  xhr.open("POST", "/Test", true);
  xhr.send(formData);
  return false;
}
</script>
</head>

<body>
<form id="myForm" method="POST" action="/Test" onsubmit="return submitForm()">
   <input type="text" value="John" name="name"/>
   <input type="submit" value="Send Data"/>
</form>
<div class="">
  <h4>Name entered was <%= data %></h4>
</div>
</body>
</html>
//Node JS
var express = require('express');
var bodyparser = require('body-parser');
var multer = require('multer'); 

var app = express();
app.use(express.static('./'));
app.set('view engine', 'ejs');
var mydata;

var urlencoded = bodyparser.urlencoded({extended:true});
var mult_handler = multer();

app.get('/Test', function(req, res){
    res.render("Test", {data:mydata});
});

app.post('/Test',mult_handler.none(), function(req, res){
  console.log("In POST");
  console.log(req.body.name);
  mydata = req.body.name;
  res.render("Test", {data:req.body.name});
});

Viewing all articles
Browse latest Browse all 72388

Trending Articles