1

I'm currently struggling with an ajax that posts a json to a nodejs route. I want to get the selected values of 4 button-groups. The button-groups have the following ids: quality, costeffectiveness, deliveryscope and rating. Each button-group contains 5 radio-buttons with a value with an own id, such as quality1 or quality2. The values of these buttons range from 1 to 5.

My guess is that I'm missing out things mentioned here: How do I return the response from an asynchronous call?

    $(document).ready(function () {

    // SUBMIT FORM
    $("#ratingForm").submit(function (event) {
        // Prevent the form from submitting via the browser.
        event.preventDefault();
        ajaxPost();
    });

    function ajaxPost() {

        // PREPARE FORM DATA
        let ratingData = {
            quality: $('input[name=options]:checked', '#quality').val(),
            costeffectiveness: $('input[name=options]:checked', '#costeffectiveness').val(),
            deliveryscope: $('input[name=options]:checked', '#deliveryscope').val(),
            contentment: $('input[name=options]:checked', '#contentment').val()
        };

        // DO POST
        $.ajax({
            type: "POST",
            contentType: "application/json",
            url: "/rating",
            data: JSON.stringify(ratingData),
            dataType: 'json',
            success: function (rating) {
                $("#ratingResultDiv").html("<p>" +
                        "Post Successfully! <br>" +
                        "--->" + JSON.stringify(rating) + "</p>");
            },
            error: function (e) {
                alert("Error!");
                console.log("ERROR: ", e);
            }
        });
    }
});

When I'm assigning variables in a different kind of way and change the route for the expected json, it works like a charm:

            // PREPARE FORM DATA
        let formData = {
            firstname: $("#firstname").val(),
            lastname: $("#lastname").val()
        };

Working.

NodeJS Route:

router.post('/rating', function (req, res, next) {

console.log("RATINGS: " + JSON.stringify(req.body));
console.log(req.body.quality);
console.log(req.body.costeffectiveness);
console.log(req.body.deliveryscope);
console.log(req.body.contentment);

let rating = {};

rating.quality= req.body.quality;
rating.costeffectiveness = req.body.costeffectiveness;
rating.deliveryscope = req.body.deliveryscope;
rating.contentment = req.body.contentment;

return res.send(rating);

HTML:

                            <form method="POST" action="/rating">
                            <form id="ratingForm">
                                <div class="form-group">
                                    <p class="my-2">Quality</p>
                                    <div class="btn-group btn-group-lg btn-group-toggle" id="quality"
                                         data-toggle="buttons">
                                        <label class="btn btn-primary active">
                                            <input type="radio" name="quality" id="quality1" value="1"
                                                   autocomplete="off" checked>
                                            1
                                        </label>
                                        <label class="btn btn-primary">
                                            <input type="radio" name="quality" id="quality2" value="2"
                                                   autocomplete="off"> 2
                                        </label>
                                        <label class="btn btn-primary">
                                            <input type="radio" name="quality" id="quality3" value="3"
                                                   autocomplete="off"> 3
                                        </label>
                                        <label class="btn btn-primary">
                                            <input type="radio" name="quality" id="quality4" value="4"
                                                   autocomplete="off"> 4
                                        </label>
                                        <label class="btn btn-primary">
                                            <input type="radio" name="quality" id="quality5" value="5"
                                                   autocomplete="off"> 5
                                        </label>
                                    </div>
                                    <p class="my-2">Cost Effectiveness</p>
                                    <div class="btn-group btn-group-lg btn-group-toggle" id="cost-effectiveness"
                                         data-toggle="buttons">
                                        <label class="btn btn-secondary active">
                                            <input type="radio" name="costeffectiveness" id="cost_effectiveness1" value="1"
                                                   autocomplete="off"
                                                   checked> 1
                                        </label>
                                        <label class="btn btn-secondary">
                                            <input type="radio" name="costeffectiveness" id="cost_effectiveness2" value="2"
                                                   autocomplete="off">
                                            2
                                        </label>
                                        <label class="btn btn-secondary">
                                            <input type="radio" name="costeffectiveness" id="cost_effectiveness3" value="3"
                                                   autocomplete="off">
                                            3
                                        </label>
                                        <label class="btn btn-secondary">
                                            <input type="radio" name="costeffectiveness" id="cost_effectiveness4" value="4"
                                                   autocomplete="off">
                                            4
                                        </label>
                                        <label class="btn btn-secondary">
                                            <input type="radio" name="costeffectiveness" id="cost_effectiveness5" value="5"
                                                   autocomplete="off">
                                            5
                                        </label>
                                    </div>
                                    <p class="my-2">Delivery Scope</p>
                                    <div class="btn-group btn-group-lg btn-group-toggle" id="delivery-scope"
                                         data-toggle="buttons">
                                        <label class="btn btn-info active">
                                            <input type="radio" name="deliveryscope" id="delivery_scope1" value="1"
                                                   autocomplete="off"
                                                   checked> 1
                                        </label>
                                        <label class="btn btn-info">
                                            <input type="radio" name="deliveryscope" id="delivery_scope2" value="2"
                                                   autocomplete="off">
                                            2
                                        </label>
                                        <label class="btn btn-info">
                                            <input type="radio" name="deliveryscope" id="delivery_scope3" value="3"
                                                   autocomplete="off">
                                            3
                                        </label>
                                        <label class="btn btn-info">
                                            <input type="radio" name="deliveryscope" id="delivery_scope4" value="4"
                                                   autocomplete="off">
                                            4
                                        </label>
                                        <label class="btn btn-info">
                                            <input type="radio" name="deliveryscope" id="delivery_scope5" value="5"
                                                   autocomplete="off">
                                            5
                                        </label>
                                    </div>
                                    <p class="my-2">Contentment</p>
                                    <div class="btn-group btn-group-lg btn-group-toggle" id="contentment"
                                         data-toggle="buttons">
                                        <label class="btn btn-secondary active">
                                            <input type="radio" name="contentment" id="contentment1" value="1"
                                                   autocomplete="off"
                                                   checked>
                                            1
                                        </label>
                                        <label class="btn btn-secondary">
                                            <input type="radio" name="contentment" id="contentment2" value="2"
                                                   autocomplete="off"> 2
                                        </label>
                                        <label class="btn btn-secondary">
                                            <input type="radio" name="contentment" id="contentment3" value="3"
                                                   autocomplete="off"> 3
                                        </label>
                                        <label class="btn btn-secondary">
                                            <input type="radio" name="contentment" id="contentment4" value="4"
                                                   autocomplete="off"> 4
                                        </label>
                                        <label class="btn btn-secondary">
                                            <input type="radio" name="contentment" id="contentment5" value="5"
                                                   autocomplete="off"> 5
                                        </label>
                                    </div>
                                    <div class="modal-footer my-4">
                                        <button type="submit" class="btn btn-lg btn-primary btn-block">Submit rating
                                        </button>
                                    </div>
                                </div>
                            </form>
                        </form>
S.Neum
  • 82
  • 8
  • Can I see your HTML markup for those checkboxes? Plus this `$('input[name=options]:checked', '#quality')` looks wrong to me. What are you trying to achieve with that? – Romeo Sierra Jun 28 '18 at 07:29
  • The question is: WHY? What does your ajax- post- request add? If you have a form with input and a form- method post, then using ajax is completely unnecessary... – Tode Jun 28 '18 at 07:30
  • @Romeo Im trying to get the checked radio button within the button group with the mentioned lines. HTML markup added. – S.Neum Jun 28 '18 at 07:42
  • Anyway, the problem lies in `$('input[name=options]:checked', '#quality')`. This selection makes no sense to the jQuery engine. – Romeo Sierra Jun 28 '18 at 07:43
  • @RomeoSierra thanks for that! Got that snippet from stackoverflow. How would you get those information - or even better: what kind of buttons / inputs would you use to allow a "rating" from 1-5? – S.Neum Jun 28 '18 at 07:45
  • Check my answer and see if that helps. – Romeo Sierra Jun 28 '18 at 07:50
  • Checked your answer - thanks for that! Didn't worked out. Still getting an undefined. I guess that i'm accessing the json object wrong somehow? Because there is a value stored in "options". Node logs: RATINGS: {"options":"4"} undefined – S.Neum Jun 28 '18 at 08:13

3 Answers3

0
let req = JSON.parse(req);

Try to put this on your node js script

Joven28
  • 769
  • 3
  • 12
0

Problem is in your jQuery selectors. It should be

let ratingData = {
    quality: $('#quality input[name=options]:checked').val(),
    costeffectiveness: $('#costeffectiveness input[name=options]:checked').val(),
    deliveryscope: $('#deliveryscope input[name=options]:checked').val(),
    contentment: $('#contentment input[name=options]:checked').val()
};
Romeo Sierra
  • 1,666
  • 1
  • 17
  • 35
  • I tested your fixed jQuery selectors, and they are working when I use them outside the function ajaxPost(). When I use them within I receive a undefined json object. – S.Neum Jun 28 '18 at 10:15
  • Can you try `console.log(ratingData)`, **just after** the `ratingData` object is constructed? And what do you exactly mean by *I receive*? Are you referring to the response from the NodeJS server? – Romeo Sierra Jun 28 '18 at 10:28
  • Tried to console.log but I just get a blank page in the browser with empty curly brackets. I meant the nodejs log with my mentioned "I received [...]". When I console log the minified example the following entries are in the javascript log in the browser: {firstname: "demo", lastname: "demo"} 12:35:07.260 jquery-3.3.1.js:9600 XHR finished loading: POST "http://localhost:3001/rating". When I console log the critical post there's no entries in die javascript console except the following: Navigated to http://localhost:3001/rating – S.Neum Jun 28 '18 at 10:40
0

The problem was, that each button in the button group had the same name. As soon as I gave the buttons in a group an individual name, the values were accessible in json. I'm going to edit my code in the question.

S.Neum
  • 82
  • 8