Save success not working with parse.com object - javascript

I have been messing around trying to save data from a web form and cannot get the standard validation to return. Thinking this is some sort of async problem that I am just not getting. Saving objects with the parse.com api is built off of backbone.js, so it is pretty similar to that. For some reason I can save my data to my database no problems, but when I try to introduce some sort of validation it gets messed up. Looking for some info on how to properly get a success validation back from the server. Right now it hits error every time, and seems to kill the server from saving data.
Below is the code that executes on submit. I have shown the three ways I have tried saving data.
$("#f1").submit(function(event) {
var NewRes = Parse.Object.extend("Customer");
var newRes = new NewRes();
newRes.set("FirstName", "Ricky");
newRes.set("LastName", "Bobby");
//works every time, but I have no return validating it
newRes.save();
//saving with callback options, doesn't save anything to the database and hits error message
newRes.save(null, {
wait: true,
success: function(newRes, response) {
alert("success" + response.message);
},
error: function(newRes, response) {
alert("errorcode: " + response.code + " Message: " + response.message);
}
});
//saving with promises, doesn't save anything and hits error message
newRes.save().then(function(response) {
alert("success");
}, function(error) {
alert("error");
});
});
Here are the results of the error message given below:
errorcode: 100 Message: XMLHttpRequest failed: {"statusText":"","status":0,"response":"","responseType":"","responseXML":null,"responseText":"","upload":{"ontimeout":null,"onprogress":null,"onloadstart":null,"onloadend":null,"onload":null,"onerror":null,"onabort":null},"withCredentials":false,"readyState":4,"timeout":0,"ontimeout":null,"onprogress":null,"onloadstart":null,"onloadend":null,"onload":null,"onerror":null,"onabort":null}

The reason none of this was working is because the form.submit() function was finishing before any of the parse.com asynchronous functions were complete. In order to prevent this I used the preventdefault method to stop the form from submitting. Then I used location.reload() to refresh the page after my parse.com requests have either finished successful or failed.
$("#f1").submit(function(event) {
event.preventDefault();
var NewRes = Parse.Object.extend("Customer");
var newRes = new NewRes();
newRes.set("FirstName", "Ricky");
newRes.set("LastName", "Bobby");
//saving with promises
newRes.save().then(function(response) {
alert("success");
location.reload(); //refreshes the form
}).catch(function(error) {
alert("error");
location.reload();
});
});

Related

Error with the promise/catch from a Firestore query

I've modified the code below a bit but this is an externally facing endpoint where a mobile client can ping this endpoint and send some pushes to appropriate users.
However, in my console, I'm getting an error:
UnhandledPromiseRejectionWarning: TypeError: assert.isNotOk is not a function
function myFunc(request, response) {
var db = firestore.firestore();
db.collection("myCollection")
.doc(request.params.someParam)
.get()
.then(docSnapshot => {
if (docSnapshot.exists) {
for (var userId of request.params.userIds) {
sendPush(userId, request.params);
continue;
} else {
response.error("Unable to get param");
}
}).catch((error) => {
assert.isNotOk(error, 'Promise error');
done();
});;
});
Any idea what I'm doing wrong here? Thanks
As you can see in the documentation for node's assert, there is no method called isNotOk. However, this is a method called ok. In any event, it's not clear to me what you're trying to do with that line, since you already know at that point that there's an error. Perhaps you just want to log it?

How do I successfully console log the data from this api?

When I go into the Network tab and inside response, I do get the results of this API, but I cannot get it to output in the console.
This is the code:
const NAMEURL = "https://uzby.com/api.php"
// get data from api
function getDataFromApi(value, callback){
const QUERY = {
min:`${value}`,
max:`${value}`
}
$.getJSON(NAMEURL, QUERY, callback)
}
function renderResult(result){
return `${result}`;
}
// render results to page
function displayName(data){
console.log(data);
const results = renderResult(data);
$('.nameResult').html(results);
}
// wait for user to submit
function watchSubmit() {
$('.js-search-form').submit(event => {
event.preventDefault();
const queryTarget = $(event.currentTarget).find('#js-dropValue');
const thisquery = queryTarget.val();
getDataFromApi(thisquery, displayName);
});
}
// running the watch submit function waiting for click
$(watchSubmit);
I tried doing a console.log(getDataFromApi()) but I get undefined in console.
console.log(getDataFromApi()); would never work, its displayName() that you would have to console log.
Your code was not wrong, with the exception of what you were trying to console log, but even then its not going to work because uzby does not want to share its resources directly with your application.
So indeed that error you were getting, the CORS error is the problem.
You need to proxy that request through your own server, the one that loads your page. You will have to research documentation on your server side language proxy. A potential solution for your code could be like this:
xmlhttp.open(
'GET',
'https://cors-anywhere.herokuapp.com/https://example.com/api.php?' + param,
true
);

Parse custom webhook: can I query my tables?

