Why Parse.Query function is not work? - javascript

I use to Parse Cloud Code.
now I can not unsolvable problem.
It is this code.
This 1 code is not problem working ,but 2 code is not work.
Why?
var className = Parse.Object.extend("Post");
//--------------------------1 Start-----------------------------
var post = new className();
post.set("ArtistName","Name");
post.set("Collection","アルバム");
post.set("MusicTitle","タイトル");
post.set("user",toUser);
post.save(null, {
success: function(gameScore) {
console.log("クラス保存成功");
}
});
//---------------------------1 end----------------------------
//-------------------------2 start-----------------------------
var query = new Parse.Query(className);
//query.equalTo("user", toUser);
query.count({
success: function(count) {
console.log("Sean has played " + count + " games");
},
error: function(error) {
console.log("エラー");
}
});
//--------------------------2 end-------------------------------

From the code you provide is valid except one line. You have to call response success as below;
var query = new Parse.Query(className);
//query.equalTo("user", toUser);
query.count({
success: function(count) {
console.log("Sean has played " + count + " games");
response.success(count);
},
error: function(error) {
console.log("Error");
response.error(error);
}
});
After calling the success you can see the count both in the logs and function caller.
Hope this helps.
Regards.

Related

AJAX does not return anticipated response [duplicate]

