问题: -
我想从表单中插入数据并将所有数据显示回数据网格。目前,我可以正确地插入和检索数据库中的数据,但无法将其发送到客户端ajax调用。
我尝试了多种解决方案但没有得到最佳解决方案。 我希望你们能帮助解决这个问题。
App.js(服务器文件)
var express = require("express"),
app = express(),
bodyParser = require("body-parser"),
mysql = require("mysql");
app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({extended: true}));
app.use( bodyParser.json());
app.use(express.static(__dirname + '/public'));
app.post("/posts", function (req, res) {
console.log("Posts Api called from Admin.!");
var sql = "INSERT INTO post_master (title, description, user_id, created_by, comments, category, created_date) " +
"values (?, ?, ?, ?, ?, ?, ?)";
connection.query(sql, [req.body.news_title, req.body.description, null,null, null, null, req.body.news_date ], function (err, res) {
if(err){
console.log("Something went wrong while inserting data.!");
console.log(err);
} else {
console.log("Data successfully inserted.!");
// I want to load all data and return back to ajax call.
var fetchPosts = "select * from user_master where user_name= ? AND password= ?";
connection.query(fetchPosts, function (err, posts) {
console.log("Data successfully fetch and passing to ajax call back.!");
// Error while sending
res.send(posts); // Error :- res.send is not a valid function.
});
}
});
});
Posts.ejs
var requestMedia = $.ajax({
url: "/posts",
type: "POST",
data: JSON.stringify(postData),
dataType: "json",
contentType: "application/json",
headers: headerSetting
});
// Not getting data from server app.js file.
requestMedia.done(function (data) {
console.log("Ajax post response data : " + data);
return;
});
requestMedia.fail(function (jqXHR, textStatus) {
alert("fail");
return
});
如果您仍然有任何问题需要了解问题,请告知我们。