1

it's been one week now that i am struggling with this, I have searching to the internet, but i a am not able to succeed on this.

context : i have a form with 2 select lists. what i want is to use ajax to not have to reload the whole page each time i submit the form and also that the user selection stay keeped.

i can see the exact response i want to display on my page when i am looking to the devtools in firefox. but, the page is not refreshing/displaying the data....

this is my first project with nodejs/ejs/mongodb/ajax , i haven't yet enough experience i think. there are mayebe something i am not understanding on the success/done part of my ajax request... can anyone help me? how to display, render what i can see in the response from the server in my devtool?

server part : the post request: app.js

EDIT : i forgot to mention that i have the following line too: //SETTING BODY-PARSER FOR JSON REQUESTS: app.use(bodyParser.json()); in my app.js file.

app.post('/games-query',urlencodedParser, (req, res) => {
    console.log(req.body);

    let titlepage = 'Games list :';   
    let platform = req.body.platformAjax;
    let genre = req.body.genreAjax;

    console.log('PLATFORM PARAM = '+  platform  );
    console.log('GENRE PARAM = '+  genre  );

    mameGames = [];

if ((genre == "") || (genre == "All")){
    Game.find({gameplatform: platform}).sort({ gametitle: 1 }).limit(100).exec(function (err, games) {
        var count = "results :"+games.length;
        if(err){
            console.error('could not retrieve games from DB');
            res.sendStatus(500);
        }else {
            mameGames = games;
            console.log("GAMES : "+mameGames.gametitle);
            res.render('games', {games: mameGames, count: count, title:titlepage});
        }
        });
}else{

        Game.find({gameplatform: platform, gamegenre:genre}).sort({ gametitle: 1 }).limit(100).exec(function (err, games) {
            var count = "results :"+games.length;
        if(err){
            console.error('could not retrieve games from DB');
            res.sendStatus(500);
        }else {
            mameGames = games;
            // console.log('mameGames : ' + mameGames);
            res.render('games', {games: mameGames, count: count, title:titlepage});
        }
        });
    }
});

the ajax request (in /public/js/posrequest.js) :

$( document ).ready(function() {


    function ajaxPost(){
      const selectForm = document.getElementById('btnquery');
      selectForm.addEventListener('click', (e)=>{
          e.preventDefault();

          let platform = document.getElementById('platformId').value;
          let genre = document.getElementById('genreId').value;

          let payload = {
            platformAjax:platform,
            genreAjax:genre
          }


            // DO POST
            $.ajax({
              type : "POST",
              url : "games-query",
              contentType : "application/json",
              // data : {platformAjax:platform, genreAjax:genre},
              data : JSON.stringify(payload),
              dataType : "json",  
            }).done(function(data){
              $('#gametitle').text(JSON.parse(data.gametitle));

              return;
          });
      });
    }

      ajaxPost();
  });

the ejs file : (in /views/games.ejs) :

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>games</title>
        <link rel="stylesheet" type="text/css" href="https://cdn.rawgit.com/rikmms/progress-bar-4-axios/0a3acf92/dist/nprogress.css" />
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
        <link rel="stylesheet" href="../public/style.css">
        <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

    </head>
    <body>

    <%- include ('./partials/header'); %>

    <h2><%= title %></h2>


        <h4 class="paddingBottom"><%= count %></h4>

    <span class="forms form-group form-inline justify-content-center">
        <div class="arrondi1">
    <form class="form-inline form-search" action="/games" method="post">
        <label for="byname" class="control-label label-padding">By Name:</label>
        <input type="text" id="term" name ="term" class="form-control" placeholder="titre de jeu" width="1000px">
        <button type="submit" class="btn btn-primary" id="btnSearch">Chercher</button>
    </form>
    </div>
    <h5 class="between-forms">OR</h5>
    <div class="arrondi2">
    <form class="form-inline form-selection" id="selectForm" name="selectForm">    
        <label for="platform" class="control-label">By Platform:</label>
        <select id="platformId" name="platformName" class="form-control" onsubmit="return false">
            <option value = "Arcade" selected>Arcade</option>
            <option value = "NeoGeo" >NeoGeo</option>
            <option value = "SMS" >SMS</option>
            <option value = "Genesis" >Genesis</option>
            <option value = "Saturn" >Saturn</option>
            <option value = "DC" >DC</option>
            <option value = "NES" >NES</option>
            <option value = "SNES" >SNES</option>
            <option value = "NGC" >NGC</option>
            <option value = "Wii" >Wii</option>
            <option value = "WiiU" >WiiU</option>
            <option value = "Switch" >Switch</option>
            <option value = "PS1" >PS1</option>
            <option value = "PS2" >PS2</option>
            <option value = "PS3" >PS3</option>
            <option value = "PS4" >PS4</option>
            <option value = "PC" >PC</option>
        </select>
        <label for="genre" class="control-label ">And Genre:</label>
        <select id="genreId" name="genreName" class="form-control" onsubmit="return false">
            <option value = "" selected>All</option>
            <option value = "shmup" >shmup</option>
            <option value = "fighting" >fighting</option>
            <option value = "beatThemUp" >beatThemUp</option>
            <option value = "platform" >platform</option>
            <option value = "lightgun" >lightgun</option>
            <option value = "run&gun" >run&gun</option>
            <option value = "race" >race</option>
            <option value = "flight" >flight</option>
            <option value = "puzzle" >puzzle</option>
            <option value = "pinball" >pinball</option>
            <option value = "sport" >sport</option>
            <option value = "rpg" >rpg</option>
            <option value = "adventure" >adventure</option>
        </select>
        <button type="submit" id="btnquery" class="btn btn-primary">Submit</button>
    </form>
    </div>  
    </span>


    <div class = "main">
        <div class="container">
            <div class="row">





            <% for(game of games){%> 
               <h4 class 'titre' id="gametitle"><a href="/games-details/<%= game._id %>"> <%= game.gametitle %></a></h4>
               <h4 class 'titre' id="gametitleback"><%= game.gametitle %></h4>



                <% }  %> 
    </div>
    </div>
    </div>
    <br>





    <%- include ('./partials/footer'); %>
    <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
    <script src="/public/js/postrequest.js"></script>
    <script>

        let term = document.querySelector('#term'); 
        const btnSearch = document.querySelector('#btnSearch');



    </script>
    </body>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script> 
    <script src="https://cdn.rawgit.com/rikmms/progress-bar-4-axios/0a3acf92/dist/index.js"></script> 
    <script>loadProgressBar()</script>
    </html>