This question already has answers here:
How do I catch an Ajax query post error?
(8 answers)
Closed 1 year ago.
I'm trying to start to use AJAX to
send a Javascript variable from one PHP file to another
that will enqueue it to a queue function I have created
and then peek that ID in the queue by changing the < p > tag in my main file
EDIT:
I get an error now that I have added an error parameter; either [Object Object] or Undefined and console.log(data) the error is a POST 500 jquery.js
I have tried solutions to add .d after data, altering the dataType to match the response from the Networks panel in Dev Tools, json_encode in the PHP file, but no luck.
Javascript:
var log = document.getElementById("log"); //ID of the <p> tag to change to ID number
document.getElementById("scanButton".addEventListener("click", async () => {
try{
/*functions to obtain ID number*/
var IDnumber = 0000; //functions will change this value after every click
$.ajax({
type: "POST",
url: "savetodb.php",
data: { idNumber : IDnumber },
success: function(data){
log.innerHTML = data;
},
error: function(error) {
log.innerHTML = error;
}
});
} catch (error){
log.innerHTML = error;
});
PHP:
$idNumber = $_POST['idNumber'];
/*queue methods and functions*/
public function peek() {
return $this->queue[$this->front];
}
$queue = new CircularQueue(15);
$queue->enqueue($idNumber);
echo $queue->peek();
Try to catch error through parameter "error" instead of using try catch.
$.ajax({
type: "POST",
url: "savetodb.php",
data: { idNumber : IDnumber},
success: function(){
log.innerHTML = ("ID : " + IDnumber + " logged successfully!");}
},
error: function(error) {
log.innerHTML = error.responseText;
}
);
https://api.jquery.com/jquery.ajax/

JS exception is still able to sneak in but very rarely, not sure why

I wrapped the function with setTimeout it will run forever. If you notice on the screenshot, js exception happened after so many times. That is what is happening on our real app too. I am not sure why.
Here is the fiddle: http://jsfiddle.net/ux12xoya/1/
// JSON Request
var auxTime = new Date();
var jQueryCallbackRandom = auxTime.getTime();
var callParameters = {
url: 'http://jsfiddle.net/echo/jsonp/',
timeout: 2,
dataType: "jsonp",
data: { echo: "Hello World!" },
jsonpCallback: "jQueryRandom_" + jQueryCallbackRandom,
success: function(){
console.log("success");
},
error: function(jqXHR, textStatus){
console.log("failed with error: " + textStatus);
window["jQueryRandom_" + jQueryCallbackRandom] = function() {
window["jQueryRandom_" + jQueryCallbackRandom] = null;
};
}
};
var timeout = setTimeout(callAjax, 5000)
function callAjax() {
$.ajax(callParameters);
clearTimeout(timeout);
timeout = setTimeout(callAjax, 5000)
}
Here is the screenshot of the error: http://i.imgur.com/IFiW9ij.png
This is failing because your timeout is too short. When the request times out, the callback is removed from the window, and then when the request actually finishes, an exception is thrown because the callback isn't on the window. It doesn't happen every time because you're using the same callback name for every request, and sometimes it just so happens to complete while another request hasn't timed out yet resulting in a "success" that wasn't actually a success.
Your code was actually pretty close, the root of the issue here is that you didn't give each request a unique JSONPCallback. You simply need to move those variables into the ajax function so that they will be re-created for each request, resulting in each getting it's own auxTime based callback name.
// JSON Request
var timeout = setTimeout(callAjax, 5000)
function callAjax() {
var auxTime = new Date();
var jQueryCallbackRandom = auxTime.getTime();
var callParameters = {
url: 'http://jsfiddle.net/echo/jsonp/',
timeout: 5,
dataType: "jsonp",
data: { echo: "Hello World!" },
jsonpCallback: "jQueryRandom_" + jQueryCallbackRandom,
success: function(){
console.log("success");
},
error: function(jqXHR, textStatus){
console.log("failed with error: " + textStatus);
window["jQueryRandom_" + jQueryCallbackRandom] = function() {
window["jQueryRandom_" + jQueryCallbackRandom] = null;
};
}
};
$.ajax(callParameters);
clearTimeout(timeout);
}
http://jsfiddle.net/ux12xoya/2/

order of operations parse cloud

I was wondering what the order of operations are in the parse cloud. I currently am running into trouble trying to do multiple things at once inside my job on the cloud. I am currently trying to make an HTTP request for each user in my user table (there are 2) and then get the webpage or httprequest.text from the webpage. My code is as followed
Parse.Cloud.job("WeatherUpdates2", function(request, status) {
var query = new Parse.Query(Parse.User);
query.exists("City");
query.each(
function(result){
var object = result;
console.log(object.id);
var city = object.get("City");
city = city.replace(" ", "");
city = city.replace(" ", "");
// get the country code.
var countryCode = object.get("CountryCode");
var woeidUrl = "http://where.yahooapis.com/v1/places.q(" + city + "," + countryCode + ")?appid=(appid)";
console.log(woeidUrl);
var woeID = "An error occured retrieving your WOEID.";
Parse.Cloud.run('httpRequest', { url: woeidUrl }, {
success: function(WOEID) {
console.log("returned from http request.");
},
error: function(error) {
console.log("Error occurred while making request for WOEID " + error.message);
status.error(error.message);
}
});
},
{
success: function() {
// results is an array of Parse.Object.
console.log('#Query');
status.success("Updated Records!!");
},
error: function(error) {
// error is an instance of Parse.Error.
console.log('#error');
response.error("Failed to save vote. Error=" + error.message);
}
});
});
Where the job httpRequest is:
Parse.Cloud.define("httpRequest", function(request, response) {
var webpage = "Something went wrong.";
Parse.Cloud.httpRequest({
url: request.params.url,
success: function (httpResponse) {
webpage = httpResponse.text;
webpage = webpage.toString();
response.success(webpage);
},
error: function (error)
{
console.log("Error in http request " + error.message);
response.error(error.message);
}
});
});
now I would expect to be printed would be the, object id of first user, their url, the job running, the message"returned from http request." then repeated another time for the second user and finally the job finishing with the message "Updated Records". but instead I get:
I2014-07-22T15:15:16.013Z] A5hod7qKE3
I2014-07-22T15:15:16.045Z] http:/where.yahooapis.com/v1/places.q(Draper,US)?appid=(appid)
I2014-07-22T15:15:16.053Z] GmuqxpTUpM
I2014-07-22T15:15:16.066Z] http:/where.yahooapis.com/v1/places.q(SaltLakeCity,US)?appid=(appid)
I2014-07-22T15:15:16.082Z] #Query
I2014-07-22T15:15:16.131Z] v385: Ran cloud function httpRequest with:
Input: {"url":"http://where.yahooapis.com/v1/places.q(SaltLakeCity,US)?appid=(appid)"}
Result:
2487610TownSalt Lake CityUnited StatesUtahSalt LakeSalt Lake City40.777561-111.93071740.699890-112.10125740.852951-111.739479511America/Denver
I2014-07-22T15:15:16.141Z] v385: Ran cloud function httpRequest with:
Input: {"url":"'http://where.yahooapis.com/v1/places.q(Draper,US)?appid=(appid)'"}
Result:
http://where.yahooapis.com/v1/schema.rng'" xmlns:yahoo="http://www.yahooapis.com/v1/base.rng" yahoo:start="0" yahoo:count="1" yahoo:total="11">2393601TownDraperUnited StatesUtahDraper8402040.524139-111.86627240.442921-111.92212740.544361-111.78304349America/Denver
I removed 1 / from both the printing urls so I could posts this because I don't have high enough rep to post more than 2 links. I also have put in my appid into the (appid) so the url does return to me the according woeid from yahoo.com. The problem here being I can't actually get into the success function of the http request job. Any help is greatly appreciated!
EDIT:
I was trying to figure out how to run a job in a for loop but couldn't get it to work. I tried to make a promise and do what Fosco said below, but have had no luck. Here is my code.
for(var i = 0; i < woeIDs.length; i++)
{
console.log("hello");
var weatherURL = "http://weather.yahooapis.com/forecastrss?w=" + woeIDs[i] + "&u=f";
var promise = Parse.Cloud.run('httpRequest', { url: weatherURL }, {
success: function(WOEID) {
console.log("got here");
},
error: function(error) {
console.log("Error occurred while making request for WOEID " + error.message);
status.error(error.message);
}
});
Parse.Promise.when([promise]).then(function() { status.success(); });
}
if I run this code I get a hello twice then the two job calls then the "got here" message once. I have tried adding a return statement to it and with no luck also. Thanks again for all the help!!!
The issue here is that inside the each callback, you need to return the promise from your cloud function call if you want to ensure the tasks complete, and have it wait before going to the next object.
Simplified and using promises:
query.each(function(object) {
...
return Parse.Cloud.run(...);
}).then(function() {
// success
}, function(err) {
// error
});
For looping over a promise-returning function like Parse.Cloud.run:
var promises = [];
for (i = 0; i < 5; i++) {
promises.push(Parse.Cloud.run('...', {}));
}
Parse.Promise.when(promises).then(function() {
// all done
}, function(err) {
// error
});

