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.