0

I am trying to grasp using node express server and jQuery.ajax() in tandem. I have created a code repository with the following structure:

/
|-public
| |-index.html
|-server.js

My index page has the following JS snippet in it:

var successHandler = function (data, status, jqXHR) {
    console.log('success')
};

var failHandler = function (jqXHR, status, errorThrown) {
    console.log('fail')
};

var progressHandler = function () {
    console.log('progress')
};

var ajaxConfig = {
    url: 'http://localhost:4444/test',
    type: 'GET'
};

$.ajax(ajaxConfig).then(successHandler, failHandler, progressHandler);

the server-side code is defined as such:

const express = require('express')
const app = express()
const sleep = require('sleep')

app.get('/test', function (req, res) {
    console.log('/test method called!');
    sleep.sleep(3);
    res.status(202).send({"thing":"stuff"})
})

app.post('/test', function(req,res){
    res.status(202).send('ok')
})

app.use(express.static('public'))
app.use(express.static('node_modules/jquery/dist'))

app.listen(4444, function () {
    console.log('Running on localhost:4444!')
})

The thing that I want to accomplish is to get some hits on the progress handler, just to get it to write data in the console.

According to this page, I need to use the deffered.notify() method to trigger the handler but I have no idea how to get to the deffered object. I tried saving the return value of $.ajax() but that doesn't seem to have the notify() method since it is a jqXHR object.

It is my understanding that I need to have a progress handler defined on the server-side (the post handler for the /test route) that gets called to get to the current status of the pending task. Don't think making a new ajax request is the way to go, but I might be wrong. I have also found some articles that utilize the setTimeout method, My guess is that it gets used in order to repeatedly call the endpoint that gives status info.

Denis Kralj
  • 633
  • 2
  • 12
  • 27
  • [**this**](https://stackoverflow.com/questions/19126994/what-is-the-cleanest-way-to-get-the-progress-of-jquery-ajax-request#answer-19127053) is how you generally set up a progress callback for jQuery's ajax. I'm not sure if jQuery calls the third progress argument of `then` the same way it would when you use the XMLHttpResponse progress ? – adeneo Sep 04 '17 at 14:58
  • There is no way to trigger a jQuery progress event from the server that I know of. – jfriend00 Sep 04 '17 at 14:58
  • Just so you know, the `sleep` module is a pretty horrible thing to use for anything other than testing. It blocks the entire node.js Javascript thread and event loop from doing anything else. Use `setTimeout()` instead. – jfriend00 Sep 04 '17 at 15:04
  • @jfriend00 I don't insist on making it that way, I would just like to know what part of code (either server or client side) I am missing in order to get the desired effect. – Denis Kralj Sep 04 '17 at 15:20

0 Answers0