In a Parse custom webhook, which is of the form:
app.post('/receiveSMS', function(req, res) {
Where receiveSMS is hooked up to the Twilio api and this method is properly called (I have logs to prove it), but I'm trying to query on my tables within this method and it doesn't seem to be working.
Is this allowed, or is there anything special I need to do to make this work?
var contactObj = Parse.Object.extend("Contact");
var contactQuery = new Parse.Query(contactObj);
console.log(req.body.From);
contactQuery.each(function(contact) {
and the body of the each call never gets called.
Is this allowed, and if so, what am I doing wrong here?
Update -- The entirety of the webhook code block is:
app.post('/receiveSMS', function(req, res) {
console.log('receive SMS');
console.log(req.body.Body);
res.send('Success');
if(req.body.Body.toLowerCase() == "in" || req.body.Body.toLowerCase() == "out") {
twilio.sendSMS({
From: "(xxx) xxx-xxxx",
To: req.body.From,
Body: "It's been noted, and notifications have been sent. Check us out!"
}, {
success: function(httpResponse) {
console.log(httpResponse);
response.success("SMS Sent!");
},
error: function(httpResponse) {
console.error(httpResponse);
response.error("Uh OH, something went wrong");
}
});
if(req.body.Body.toLowerCase() == "in") {
console.log("in was received");
// eventQuery
var contactObj = Parse.Object.extend("Contact");
var contactQuery = new Parse.Query(contactObj);
console.log(req.body.From);
// contactQuery.equalTo("phone", req.body.From);
contactQuery.first({
success: function(contact) {
console.log("found contact");
console.log(contact);
}, error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
}
}
});
This code is called and the logs "console.log('receive SMS')" and the like are all called, except for what is inside the query's first call.
Queries on tables is fine, but you can't use the each() function, as that is restricted to only work in background jobs.
You'll have to use find() or first() or get() depending on your needs.
UPDATE
OK, after seeing your full code I have some ideas as to why it isn't working. First off you're sending res.send("Success"); before you're finished, I'm not positive but I think this causes it to stop running the rest of your code (haven't checked, could be wrong).
Also you're doing multiple async operations without chaining them so the contactQuery.first() will run before the twilio.sendSMS() is finished.
Inside twilio.sendSMS() you're calling response.success() / response.error(). These are for cloud methods, not web hooks, so I expect these would be throwing errors server-side (check the logs on the Dashboard).
Inside contactQuery.first() you are using alert() which isn't supported in cloud code.
I'm not sure if those mistakes will be caught early and throw errors or if they'll raise run-time exceptions, but they should be fixed, your code re-deployed and try again. Then report any errors in the server logs.
Yes, it's allowed, I'm using the same web hooks.
My guess is that you probably have defined security restriction on your Contact class that prevent the query to fetch anything. What's the security setting on this class ?
You can either try to relax the constrains, or login as a dummy user, and execute the query (approach that I chose).
cheers
-A

No response from Javascript SDK find call

I'm working with the cloud code javascript SDK. I'm trying to run a query, but it seems that the "find" method never receives a response. Here's what I've got so far:
var query = new Parse.Query("Report");
var sixteen_h = new Date();
sixteen_h.setHours(sixteen_h.getHours() - 16);
query.greaterThan("createdAt", sixteen_h);
query.find({
success: function(results) {
console.log("Got pain results!");
},
error: function(error) {
console.log("Error: " + error.code + " " + error.message);
}
});
Neither of these console logs are ever executed! Any ideas here? I've tried it both with and without the "query.greaterThan()" part and get no response both times. I've tried putting various log statements throughout it but can't see where it goes wrong.
I was using this in a beforeSave function. Apparently you can't do that. Once I moved this to an afterSave function then it worked fine!

How to be sure that message via socket.io has been received to the client?

How to check that message sent with socket.io library has been received to the client.
Is there special method for it in socket.io?
Thanks for your answers!
You should use the callback parameter while defining the event handler.
A typical implementation would be as follows:
Client side
var socket = io.connect('http://localhost');
socket.emit('set', 'is_it_ok', function (response) {
console.log(response);
});
Server side
io.sockets.on('connection', function (socket) {
socket.on('set', function (status, callback) {
console.log(status);
callback('ok');
});
});
Now check the console on the server side. It should display 'is_it_ok'. Next check console on client side. It should display 'ok'. That's the confirmation message.
Update
A socket.io connection is essentially persistent. The following in-built functions let you take action based on the state of the connection.
socket.on('disconnect', function() {} ); // wait for reconnect
socket.on('reconnect', function() {} ); // connection restored
socket.on('reconnecting', function(nextRetry) {} ); //trying to reconnect
socket.on('reconnect_failed', function() { console.log("Reconnect failed"); });
Using the callback option shown above is effectively a combination of the following two steps:
socket.emit('callback', 'ok') // happens immediately
and on the client side
socket.on('callback', function(data) {
console.log(data);
});
So you don't need to use a timer. The callback runs immediately except if the connection has any of the following states - 'disconnect', 'reconnecting', 'reconnect_failed'.
You can use the socket.io's acknowledgements.
Quote from the socket.io documentation:
Sometimes, you might want to get a callback when the client confirmed
the message reception.
To do this, simply pass a function as the last parameter of .send or
.emit. What's more, when you use .emit, the acknowledgement is
done by you, which means you can also pass data along.
On the client side simply emit the event with your data, the function will be called whenever the server responds to your event:
client.emit("someEvent", {property:value}, function (data) {
if (data.error)
console.log('Something went wrong on the server');
if (data.ok)
console.log('Event was processed successfully');
});
On the server side you get called with the data and the callback handle to send the response:
socket.on('someEvent', function (data, callback) {
// do some work with the data
if (err) {
callback({error:'someErrorCode', msg:'Some message'});
return;
}
callback({ok:true});
});
When you add a function as the last parameter of .send() or .emit() method calls, this function is called when the other party receives the message.
socket.send('hi', function() {
// if we are here, our salutation has been received by the other party.
});

Categories

Resources