Deidara
Deidara

Reputation: 677

Use Ajax and Nodejs to update data on a page

I am trying to write a loop to update a webpage every 30 seconds, but I am not sure how to make an ajax call with setInverval function. Here's my server code:

var app = express()
app.get('/', function(req, res){
// error here
res.sendFile('./index.html',{root: __dirname})
//...Some data 
res.send(data)
});

I have a setInverval function in my index.html:

<script>
function ajaxCall(){
  $.ajax({url: "http://localhost:3000/", success: function(result){
    // I want to receive new result every 30 seconds
  }})

}
setInterval(ajaxCall,30000)
</script>

Since I am not sure how to deal with app.get("/") and the ajax request, I got

Error: Can't set headers after they are sent.

cause I tried to send data twice

How should I modify the code so that I can see my data displaying on 'http://localhost:3000/' and it updates every 30 seconds?

Thank you.

Upvotes: 0

Views: 1647

Answers (2)

Hijliche
Hijliche

Reputation: 119

Like Nicholas Kyriakides said, you need to define the following:

// serve your index
app.get('/', function(req, res){
  res.sendFile('./index.html',{root: __dirname})
});

// serve your data
// Your AJAX call should hit this endpoint instead
app.get('/data', function(req, res) {
 var data = "lorem ipsum dolor";
  res.send(data);
});

Then, you need to change your AJAX call:

<script>
function ajaxCall(){
  $.ajax({url: "http://localhost:3000/data", success: function(result){
    //do whatever you want with the returned data (in result)
    //f.e. to update something on your web page, you want something like:
    document.getElementById("idOfElementYouWantChanged").innerHTML = result;
  }})

}
setInterval(ajaxCall,30000)
</script>

Upvotes: 1

nicholaswmin
nicholaswmin

Reputation: 22989

Can't set headers after they are sent usually indicates that you respond to a request twice.

You can't do that.

For each request/req there should only be one response/res.

app.get('/', function(req, res) {
  // you respond to the request here
  res.sendFile('./index.html',{root: __dirname});
  // and you respond again here
  res.send(data)
});

Decide if you want to sendFile() OR send(data) for that endpoint.

Judging from your code you probably want to create another endpoint, to hit with your AJAX call, where it does the latter

// serve your index
app.get('/', function(req, res) {
  res.sendFile('./index.html',{root: __dirname})
});

// serve your data
// Your AJAX call should hit this endpoint instead
app.get('/data', function(req, res) {
  var data = 'lorem ipsum dolor';
  res.send(data);
});

Upvotes: 1

Related Questions