ParseApp Saving data from httpRequest

I am writing a simple app where I need to get the data from a http get api call and store it in Parse for some reason not all the data is stored. Also the http call returns before saving all the data here is the code.
How can I make it to return only after saving all the data?
Parse.Cloud.httpRequest({
url: 'http://api.rottentomatoes.com/api/public/v1.0/lists/movies/upcoming.json?apikey=apikey',
success: function(httpResponse) {
var jsonobj = JSON.parse(httpResponse.text);
var total = jsonobj.movies.length;
for ( var idx in jsonobj.movies) {
var movie = new Movie();
movie.save(new Movie(jsonobj.movies[idx])).then(
function(object){
console.log(object)
},
function(error){
console.log(error);
}
)
}
response.send("All saved");
},
error: function(httpResponse) {
console.error('Request failed with response code ' + httpResponse.status);
response.send("Failed");
}
})
You need to aggregate all the promises you used via an aggregation function, in the case of parse promises, it's .when :
Parse.Cloud.httpRequest({
url: 'http://api.rottentomatoes.com/api/public/v1.0/lists/movies/upcoming.json?apikey=apikey',
success: function(httpResponse) {
var jsonobj = JSON.parse(httpResponse.text);
var total = jsonobj.movies.length;
var results = [];
// do NOT iterate arrays with `for... in loops`
for(var i = 0; i < jsonobj.movies.length; i++){
var movie = new Movie();
results.push(movie.save(new Movie(jsonobj.movies[i]))); // add to aggregate
}
// .when waits for all promises
Parse.Promise.when(promises).then(function(data){
response.send("All saved");
});
},
error: function(httpResponse) {
console.error('Request failed with response code ' + httpResponse.status);
response.send("Failed");
}
})
Although, it might be better to use promises for the httpRequest too, this should work.

