0

So I have this webpage where there is one input field. The user can type in an input and the form gets submittted via AJAX post method. The user input is then used to fetch data from an API in the post endpoint. The API returns some data which is then sent to the frontend and I get access to it in the AJAX block inside success method, which is then rendered on the webpage. Now everything works perfectly fine and all.

The problem arises when the post endpoint has failed to fetch data from the API. The catch block of the post endpoint runs but it doesn't display the connect-flash-plus based error flash message on the webpage. It just redirects to the page.

Please note at this point that the flash message works perfectly for the other pages of my app where I'm not using any AJAX method of form submission. So I'm thinking it's because of AJAX.

Here's the HTML:

<!-- ERROR SECTION  -->

<form id="form">
        <input type="text" id="inlineFormInputName2" required >
        <button type="submit" class="submit">Submit</button>
</form>

<% if(error && error.length > 0){ %>
        <div class="error-container boxshadow w-100 mb-5">
                <div class="alert alert-danger">
                        <strong>Error:</strong> <%= error %>
                </div>
        </div>
<% } %>

These are the GET and POST endpoints:

router.get("/example", async (req, res) => {

    try{
        res.locals.title = "Example";
        res.render( "../views/example" );
    }catch(err) {
        req.flash("error", "Unable to retrieve data. Please try again!");
        res.redirect("/example");
    }
    
});


router.post("/example", async (req, res) => {
    try{
        const query     = req.body.name;
        const url       = `https://api.example.com/${query}?key=${process.env.API_KEY}`;
        const response  = await axios.get(url);

        if( response.status === 200 ) {

            return res.json({ 
                data: response.data
            });
        
        }

    }catch(err) {
        console.log(err)
        req.flash("error", "Unable to retrieve data. Please try again!");
        res.redirect("/example");
    }
});

This is the AJAX code in main.js file:

$(#form).submit( e => {

        e.preventDefault();
        const formInput = $('#inlineFormInputName2');
        const name = formInput.val();

        $.ajax({
            type: "POST",
            url: '/example',
            dataType: 'json',
            data: { 
                "name": name
            },
            beforeSend: function () { 
                $('.loader-container').removeClass('hidden');
            },
            success: function (data) {
                console.log(data)
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.log('1: ', jqXHR)
                console.log('2: ', textStatus)
                console.log('3: ', errorThrown)
                $('.loader-container').addClass('hidden');
                $('section .error-container').removeClass('hidden');
            },
            complete: function () { 
                $('.loader-container').addClass('hidden');
            }
        });
    });

UPDATE:

As I'm using a catch block, I had to remove the connect flash message and created a res.json() as the error message. This is then accessible in the ajax call in success method. I don't know why but it is accessible in success method instead of error method.

Zak
  • 860
  • 16
  • 39
  • please confirm if you are expecting this line "req.flash("error", "Unable to retrieve data. Please try again!");" to show error for you on webpage. – Akshay Aggarwal Dec 01 '20 at 09:22
  • @AkshayAggarwal Hi. Yes. That's what I used in the other pages of the app where it works and doesn't have AJAX form submission. – Zak Dec 01 '20 at 09:33
  • https://stackoverflow.com/questions/39669520/how-to-use-connect-flash-with-ajax please refer to this it might help you. – Akshay Aggarwal Dec 01 '20 at 09:42
  • @AkshayAggarwal hey I had already tried that solution before posting here. It just doesn't work. I had removed the req.flash message. And put a simple console.log() in the catch block. The in ajax call I added ```error: function () {}``` method and put a console.log() there as well. But I always get the output from catch block console.log(). – Zak Dec 01 '20 at 14:40
  • Kind of fixed it myself. As I'm using a catch block, I'll need to res.json() the error message and that is accessible in the ajax call in success method. I don't know why but it is accessible in success method instead of error method. – Zak Dec 01 '20 at 15:00

1 Answers1

0

As I'm using a catch block, I had to remove the connect flash message and created a res.json() as the error message. This is then accessible in the ajax call in success method instead of error method.

Zak
  • 860
  • 16
  • 39