0

when pressing a button this code gets executed

function submitData() {
    $.ajax({
        type: 'GET',
        url: '/questionnaire/submit', // listen to a route
        dataType: "json",
        data: JSON.stringify({ // some test data
            satisfactory: "house",
            improvement: "bla",
            rating: "this is a text"
        })
    }).done(function () {
        $(location).attr('href', '/sendOff'); // redirect to another route
    }).fail(function () {
        console.log("Error");
    });
}

and the server is listening on this

app.get('/questionnaire/submit', function (req, res) {
    var data = req.query; // Get the data object from the Ajax call

    console.log(data);

    res.send(null); // Send nothing back
});

Whenever pressing the button, "Error" gets logged in the console. The Ajax call always fails.

Even when writing res.send("Success"); the client will log "Error". What am I missing?


Update: I installed the body parser middleware and use this code now

my app.js

const path = require('path');
const express = require('express');
const exphbs  = require('express-handlebars');
const bodyParser = require('body-parser');

const handlebars = exphbs.create({
    defaultLayout: 'index',
    extname: 'hbs'
});

const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

require('./Server/Routes/questionnaire')(app);
require('./Server/Routes/sendOff')(app);

app.engine('hbs', handlebars.engine);
app.set('view engine', 'hbs');

app.use(express.static(path.join(__dirname, 'Public')));

app.listen(8888, function () {
    console.log('Server running on port 8888');
});

my route

module.exports = function (app) {

    app.get('/questionnaire', function (req, res) {
        res.render('questionnaire');
    });

    app.post('/questionnaire/submit', function (req, res) {
        var data = req.body;

        console.log(data);

        res.send(null);
    });
};

and my client function

function submitData() {
    $.ajax({
        type: 'POST',
        url: '/questionnaire/submit',
        dataType: "json",
        data: JSON.stringify({
            satisfactory: $("#edtSatisfactory").val(),
            improvement: $("#edtImprovement").val(),
            rating: currentRating / ratingElements.length
        })
    }).done(function () {
        $(location).attr('href', '/sendOff');
    }).fail(function () {

    });
}

And when executing the Ajax call the client still runs into .fail()

3
  • you should check the network tab of your browser console to see what is happening. You can also pass a variable (err) to the fail callback and log the error Commented Dec 5, 2017 at 9:53
  • can you try req.body instead of req.query? Commented Dec 5, 2017 at 9:54
  • req.body will log "undefined" Commented Dec 5, 2017 at 9:56

4 Answers 4

1

Client request is :

function submitData() {
        $.ajax({
            type: 'POST',
            url: '/questionnaire/submit', // listen to a route
            dataType: "json",
            data: {
                satisfactory: "house",
                improvement: "bla",
                rating: "this is a text"
            }
        }).done(function () {
            $(location).attr('href', '/sendOff'); // redirect to another route
        }).fail(function () {
            console.log("Error");
        });
    }

and the server is listening on this Using bodyParser middleware in your node backend :

app.post('/questionnaire/submit', function (req, res) {
    var data = req.body; // Get the data object from the Ajax call

    console.log(data);

    res.end(); // Send nothing back
});
Sign up to request clarification or add additional context in comments.

3 Comments

npm install --save body-parser // Install body-parser node module, const bodyParser = require('body-parser'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: false}));
when using the bodyParser the console will log POST http://localhost:8888/questionnaire/submit 404 (Not Found)
This is POST request so you can not hit directly using browser URL. Hit this POST request by using any button click or any REST client tools like as Postman.
1

You're using a GET http method, which shouldn't take body, you should instead append your data to the back of the url. Or if you want to use a body, then switch to a POST.

url: '/questionnaire/submit?satisfactory=house&improvement=bla&rating=sometext

If you're using POST don't forget:

'Content-Type': 'application/json',

Edit: On the server you need to parse the JSON request, this is best done with a middleware called body-parser:

npm install --save body-parser
const bodyParser = require('body-parser');
app.use(bodyParser.json());

This will parse your JSON and add it to req.body.

8 Comments

When writing type: 'POST', and on the server app.post(...) it still runs into "Error"
check update, btw are you using bodyParser middleware in your node backend?
No I don't know this, I am new to NodeJs. Would you mind giving me an example?
npm install --save body-parser const bodyParser = require('body-parser'); app.use(bodyParser.json()); This will parse your JSON and add it to req.body
when using the bodyPaser the console will log POST http://localhost:8888/questionnaire/submit 404 (Not Found)
|
1

Try this..

Client Side

function submitData() {
    $.ajax({
        type: 'POST',
        url: '/questionnaire/submit', // listen to a route
        'Content-Type': 'application/json',
        data: JSON.stringify({"satisfactory": "house", "improvement": "bla", "rating": "this is a text"})
    }).done(function () {
        console.log('hi')
    }).fail(function () {
        console.log("Error");
    });
}

On server Side:

var express = require('express');
var bodyParser = require('body-parser');

var app = express();
app.use(bodyParser.json());

app.post('/questionnaire/submit', function (req, res) {
var data = req.body
    console.log(data);

    res.send(null); // Send nothing back
});

You have to install body-parser library using following command.

npm install --save body-parser

It will log "Hi" as ajax done is called. BTW You have redirected the page to 'sendOff' in your question. If you are not understanding anything plz comment below.

Comments

1

You just have to replace

dataType: "json",

with this:

'Content-Type': 'application/json'

in $.ajax request

Hope this will work.. I have tried & tested.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.