example response i can see in the devtool (it is working)

Edit 2 : I see that it is not obvious to anyone. i am going to isolate my code to see if something else is in the party!

Edit 3 : i have made a ton of new test since i posted it last sunday. Always the same thing..
actually i move the following line :

<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>

into my head html tag as i saw on w3school website.

how could i send the response in my page?

actualy what i saw in the firefox web console when i send DC as platform and All to genre input:

HEADERS:

**Response headers:**

XHRPOSThttp://localhost:3000/games-query
[HTTP/1.1 200 OK 98ms]

URL de la requête :http://localhost:3000/games-query
Méthode de la requête :POST
Adresse distante :[::1]:3000
Code d’état :
200
Version :HTTP/1.1

En-têtes de la réponse (333 o)  
En-têtes bruts
HTTP/1.1 200 OK
X-Powered-By: Express
Access-Control-Allow-Origin: localhost:3000
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept
Content-Type: text/html; charset=utf-8
Content-Length: 32157
ETag: W/"7d9d-m2EHsBSaOIu0E/Jr6q+X8UJQtdo"
Date: Tue, 19 May 2020 22:10:00 GMT
Connection: keep-alive
En-têtes de la requête (604 o)  
En-têtes bruts
Accept  
application/json, text/javascript, */*; q=0.01
Accept-Encoding 
gzip, deflate
Accept-Language 
fr,fr-FR;q=0.8,en-US;q=0.5,en;q=0.3
Connection  
keep-alive
Content-Length  
36
Content-Type    
application/json
Cookie  
hblid=SAF2ExIBZf2cIdPG3m39N0O0…ID=7hvm3c3ie9k4ku9cue18777h82
DNT 
1
Host    
localhost:3000
Origin  
http://localhost:3000
Referer 
http://localhost:3000/games?platform=Arcade
User-Agent  
Mozilla/5.0 (Windows NT 10.0; …) Gecko/20100101 Firefox/76.0
X-Requested-With    
XMLHttpRequest

Parameters:

JSON:
    genreAjax   ""
    platformAjax    "DC"

Transmission de la requete:
    {"platformAjax":"DC","genreAjax":""}

Response / response payload:

<h4 class 'titre' id="gametitle"><a href="/games-details/5ebc645d200af104b4a9938d"> Ready 2 Rumble Boxing: Round 2</a></h4>

2 Answers 2

1

This is because you are using res.render() for an AJAX call, which won't do anything. It only works if you submit the HTML form without page refresh.

So there are actually 2 solutions to this (that I came up with):

  1. Solution 1 (Use normal request i.e. not AJAX and resist the input fields)

You can submit the form without AJAX request, and in the server side retrieve the request body like this:

 let { titlepage, platform, genre } = req.body.platformAjax;

and for the response send these values along the response. For this, do something like:

res.render("games", {
  titlePage,
  platform,
  genre
})

and set these values in your games.ejs as default values for the next render.

You can use Javascript/jQuery to select the option dynamically like $("[option='SMS']").attr("selected", true)

Refer to this for accessing the values in javascript that are passed through EJS

Additional Info: For normal inputs, it is as easy as doing:

<input type="text" name="genre" value="<%= typeof genre != 'undefined' ? genre : '' %>" />

inside your ejs file.

OR

  1. Solution 2

Visit these resources to figure out why in res.render() not changing your HTML:

Sign up to request clarification or add additional context in comments.

Comments

0

Ok,

to make it short the dataType i used inside my ajax request was the problem with render method in nodejs.

so, what i am actually using to make it work :

// DO POST
        $.ajax({
          type : "POST",
          url : "games-query",
          contentType : "application/json",
          data : JSON.stringify(payload),

          success: (data) => {
          console.log('ajax success!' );


          $('.main').html(data);

          }
        });

We can use : dataType : "html" or dataType : "text" or no dataType like i do (because i have read if no dataType is declared jquery will determine the correct dataType : ) :

quote from the jquery documentation :

If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback) are: see the documentation for more here : https://api.jquery.com/jQuery.ajax/

I also tried to replace res.render by res.send() and res.json() from nodejs side but result was not displayed the same (it was the whole object) or give me each object no readable : [object : object ].

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.