Regarding the iteration query in node.js with mysql - javascript

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.

Related

JS to PHP SyntaxError: Unexpected token N in JSON at position 0

I'm having some issues with Ajax POST and sending an array as a JSON.
I firstly get my data externally break it apart a little and then send it to my function.
const getPrices = async () => {
const now = Epoch(new Date());
var company1 = $('#fcomp').val();
var company2 = $('#lcomp2').val();
console.log("Company1 =", company1);
console.log("Company2 =", company2);
const response = await fetch("https://alpha-vantage.p.rapidapi.com/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol="+company1+"&outputsize=compact&datatype=json", {
"method": "GET",
"headers": {
"x-rapidapi-key": "f16d556786msh84b3a1e5cb78a33p172e62jsnb2827ccaab51",
"x-rapidapi-host": "alpha-vantage.p.rapidapi.com"
}
});
await delay(5000);
console.log("Waited 5s for API rules");
const response2 = await fetch("https://alpha-vantage.p.rapidapi.com/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol="+company2+"&outputsize=compact&datatype=json", {
"method": "GET",
"headers": {
"x-rapidapi-key": "f16d556786msh84b3a1e5cb78a33p172e62jsnb2827ccaab51",
"x-rapidapi-host": "alpha-vantage.p.rapidapi.com"
}
});
const Prices = await response.json();
const Prices2 = await response2.json();
const just_prices = Prices["Time Series (Daily)"];
const just_prices2 = Prices2["Time Series (Daily)"];
sendToPHP(company1,just_prices);
sendToPHP(company2,just_prices2);
this then sends (Or Should Send) the company code and the array
function sendToPHP (company,json){
console.log("Attempting POST" );
$.ajax({
type : "POST", //type of method
url : "daily_push.php", //your page
dataType: 'json',
data : { company : company, json : json },// passing the values
success: function(res){
console.log("Successful POST Response:", res );
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("Error Occured in POST: ", errorThrown);
console.log("Error Occured in POST: ", textStatus);
console.log("Error Occured in POST: ", XMLHttpRequest);
console.log("JSON: ", json);
}
});
}
im Debugging in Chrome Dev and am getting this responce:
"SyntaxError: Unexpected token N in JSON at position 0"
I dump my Data Afterwards and it all Looks OK!?
Im a little stumped now after searching around for an hour or so....
If I have missed something glaringly obvious I can only appologies for wasting your time!
EDIT 1:
More info (Prices Ouput)
here is the output from Prices:
[]
Still not sure what is going on with it? hey all seem to be Objects. ONly thing I can think is that I need to maybe unpack each indevidual object thats held in tha dates then pass it back?
The issue I was having is I was Sending dataType: 'json', whereas it should have been dataType: 'html', This then gets recieved by the PHP script and Successfully responds.
See image.
$.ajax({
type : "POST", //type of method
url : "daily_push.php", //your page
dataType: 'html',
data : { company : company, json : json },// passing the values
success: function(res){
console.log("Successful POST Response:", res );
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("Error Occured in POST: ", errorThrown);
console.log("Error Occured in POST: ", textStatus);
console.log("Error Occured in POST: ", XMLHttpRequest);
console.log("JSON: ", json);
}
});

Submitting a From to a REST API using JQuery does not work

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

Method being called before Promise is complete

I am attemting to add an item to a sharepoint list from an Apache Cordova application. It first prompts the user to login then it will make a HTTP Post to so the data entry.
I have the following code:
function saveToSharepoint(data) {
var authority = "https://login.microsoftonline.com/common/";
var authContext = new Microsoft.ADAL.AuthenticationContext(authority);
var authResult = authContext.acquireTokenAsync("https://my.sharepoint.com", "4be098f8-2184-4831-9ef7-3d17dbbef6a0", "http://localhost:4400/services/office365/redirectTarget.html")
.then(FormatAndUpload(authResult, data), errorCallback);
}
function FormatAndUpload(authResponse, data) {
var token = authResponse.accessToken;
var expiry = authResponse.expiresOn;
console.log("Token acquired: " + authResponse.accessToken);
console.log("Token will expire on: " + authResponse.expiresOn);
$.ajax({
url: "https://my.sharepoint.com/_api/web/lists/getbytitle('" + Test + "')/items",
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(data),
headers: {
"Accept": "application/json;odata=verbose",
"Authoriztion":"Bearer " + token
},
success: function (data) {
success(data);
},
error: function (data) {
failure(data);
}
});
}
The problem I am having is that the FormatAndUpload method is being called before acquireTokenAsync has completed, so the authResponse variable passed into the FormatAndUpload method is null.
I'm not too familiar with the promise framework in Javascript/JQuery but I was under the impression that the event should only fire on completion of the previous method.
Does anyone have any pointers in how I can correctly wait for the login to complete before attempting the POST?
what you did FormatAndUpload(authResult, data); is wrong the correct way to pass a callback is
.then(function(authResult){
FormatAndUpload(authResult, data);
}, errorCallback);
so your saveToSharepoint will be like this
function saveToSharepoint(data) {
var authority = "https://login.microsoftonline.com/common/";
var authContext = new Microsoft.ADAL.AuthenticationContext(authority);
var authResult = authContext.acquireTokenAsync("https://my.sharepoint.com", "4be098f8-2184-4831-9ef7-3d17dbbef6a0", "http://localhost:4400/services/office365/redirectTarget.html")
.then(function(authResult){
FormatAndUpload(authResult, data);
}, errorCallback);
}
Thanks for the answer Newbee Dev, you were correct in that I didn't formulate the then method correctly.
For any others who see this regarding SharePoint, I actually reformatted the code for it to work as expected, so the saveToSharepoint method looks like so:
function saveToSharepoint(data) {
var AuthenticationContext = Microsoft.ADAL.AuthenticationContext;
AuthenticationContext.createAsync("https://login.microsoftonline.com/common/")
.then(function (authContext) {
authContext.acquireTokenAsync(
"https://my.sharepoint.com", // Resource URI
"4be098f8-2184-4831-9ef7-3d17dbbef6a0", // Client ID
"http://localhost:4400/services/office365/redirectTarget.html" // Redirect URI
).then(function (authResult) {
FormatAndUpload(authResult, data);
}, function (err) {
console.log(err);
});
}, function (err) {
console.log(err);
});
}
The main thing to note is creating the AuthenticationContext asynchronously and this way, the FormatAndUpload calls after the whole login process is complete. Just thought I would post this for other people who see this regarding Sharepoint and are stuck.

AJAX call and getting return data in Node

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)};

can't get return value in nodejs?

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);
});

Categories