I have following tutorial how to request value from node js and return back to user requested but not successful.
here my javascript code..
put('id','coment',function(data) {
var obja = JSON.parse(data);
var items = Object.keys(obja);
items.forEach(function(item) {
alert(obja[item].field1); //its no result value
});
})
function put(id, data, callback) { //call from here to nodejs
$.ajax('http://localhost:8000/' + id + '/', {
type: 'POST',
data: JSON.stringify(data),
dataType: 'json',
success: function(data) { if ( callback ) callback(data); },
error : function() { if ( callback ) callback(false); }
});
}
and here my nodejs
connection.query("SELECT field1,field2,field3 from table", function(e, row) {
if(e)
{
console.log('An error occured: '+e)
}
else
{
try{
res.write(JSON.stringify(row)); //send value back to user requested
res.end();
}catch(ex){
console.log('errror' + ex) ;
}
}
});
in console, the query was load normally but when I try send back to user requested, it gets no value.
My problem is, why can't I send back to user requested?
You shouldn't need var obja = JSON.parse(data); because it will already be parsed by jQuery due dataType: 'json' being set.
Also based on the code you've shown obja is an Array so instead of this:
var items = Object.keys(obja);
items.forEach(function(item) {
alert(obja[item].field1);
});
Just do this:
obja.forEach(function(row){
alert(row.field1);
});
Related
I am doing a simple function to update a field in the database and I get this error:
Failed to load resource: the server responded with a status of 403 (Forbidden)
I do the request in html/Jquery:
function AgregarLike(id, num){
alert("Entre:" + id);
var urlAction = "#Url.Action("UpdateLikeVisitBrandPhoto", "Report")";
alert (urlAction);
var request;
// Fire off the request to /form.php
request = $.ajax({
url: urlAction + '/' + id,
type: "post"
});
// Callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
// Log a message to the console
console.log("Hooray, it worked!");
console.log(response);
console.log(textStatus)
alert("worked");
});
}
And the controller (I return all the time bu.CreateLike(Id) because I want to forze the error):
public int UpdateLikeVisitBrandPhoto(int id)
{
try
{
try
{
var num = bu.CreateLike(id);
}
catch
{
return bu.CreateLike(id);
}
return bu.CreateLike(id);
}
catch (ServicesException ex)
{
logger.Error("", ex);
Console.WriteLine(ex);
return bu.CreateLike(id);
}
catch (Exception ex)
{
logger.Error("", ex);
Console.WriteLine(ex);
return bu.CreateLike(id);
}
}
And the model:
public int CreateLike(int id)
{
using (var sqlConnection = DatabaseUtilities.GetConnection())
{
var SQL = "UPDATE [RBAcuerdos].[dbo].[VisitBrandPhoto] SET MeGusta = 1 WHERE id = #paramId";
var sqlCommand = new SqlCommand(SQL, sqlConnection);
sqlCommand.Parameters.Add(new SqlParameter("paramId", id));
//sqlCommand.Parameters.Add(new SqlParameter("paramvalue", 1));
return sqlCommand.ExecuteNonQuery();
}
//throw new NotImplementedException();
}
Someone can help me please?
Since you're sending a POST request, the parameters you need to send should not be a part of the URL. Try sending the parameters like:
request = $.ajax({
url: urlAction,
data: {id: id},
type: "POST",
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert("It worked!");
},
error: function () {
alert("Error");
}
});
Further Reading:
How to pass parameters in $ajax POST?
request = $.ajax({
url: urlAction + '?id=' + id,
type: "get"
});
Substitute your code
var urlAction = "#Url.Action("UpdateLikeVisitBrandPhoto", "Report")";
It generates
/Report/UpdateLikeVisitBrandPhoto
To hit controller you need your url to be
/Controller/Action?param1=paramvalue //single param
/Controller/Action?param1=paramvalue ¶m2=paramvalue //multiple params,apppend each paramname with prefix &
In server side,I fetch data from database
var sql = require('mssql');
app.get('/api/comments', function(request, response) {
var sqlConfig = {
// Connection string parameters.
}
sql.connect(sqlConfig, function() {
var request = new sql.Request();
var stringRequest = 'select TOP 10 * from comment';
request.query(stringRequest, function(err, recordset) {
if(err) console.log(err);
sql.close();
response.json(recordset);
});
});
});
Then,I fetch the data from server side by AJAX (get method)
_fetchComments() {
jQuery.ajax({
method: 'GET',
url: '/api/comments',
success: (comments) => {
this.setState({ comments })
}
});
I get an error when I get the data by Ajax.
(Uncaught TypeError: this.state.comments.map is not a function)
It seems that the data return is undefined.Instead of fetching database,the code is work if I use static data(hard code) in server side.
I think the problem is the callback function in sql.connect() but I have no idea how to solve it.Does anyone can help?
Error:
The solution is adding dataType: 'json' to the ajax
_fetchComments() {
jQuery.ajax({
method: 'GET',
url: '/api/comments',
dataType: 'json',
success: (comments) => {
this.setState({ comments })
}
});
}
I have a REST API running and I am posting some data to it using JQuery.
This is how my JQuery code looks:
$(document).ready(function () {
$('#login-form').submit(function () {
var user = $('#uname').val();
var pass = $('#pwd').val();
alert('username = ' + user);
alert('password = ' + pass);
var JSONObject = { 'userName': user, 'password': pass };
var jsonData = JSON.parse(JSONObject);
$.ajax({
url: 'http://127.0.0.1:8080/user/login',
method: 'POST',
data: { userName: user, password: pass },
dataType: 'JSON',
contentType: 'application/json',
success: function (data, status, jqXHR) {
//Do something
console.log('data = ' + data);
},
error: function (jqXHR, status, errorThrown) {
alert('error ' + errorThrown);
}
});
});
});
However, this code is unable to access the API. I do not get the expected message in the server log.
When the Submit button of the form is clicked, the browser gets reloaded and it shows the form inputs in the url. That is all.
My API is written using Java and this is the relevant method.
#RequestMapping(value = "/user/login", method = RequestMethod.POST)
public ResponseEntity<User> logUser(#RequestBody User user){
User loggedUser = loginService.authenticateUser(user);
if(loggedUser != null){
System.out.println("User found");
return new ResponseEntity<User>(loggedUser, HttpStatus.ACCEPTED);
}else{
//user does not exsits
System.out.println("User not found");
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
}
I really can't understand what is wrong. No any error is shown. Can somebody point me out why this happens and how to fix this issue.
The issue is that the browser is reloading on submit event.
You need to add preventDefault() method like this
$("#login-form").submit(function (event) {
event.preventDefault()
//further code here
This will prevent the browser from reloading
After the update request is sent, I would like to get a success/fail response.
Regarding the response, I have to receive the one response after all update query is performed.
How to receive the one response?
The following code is my node.js server example.
Thank you!!
$.ajax({
url: "http://127.0.0.1:62590/updatingResourceList",
type: "put",
dataType: "text",
cache: false,
timeout: 30000,
data: JSON.stringify(jsonObject),
contentType: "application/json",
success: function (data) {
alert("Success updating the resource");
}, error: function (xhr, textStatus, errorThrown) {
alert(textStatus + ' : ' + errorThrown);
}
});
=========================================================================
app.put('/updatingResourceList', function (request, response) {
var resultObj = request.body;
var updatedIDList = resultObj['idList'];
// Updating the user request format
var idCounting = 0;
for(var i = 0; i < updatedIDList.length; i++) {
var latest = timestamp();
var resourceName = updatedIDList[i];
var client = dbClient.getDBClient(); // Getting Database information.
client.query('UPDATE testset SET time=? WHERE resourceName=?', [latest, resourceName], function (error, results, fields) {
if (error) { // error
console.log("MySQL : Database resource update error : " + error);
response.status(500).end();
} else { // success
console.log('MySQL : Success updating the resource : ' + resourceName);
response.status(200).end();
}
});
}
});
The problem is that you are sending back a response at each iteration of the loop. If you want a single response, then do it only after the loop. In the loop keep track of the results of the update in an array (key should be the resourceName), and send back the results in one go, perhaps as a json object.
What you need to decide, however, is how to handle if only some of the updates are successful. You either have to return an OK (status code 200), or an internal error at the end.
I'm wanting to make an ajax call from the client to the backend. I get a successful call from the success function, however, I can't understand how I get data from the server to return from the client.
currently my error trying to use res.send is:
Error: Can't set headers after they are sent.
AJAX
function getProfessorResults() {
var textData = $('#inputsm').val();
var data = {user:"gopal#gmail.com"};
$.ajax({
url: 'http://localhost:3000',
data: { theme: "somevalue", snippet: { name: "somename", content: "somevalue" } },
method: 'POST',
async: false,
cache: false,
timeout: 5000,
contentType: "application/json",
success: function(data) {
console.log("success");
},
complete: function(data) {
console.log("completed");
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Error connecting to the Node.js server... ' + textStatus + " " + errorThrown);
}
});
}
JS Backend
exports.home = function(req, res) {
function passList(profArray, callback) {
setTimeout(function () {
callback(profArray);
}, 1000);
}
function getProfs(teacher_name, successCallback) {
google.resultsPerPage = 10
var nextCounter = 0
google(teacher_name, function (err, res){
if (err) console.error(err)
var teacher_results = []; //Hold all the teachers returned from the function
for (var i = 0; i < res.links.length; ++i) {
var link = res.links[i];
if (!link.title.includes('Add') || !link.title.includes('RATINGS') || !link.title.includes("Hint")) {
teacher_results.push(link.title);
}//End if for comparisons ||
} //End For
successCallback(teacher_results);
}); //End google function
teacher_results = ['tester1', 'tester2'];
successCallback(teacher_results);
} //End searchForProfessor
getProfs(teacher_name, function(data) {
prof_list = data;
console.log(prof_list);
return true;
});
if (req.method == 'POST'){
console.log("true");
// dataReceived = JSON.parse(req);
// console.log(dataReceived);
var obj = {
tid: 'ryan'
};
res.send(JSON.stringify(obj));
}
res.render('home', {
profs: prof_list,
dataStuff : dataReceived
});
};
In the backend, you should have some route where your AJAX call lands. In there, you can invoke send on your response.
In node.js/express, this would look something like
app.get('/ajaxURL', function (req, res) {
res.send('I want this string to return to the client');
});
To access the data from the frontend, access it in your AJAX callback:
$.ajax({url: '/ajaxURL'}).done(function (data) {
console.log(data);
});
I am not getting the context properly but you can figure out by this example .
Sending data from server
response.send("Your data");
Access this data in your client in success method of AJAX:
success:function(data){console.log(data)};