Pass Exception from plugin to Javascript

For some reasons I have a javascript that create an entity record and a plugin will fire on post create. If the pugin throw an exception, it does NOT display to the user as the javascript is involved. I am wondering if there is a way to pass the exception from the plugin to javascrit so it can display it to the user.
Thanks.
Do you receive any http status code error like 40*, 500, 50* , if you use Odata, you have a callback to get the error. Javascript exception may not be throw.
Example:
.ajax({
type: “POST”,
contentType: “application/json; charset=utf-8″,
datatype: “json”,
url: serverUrl + ODATA_ENDPOINT + “/” + odataSetName,
data: jsonEntity,
beforeSend: function (XMLHttpRequest) {
//Specifying this header ensures that the results will be returned as JSON.
XMLHttpRequest.setRequestHeader(“Accept”, “application/json”);
},
success: function (data, textStatus, XmlHttpRequest) {
},
error: function (XmlHttpRequest, textStatus, errorThrown) {
if (errorCallback)
errorCallback(XmlHttpRequest, textStatus, errorThrown);
else
alert(“Error on the creation of record; Error – “+errorThrown);
}
});
}
Checking the XMLHttpRequest readyState and status should do the trick:
function createRecord(eObject, eName) {
var jsonEntity = window.JSON.stringify(eObject);
var u = Xrm.Page.context.getServerUrl();
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
var rec = new XMLHttpRequest();
var p = u + ODATA_ENDPOINT;
rec.open('POST', p + "/" + eName, false);
rec.setRequestHeader("Accept", "application/json");
rec.setRequestHeader("Content-Type", "application/json; charset=utf-8");
rec.send(jsonEntity);
if (rec.readyState == 4) {
if (rec.status == 200) {
var r = JSON.parse(rec.responseText).d;
return r;
}
else {
var error;
try {
// To get the exception from the responseXML
// I get an error when trying to use JSON.parse(rec.response)
// Unexpected token <
// I would much rather use JSON.parse
// than fiddling with the XML
// Please let me know if you find how to
// get the error message with JSON.parse
var xmlDoc = rec.responseXML;
var error = xmlDoc.childNodes[0]
.childNodes[0]
.childNodes[0]
.childNodes[1]
.childNodes[0].nodeValue + "."; // The error message
}
catch (e) {
// unable to get error message from response
error = "General Error";
}
return error;
}
}
// there is a problem
// maybe return general error message
return "General Error";
}
Thanks for all of you. I did resolve the issue by modifying part of my code to the following:
rec.send(jsonEntity);
if (rec.readyState == 4) {
if (rec.status >= 200) {
var newRecord = JSON.parse(rec.responseText).d;
return newRecord;
}
else {
var error;
var er;
try {
error = rec.responseText.toString();
error = error.substring(error.lastIndexOf("value\": ")+9,error.lastIndexOf("\""));
alert(error);
}
catch(e) {
error = rec.responseText.toString();
error = encodeURIComponent(error);
er = error.substring(error.lastIndexOf("value%22%3A%20%22")+17,
error.lastIndexOf("%22%0D%0A%7D%0D%0A%7D%0D%0A%7D"));
er = decodeURIComponent(er);
return er;
}
}

Categories

Resources