NodeJs : Handling an AJAX call

Making AJAX calls to server is now a common things in web applications because it provide a better user experience than refreshing a complete page.

Here is a simple HTML page with a text box to search, when user type something in that and press enter an AJAX call will be sent to server


Here is the HTML

<!DOCTYPE html>
<html>
    <head>
        <style>
            #search {
                  text-align: center;
                  width:500px;
                  height: 70px;
                  font-size:3.5em;
                  border-radius:8px;
            }        
        </style>        
    </head>
    <body>      
        <input type="text" name="input" value="Search" id="search"/>
        <div id="results">        
        </div>       
        <script src="jquery-1.11.3.js"></script>
        <script src="main.js"></script>
    </body>   
</html>

Here is the javaScript code for making the AJAX call.

$(function(){
 $('#search').on('keyup', function(e){
   if(e.keyCode === 13) {
       console.log("pressed enter")
     var parameters = { search: $(this).val() };
       $.get( '/searching',parameters, function(data) {
       $('#results').html(data);
     });
    };
 });
});

It will get the content of element which has Id "search" and call URL "/searching" . So a route should be configured in server for "/searching". Response from the server will be displayed in the element with id "results .
Here is how it can be done.

app.get('/searching', function(req, res){
    var val = req.query.search;
    
    // url used to search yql
    items={ films:["film1","film2","film3"],
            games:["game1","game2","game3"],
            songs:["song1","song2","song3"],
            arts:["art1","art2","art3"]
          };
    output="";
    section=items[val.trim().toLowerCase()];
    if(section){        
        for(i=0;i<section.length;i++){
            output+=section[i]+"<br/>";
        }
    }
    else{
        output="Category cannot be identified";
    }
    res.send(output);
  // pass back the results to client side  

});

In here if user search for films, games, songs or arts relevant array will be sent with response. If user search for something other than previous categories string "Category cannot be identified" will be sent.

Note: If you are using a separate script files that should be loaded give a static file path to server using app.use(express.static('scripts')); (see previous post)

Here is the complete NodeJs server code

var express=require('express');
var app=express();
app.use(express.static('scripts'));

app.get('/',function(req,res){
      res.sendFile(__dirname + "/index.html");
});

app.get('/searching', function(req, res){
    var val = req.query.search;    
    // url used to search yql
    items={ films:["film1","film2","film3"],
            games:["game1","game2","game3"],
            songs:["song1","song2","song3"],
            arts:["art1","art2","art3"]
          };
    output="";
    section=items[val.trim().toLowerCase()];
    if(section){        
        for(i=0;i<section.length;i++){
            output+=section[i]+"<br/>";
        }
    }
    else{
        output="Category cannot be identified";
    }
    res.send(output);
  // pass back the results to client side  

});

var server=app.listen(3000,function(){
 console.log('listening');
});

Please add a comment if this was useful or you have something to add.

No comments:

Post a Comment