when i try and do the post, the data is send and the server receives it but the success function is never called. The connection appears in the network inspector tab of chrome as stalled and, a warning: connection is not finished yet.
script:
var modif = {
CRN: $("#DIAS").parent().parent().parent().children()[0].children[0].innerText,
DIAS: $("#DIAS").val(),
start_hr: $("#STRHR").val(),
end_hr: $("#ENDHR").val(),
title: $("#TITLE").val()
}
$.ajax({
url: '/cmanager/edit',
dataType: 'text',
type: 'POST',
data: modif,
success: function (order) {
alert("functiono!");
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Error, status = " + textStatus + ", " +
"error thrown: " + errorThrown
);
server:
app.post("/cmanager/edit",function (req, res) {
var CRN = req.body.CRN;
var DIAS = req.body.DIAS;
var start_hr = req.body.start_hr;
var end_hr = req.body.end_hr;
var title = req.body.title;
console.log(CRN);
console.log(DIAS);
console.log(start_hr);
console.log(end_hr);
console.log(title);
var usrq = "update section natural join class set DIAS = '"+DIAS+"', start_hr = '"+start_hr+"', end_hr = '"+end_hr+"', title = '"+title+"' where CRN = '"+CRN+"';";
connection.query(usrq, function (error, results, fields) {
if (error)
console.log(error.code);
else
try {
console.log("hello");
} catch (error) {
console.log("bad ifo by client");
}
});
})
Nowhere in your server are you actually sending any data back to the client.
In your server, you need to call res.end() at a minimum. It looks to me what you actually want is res.sendStatus(204);.
Also note that you are wide open to SQL injection attacks, and you will be hacked if you haven't been already. Always use parameterized queries to avoid this problem entirely.
Related
I need some help here:
When I use debugger, everything works, but when debugger is not used, it not working.
When getAjax function is not called to get data from local server, then it the program is working and it can send mail
function sendMessage(headers_obj, message, callback) {
var pGmail = $('#compose-to').val();
getAjax(pGmail).then(result => {
var email = '';
message = encryptText(result, message);
for (var header in headers_obj) {
email += header += ": " + headers_obj[header] + "\r\n";
}
email += "\r\n" + message;
alert(email);
if(email!=null|| email!=''){
var mail = encodeBase64(email);
var sendRequest = gapi.client.gmail.users.messages.send({
'userId': 'me',
'resource': {
'raw': mail
}
})
sendRequest.execute(callback)
}
})
}
function getAjax(pGmail) {
return new Promise((resolve) => {
$.ajax({
url: 'http://localhost:7777/' +
'?pmail=' + pGmail + '&method=where', success: function (result) {
return resolve(result);
}
})
});
}
Trick lies in the time delay.
When I use debugger, everything works, but when debugger is not used, it not working
When you are in Debug mode, the getAjax call is able to complete its request and the response is arrived. Since while debugging there is a small time delay for us to step over to next line of code.
When getAjax function is not called to get data from local server, then it the program is working and it can send mail
Obviously there is no need to of time delay here, since you are not calling getAjax function.
Few Solution Approaches
Option 1 : Make it synchronous
Even though the getAjax is an asynchronous call, we can wire up the email sending code in the response of getAjax call, thus making it synchronous,
Option 2 : Introduce a time delay between getAjax and email sending code.
Please note in this approach, the time delay which might be higher or lower than the time taken by getAjax function and in some cases it may fail, if the getAjax call doesn't respond within in the time delay.
Choose the option which suits best for your scenario.
Hope it helps!
var mysql = require('mysql');
var http = require("http");
var url = require("url");
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "1234",
database: 'publickeyserver'
});
con.connect(function (err) {
if (err) throw err;
console.log("Connected!");
});
http.createServer(function (req, res) {
var query = url.parse(req.url, true).query;
switch (query.method) {
case "insert":
var pkey = new Buffer(query.publickey,
'base64').toString('ascii');
insertKey(query.pmail, pkey, res);
break;
case "where":
getKey(query.pmail, res);
break;
default:
console.log("Error");
}
}).listen(7777);
function insertKey(pmail, publickey, res) {
var value = [[pmail, publickey]];
var sql = "INSERT INTO publickey (GmailId, PublicKey) VALUES ?";
con.query(sql, [value], function (err, result) {
if (err) throw err;
console.log("success");
res.write('success');
res.end();
});
}
function getKey(pmail, res) {
console.log(pmail);
var sql = 'SELECT PublicKey FROM publickey WHERE GmailId = ?';
con.query(sql, [pmail], function (err, result) {
if (err) throw err;
res.writeHead(200, { "Content-Type": "text/plain" });
res.end(result[0]['PublicKey']);
console.log(result[0]['PublicKey']);
});
}
Here is my server code, i use nodejs
So I have some cloud code I am trying to write to like a post.
My database is setup that users have a likedPosts array, which has object id's of all the posts that the user liked. Users also have a column coins, that should get incremented when users like their posts.
The post object has a likes column which is an integer that gets incremented with each like, and the post object also has a posterId column, which is the object id of the user that posted it.
Here is my function right now (I am not very good at javascript and cloud code, so if there is something horribly wrong, I'm sorry)
Parse.Cloud.define("likePost", function(request, response) {
Parse.Cloud.useMasterKey();
var senderId = request.params.senderId;
var postId = request.params.postId;
var post = new Parse.Object ({objectId: postId});
var posterId = post.posterId
var poster = new Parse.User ({objectId: posterId});
var sender = new Parse.User ({objectId: senderId});
sender.add("likedPosts", postId);
poster.increment("coins");
post.increment("likes");
poster.save(null, {useMasterKey:true, success:
function(poster) {
console.log("Successfully saved poster");
}, error: function(poster, error) {
console.error("Error saving poster: " + error.message);
response.error(error);
}
});
post.save(null,{useMasterKey:true, success:
function(post) {
console.log("Successfully saved post");
}, error: function(post, error) {
console.error("Error saving post: " + error.message);
response.error(error);
}
});
sender.save(null, {useMasterKey:true, success:
function(sender) {
console.log("Successfully saved sender");
}, error: function(sender, error) {
console.error("Error saving sender: " + error.message);
response.error(error);
}
});
response.success();
});
I call the function from swift like so:
PFCloud.callFunction(inBackground: "likePost", withParameters: ["senderId" : PFUser.current()!.objectId!, " postId": postObject!.objectId!], block: { (result, error) in
if (error != nil) {
print(error!)
} else {
print("success liking")
}
})
In my logs, however, I get the following error:
2017-06-21T21:47:59.499Z - Failed running cloud function likePost for user R4d8Zrcdhw with:
Input: {"senderId":"R4d8Zrcdhw"," postId":"XXbu55PdpR"}
Error: {"code":141,"message":{"code":200,"message":"bad or missing username"}}
2017-06-21T21:47:59.492Z - bad or missing username
My guess is that the request is missing a header to define the content-type. I've seen Parse return the "bad or missing username" error via the Parse REST API if the Swift URLSession was using an incorrect content-type header.
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
or
Parse.Cloud.httpRequest({
url: 'http://www.example.com/',
headers: {
'Content-Type': 'application/json;charset=utf-8'
}
})
I don't understand why is my code running the error function instead of success. I keep getting this from my console.log
Object {readyState: 0, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function…}
I could not think of any reason why won't it execute my logic so I tried putting a redirect in my error function and this is what I get
Object {readyState: 0, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function…}
Basically the same thing happened so as of now I don't really have an idea as to what my problem is after editing the windows to window.
This is my code in js
function login(){
var username = document.getElementById("userID").value;
var password = document.getElementById("Password").value;
var postData = { "userID": username, "Password": password };
var postJSON = JSON.stringify(postData);
$.ajax({
url: "http://localhost:3000/api/login", // server url
type: "POST", //POST or GET
contentType: "application/json",
data: postJSON, // data to send in ajax format or querystring format
datatype: "JSON",
success: function(response) {
alert('success');
console.log(response);
window.location.replace("http://localhost/index.html");
},
error: function(response) {
alert('error');
console.log(response);
window.location.replace("http://localhost/index.html");
}
});
}
This is my html code. I am using onclick.
<input class="button" type="submit" id="submit" value="Log In" onclick="return login()"/>
So exactly what went wrong in my code? I am trying to call my login api (localhost:3000/api/login) through ajax with post which would then check mongodb for correct entries and output Login Success which then redirect to another page if input is correct and stay on the same page if input is wrong by giving output "Invalid Login ID or Password".
UPDATE:
Server Side Code
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/myproject';
var authenticate = function(db, req, callback){
var cursor = db.collection('LoginID').find({"_id" : req.body.userID,
"Password" : req.body.Password
}).count(function(err,doc){
if(err) return callback(err);
if(doc == 0){
console.log('Invalid Login ID or Password');
return callback(null, doc);
} else {
console.log('Login Success');
return callback(null, doc);
}
});
}
module.exports = {
postCollection : function(req,res){
var username = req.body.userID;
var Password = req.body.Password;
//var createdDate = "<b>" + day + "/" + month + "/" + year + "</b>"
MongoClient.connect(url, function(err, db) {
//assert.equal(null, err);
if(err) {
res.send(err);
res.end();
}
authenticate(db, req, function(err,doc) {
if(err)
res.send(err);
else{
if(!doc){
res.send( ' Invalid Login ID or Password ' );
res.end();
} else {
res.send("Login success")
res.end();
}
}
db.close();
});
});
}
}
If I remember correctly, the success callback is only called if the HTTP return code is 2xx.
If you send back a redirection, it is considered as an error.
The documentation mentions it:
If the request is successful, the status
code functions take the same parameters as the success callback; if
it results in an error (including 3xx redirect), they take the same
parameters as the error callback.
From http://api.jquery.com/jquery.ajax/, statusCode section.
Moreover, you have to be careful: if an AJAX request receives a 302 response, it won't do a redirection: that is the user agent of your web browser (classic navigation) that does that automatically, but for XHR/AJAX, you have to implement it.
exports.deleteItem = function (req, res)
{
var query = req.params.id;
var cart = req.session.items;
var index;
_.each(cart,function (ticket)
{
if(ticket.id === query)
{
index = cart.indexOf(ticket);
cart.splice(index,1);
}
return res.redirect(303, '/cart');
});
};
I am using this function in my routes to perform a delete operation. It works for the first few items on my list, then suddenly stops and gives me the error "Can't set headers after they are sent."
$(document).ready(function() {
$('.delete-from-cart').click(function(event)
{
$target = $(event.target);
$.ajax({
type: 'DELETE',
url: '/cart/remove/' + $target.attr('data-item-id'),
data: {
_csrf: $target.attr('data-csrf')
},
success: function(response)
{
$target.parent().parent().remove();
Materialize.toast('Ticket Removed', 4000);
window.location.href = '/cart';
},
error: function(error)
{
Materialize.toast('Error', 4000);
console.log(error);
}
});
});
});
A single request was made, which means a single response should occur.
When you execute the _.each function I'm guessing that it works if there is one item but fails when there are multiple? This is because you are trying to send multiple responses when only one is permitted.
A good explanation for this can be found here: Error: Can't set headers after they are sent to the client
I am facing 2 issues with writing a background job in parse
Here is my code
Parse.Cloud.job("createSilentUsers",function(request,response){
// Set up to modify user data
Parse.Cloud.useMasterKey();
//get all the users from backupusers table where isbiscootactivated = 0 and issnsactivated=0
// Query for all users
var query = new Parse.Query("biscootusers");
query.equalTo("isbiscootactivated",0);
query.equalTo("issnsactivated",0);
query.first({
success: function(result) {
// Successfully retrieved the object.
var objUser = result;
console.log(result.attributes.deviceid);
console.log(result.attributes.imei);
console.log(result.attributes.appname);
console.log(result.attributes.appid);
console.log(result.attributes.appversion);
//check if the deviceid and imei set is already a biscoot activated user
var promise = Parse.Promise.as();
promise = promise.then(function() {
console.log("we are inside the prmise");
return Parse.Cloud.httpRequest({
method: 'POST',
url: 'http://<our server name>/1.0/PartnerActivation/isDeviceExists',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'},
body: {
imei: result.attributes.imei,
deviceid: result.attributes.deviceid,
appname: result.attributes.appname,
appid: result.attributes.appid,
appversion: result.attributes.appversion}
}).then(function(httpResponse)
{
console.log("Response of isdeviceactivated is " + httpResponse.text);
if(httpResponse.text == 'true' || httpResponse.text="True")
{
console.log("The user is already activated");
objUser.set("isbiscootactivated",1);
objUser.save();
}
else
{
//do the biscoot activation here
console.log("its not activated, lets do the biscootusers activation");
}
},
function(error) {
console.log("error occurred during isDeviceExists api as " + error);
});
});
console.log("nothing seems to have happened");
},
error: function(error) {
console.log("Error: " + error.code + " " + error.message);
}
}).then(function() {
// Set the job's success status
status.success("All the users been set to the db successfully");
}, function(error) {
// Set the job's error status
status.error("Uh oh, something went wrong.");
});
});
The Issues I have are
In the logs I frequently see this error
Ran job createSilentUsers with:
Input: {}
Failed with: ReferenceError: status is not defined
at main.js:74:9
at r (Parse.js:2:4981)
at Parse.js:2:4531
at Array.forEach (native)
at Object.E.each.E.forEach [as _arrayEach] (Parse.js:1:666)
at n.extend.resolve (Parse.js:2:4482)
at null. (Parse.js:2:5061)
at r (Parse.js:2:4981)
at n.extend.then (Parse.js:2:5327)
at r (Parse.js:2:5035)
The http request just doesn't seem to work, while it always does if I test it from some http REST client.
Just change the "response" to "status" on the funcion header.
Parse.Cloud.job("createSilentUsers",function(request,response){
to this
Parse.Cloud.job("createSilentUsers",function(request,status){