cjenwere4
cjenwere4

Reputation: 35

My GET request is executing exactly twice

So I'm performing a GET request in jQuery and for some it executes exactly twice. The first time it gets the appropriate data and the second time gets an empty object. Because that empty object is being passed into a EJS file, my code is throwing an error. I really don't understand why it's happening. I've tried to catch the empty object but that makes my web-app hang. I've tried to bind and the click event, but to no avail. Here is output that it is producing and the code I've written. Any help is appreciated

Output:

[nodemon] restarting due to changes...
[nodemon] starting `node app.js`
Listening to port 8081
app.get
reply get requested
found
[
  {
    replies: [
      'fight me bro',
      'boss main',
      'kinda slow innit'
    ],
    _id: 5e0cb67b48dfda4448c57ec0,
    msg: 'if you can',
    likes: 2,
    date: '1/1 @ 9:10',
    seconds: 51,
    __v: 0
  }
]
reply get requested
found
[]

You can see at the second reply get requested, the object logged is empty.

JQuery Code

    $('.bubble.sender.first.animate-bottom').on('click', function(){ // hit bubble to reveal replys
      console.log("bubble clicked.");
      var message = $(this).find('input.hiddentag').val(); // gets the message
      var replydate = $(this).find('input.hiddendatetag').val(); // gets the date

      console.log("message: " + message);

      var chat = {msg: message, date: replydate};
      console.log(chat);

      $.ajax({
        type: 'GET',
        url: '/reply',
        data: chat,
        success: function(data){
          console.log("Heading to appropriate reply page.....");
          window.location.replace("/reply");
        }
      });
      return false;

    });

Node JS Code


app.get('/reply', function(req, res){
    console.log("reply get requested");
    // console.log("message: ", req.query);

    chats.find({msg: req.query.msg, date: req.query.date}, function(err, data) {
        if (err) {
            console.log("couldn't find chat");
            throw err // crash
        }
        console.log('found');
        console.log(data);
        res.render('reply', {chat: data});

    })
})

EJS Code:


                <% for(var i = 0; i < chats.length; i++) { %> <!-- earlier chats go first-->
                    <% if (i % 2 == 0) { %>
                        <div class="bubble recipient first animate-bottom">
                            <li class = "display"><%= chats[i].msg %> &nbsp; &nbsp;
                                <i class="fas fa-heart liked" aria-hidden="true"></i> <sub><%=chats[i].likes%></sub> &nbsp; &nbsp; &nbsp; &nbsp;
                                <i class="fa fa-reply reply"></i>
                                <input type="hidden" id = "changeit" class = "likebutton" value = "<%=chats[i].likes%>" > 
                                <input type="hidden" class = "hiddentag" value="<%=chats[i].msg%>"> <!-- needed to get the message that was liked-->
                                <input type="hidden" class = "hiddendatetag" value="<%=chats[i].date%>"> <!-- needed to filter messages that are the same-->
                            </li>
                            <br>
                            <span>Sent: <%=chats[i].date %> </span>
                        </div>
                    <% } else { %>
                        <div class="bubble sender first animate-bottom">
                            <li class = "display"><%= chats[i].msg %> &nbsp; &nbsp;
                                <i class="fas fa-heart liked" aria-hidden="true"></i> <sub><%=chats[i].likes%></sub> &nbsp; &nbsp; &nbsp; &nbsp;
                                <i class="fa fa-reply reply"></i>
                                <input type="hidden" id = "changeit" class = "likebutton fas fa-heart" value = "<%=chats[i].likes%>" > 
                                <input type="hidden" class = "hiddentag" value="<%=chats[i].msg%>"> <!-- needed to get the message that was liked-->
                                <input type="hidden" class = "hiddendatetag" value="<%=chats[i].date%>"> <!-- needed to filter messages that are the same-->
                            </li>
                            <br>
                            <span>Sent: <%=chats[i].date %> </span>
                        </div>
                    <% } %>
                <% } %>

Upvotes: 0

Views: 275

Answers (1)

jfriend00
jfriend00

Reputation: 707158

You are calling your server twice, both times with the /reply route. Once with the ajax call and once with window.location.replace(...).

You send an Ajax call to /reply. That hits the app.get('/reply', ...) route.

Then in the success handler for the Ajax call, you do:

window.location.replace("/reply");

which tells the browser to go to the /reply URL. That will again hit the app.get('/reply', ...) route and give you your second set of logs for that route.

So, that explains "why" you see two sets of logs and why the route is hit twice. Now, the question is how to do what you're really trying to accomplish without hitting the server twice? Since this is just a GET, it seems like you should probably just build the same URL that the ajax call is building and just do something like this:

 window.location = `/reply?msg=${message}&date=${replaydate}`;

or whatever it takes to properly construct the desired URL. That will get the same data to your EJS template to construct the desired web page and then display the result in the browser and will only call your server once.

And, then skip the Ajax call entirely because you're not using its results anyway. The rendered web page from the Ajax call is just thrown away. The ajax call does absolutely nothing useful.

Upvotes: 2

Related Questions