Nilesh Jain
Nilesh Jain

Reputation: 116

GET json data with jquery ajax call to nodejs

I am sending data using Nodejs res.end() in JSON format, and I am also setting headers as application/json and but I am not getting the data in the success function of jquery ajax call, instead I am getting the data directly in JSON format, but I want it to come in the success function of jquery ajax call as I have to display them in datatable. I even tried res.render() and res.send() but not able to get it. please help!!

Nodejs code

router.get('/user_list',(req,res,next)=>{
   let new_password = generator.generate({
        length: 16,
        numbers: true,
        symbols: true,
        uppercase: true,
        strict: true,
        exclude: ["(",")","[","]",":","-",",","{","}","<",">",".","^","/"]
      });
  connection.query("update user, client set user.status = client.status where user.client_id = client.id",(error,result)=>{
    if(error){
      console.log(error);
    }else{
      connection.query('select user.username,user.email,user.msg_id,user.status,system.name from user inner join system on user.system_id = system.id; select id, name from client;',(error,result)=>{
        if(error){
          console.log(error);
        }else{
          let value = {values: result,new_password};
          //res.json(value);
         // res.render('user_list', {user_data: value});
          res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify(value));
        }
      })
    }
  })
})

JQuery Code

$(document).ready(function(){
      $.ajax({
        url:'user_list',
        type:'GET',
        //dataSrc: 'user_list',
        datatype:'json',
        success: function(data){
          console.log(data);
          $('#example').dataTable({
            data:data,
            columns: [
              {data:'values[0][1].username'},
              {data:'values[0][1].name'},
              {data:'values[0][1].email'},
              {data:'values[0][1].msg_id'},
            ]
          });
        }
      });
    });

Upvotes: 1

Views: 1615

Answers (1)

user5734311
user5734311

Reputation:

Please try this so we can narrow down the problem:

router.get('/user_list', function (req, res) {
    const list = [
        { id: 0, name: "Alice"},
        { id: 1, name: "Bob"}
    ];
    res.send(list);
});

In your index/script:

$(document).ready(function () {
    $.getJSON('user_list').then(res => {
        console.log(res);
    });
});

This should display the Array in the console.

Upvotes: 1

Related Questions