yaytip
yaytip

Reputation: 11

I try to send JSON in node js to client, but it does not work

Server site:
app.post('/myaction', async function(req, res) {
 async function next_func(req, res){
  var st = req.body.status;
  var myJson =  await show();
  return myJson;
  }
 dataJ =  await next_func(req, res);
 try {
     dataJson = JSON.parse(JSON.stringify(dataJ));
 } catch (e) {
     console.log("parse error");
 }
 if( isJSON(JSON.stringify(dataJ))) console.log("be Json ");
 else console.log("not Json  ");
 console.log("send JSON : "+JSON.stringify(dataJ));
 console.log("type JSON : "+typeof JSON.stringify(dataJ));
 console.log("dataJson : "+dataJson);
 console.log("type dataJson : "+typeof dataJson);
 res.status(200);
 res.setHeader('Content-Type', 'application/json');
 res.send(dataJson);
});
async function show(){
  var con = mysql.createConnection({
  host: "127.0.0.1",
  user: "root",
  password: "aaaaaaaa",
  database: "doto"
  }); 
  var sql ="select * from task_list";
  resultsArray = [];
  await new Promise((resolve, reject) => {
  con.connect((err, connection) => {
    if (err) return reject(err)
    con.query(sql, (err, rows, fields) => {
         if (err) return reject(err)
         resolve(
             rows.forEach( (row) => { 
             resultsArray.push(
             {detail:row.details, status:row.status, subject:row.subject}
             );
         })  
       )
     })
    })
  })
  return  resultsArray;
}
function isJSON(str) {
  try {
    return (JSON.parse(str) && !!str);
  } catch (e) {
    return false;
  }
}
Cleint site
$.fn.ajaxShow = function(st) {
xhrct =  $.ajax({
                    type: 'POST',
                    dataType: "json",
                    data : {
                          status : st
                          },
                    url: 'http://127.0.0.1:8081/myaction',                      
                    success: function (data) {  
                        alert("function");
                               $('#tb').empty();
                               if(data!=null) {
                                 var fotoData = $.parseJSON(data);
                                  $(fotoData).each(function (i, obx) {
                                        alert("fotoData");
                                        $('#tb').append('<tr>') 
                                          .append('<td>'+obx.detail+'</td>'
                                          .append('<td>'+obx.status+'</td>')
                                         .append('<td>'+obx.subject+'</td>')
                                          .append('</tr>');
                                        });
                                      }
                        },
                    error: function(XMLHttpRequest, textStatus, errorThrown) 
                    {    
                     alert("XMLHttpRequest:"+XMLHttpRequest.responseText);
                     alert("textStatus: "+textStatus);
                     alert("errorThrown: "+errorThrown);
                     }
                });
 }

I try to send JSON to client but client alert XMLHttpRequest is null ,textStatus:error and errorThrown is null. At console, it display 'be Json' and type of dataJson is an object and send JSON :

[{"detail":"detl0","status":"N","subject":"subj0"},{"detail":"detl1","status":"Y","subject":"subj1"}] 

pls help me

Upvotes: 0

Views: 245

Answers (1)

Ankit
Ankit

Reputation: 990

Try to add a content-Type and stringify the object you are sending:

 data: JSON.stringify({status : st}),
 contentType: "application/json"

Upvotes: 2

Related Questions