Retrieve data from a post method of express with jquery

Issue

I am using express.js for a dynamic website, and I decided to use jQuery to send the post method, so that I can create multiple buttons and send different information depending on the button pressed by the user on one and same page.
Here is my simplified environment :

html file :

<% if(alert) { %>
<div class="alert info"><i class="fas fa-info-circle"></i> Si tu viens de souscrire à un abonnement, patiente une à deux minutes.</div>
<% } %>

<form>
  <input id="premiumKey" placeholder="Enter your key here !"></input>
  <input id="save-button-key" class="sub save key" type="button" value="Save"></input>     
</form>   

<script type="text/javascript">
    $('#save-button-key').click(function(){  

    let key = document.getElementById("premiumKey").value
   $.ajax({ 
         url: '/profil/premium',
         type: 'POST',
         cache: false, 
         data: { premiumKey: key, input: 2 }, 
         success: function(data){

         }
         , error: function(jqXHR, textStatus, err){

         }
      })
   });            

</script>

express.js file :

  const renderTemplate = async (res, req, template, data = {}) => {

    const baseData = {
      bot: client,
      path: req.path,
      user: req.isAuthenticated() ? req.user : null,
    };
    // We render template using the absolute path of the template and the merged default data with the additional data provided.
    res.render(path.resolve(`${templateDir}${path.sep}${template}`), Object.assign(baseData, data));
  };


  app.get("/profil/premium", async (req, res) => {
    
    renderTemplate(res, req, "profil/premium.ejs", { alert: null });
  });

  app.post("/profil/premium", async (req, res) => {
    console.log(req.body)
    console.log(req.body.premiumKey)

    var user = req.user;

    let alert = true;
    renderTemplate(res, req, "profil/premium.ejs", { alert });
  });

What i would like
I would like to recover when I press the button, the alert that I get with the post method in the express file. I can display what ajax sends to the server, but I can’t do the reverse during a post method. For example, I would like to analyze the information, and return the result to the user.
I can’t do it so far.

Thank you again for your help.

Solution

I suggest to you, send the response using json.
Instead of render a templete

renderTemplate(res, req, "profil/premium.ejs", { alert });

Send de data in json format

const alertData = {
value: 1,
otherValue: "the alert data"
};
res.json(alertData);

Then in the front, in jquery, in the succes function you will recieve the data

$.ajax({ 
         url: '/profil/premium',
         type: 'POST',
         cache: false, 
         data: { premiumKey: key, input: 2 }, 
         success: function(data){
            console.log(data); // data from the server
            //here you can use the data

         }
         , error: function(jqXHR, textStatus, err){

         }
      })
   });     

Answered By – Denes

Answer Checked By – David Marino (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.