olefrank
olefrank

Reputation: 6810

how to use connect-flash with ajax

I have a page with a form that posts edits to a local endpoint via AJAX ($.post). I want to display a message to the user whether it went good or bad. But I can't get it to work. Here's what I have so far:

jade template (excerpt)

if message
    .alert.alert-danger= message


// Tab panes
.tab-content

    #admin-tab-profile.tab-pane.active(role='tabpanel')
        h3 Profil
        form
            include partials/admin/profile

main.js (excerpt)

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

    // find profile
    profile.findById(data._id, function(err, profile) {

        // update
        profile.summary.da = data.da;
        profile.summary.en = data.en;

        // save
        profile.save(function(err) {
            if (err) {
                req.flash('loginMessage', 'Oops! Something went wrong.');

                res.status(500).send( { message: req.flash('loginMessage') } );
            }
            console.log("profile sucessfully updated");
            req.flash('loginMessage', 'Yes! Everythings good!');
            res.status(200).send( { message: req.flash('loginMessage') } );
        });
    });
});

app.js (excerpt)

app.use(flash()); // use connect-flash for flash messages stored in session

So what am I doing wrong? Why is not shown status messages when posting data?

Upvotes: 0

Views: 1652

Answers (2)

Mario Rozic
Mario Rozic

Reputation: 254

Well if your using ajax you don't have to use express flash messages, you can simply use ajax.success method:

$.ajax({
  method:'post',
  url: '/user/singup',
  data: data,
  success: function(msg) {
    console.log('Success!!');
    console.log(msg);  // loginMessage from your code
  },
  error: function() {
    console.log('Error!!');
  }
})

And send the status code from your post method in express:

res.status(200).send({ message: 'loginMessage' });

Upvotes: 2

Zeghra
Zeghra

Reputation: 477

I managed to do that. I made it same as here: https://www.npmjs.com/package/express-messages

   <body>
   <%- messages('my_message_template', locals) %>
   <div id="messages">
     <% Object.keys(messages).forEach(function (type) { %>
       <% messages[type].forEach(function (message) { %>
         <div class="alert alert-<%= type%>">
           <%= message %>
         </div>
       <% }) %>
     <% }) %>
   </div>

And in $.ajax({ success:... I put this line:

$('#messages').load(location.href + " #messages");

So if ajax action was successful, it refreshed the div that id = messages.

In express I have this line:

res.status(200).json({ messages: req.flash('success','Yes! Everythings good')});

In above link, it states <%= type %> (ejs) if message is success or error (ie) and for that the styling is ie:

<style>
      .alert-success{
        color: #3c763d;
        background-color: #dff0d8;
        border-color: #d6e9c6;
      }
      .alert-error{
        color: #a94442;
        background-color: #f2dede;
        border-color: #ebccd1;
      }
</style>

This colors the background to green if message is 'success' or red if it's 'error'

Upvotes: 0

Related Questions