Parse Response Variable Issues with HTTP Request and Cloud Code - parse-platform

I am trying to run an HTTP Request in an afterSave. It executes correctly, but im getting errors with the response variable I was told to put in the end.
Here is the code
Parse.Cloud.afterSave("ArtPiece", function(request) {
var artistURL = 'http://www.gallery-admin-dev.iartview.com/Gilmans/imageSave.php';
var artPiece = request.object;
if (typeof request.image === "undefined") {
var pieceName = artPiece.get("piece_name");
var url = artPiece.get("imageURL");
Parse.Cloud.httpRequest({
url: artistURL,
params: {
pieceName : pieceName,
url : url
},
success: function(httpResponse) {
response.success();
},
error: function(httpResponse) {
response.error('Request failed with response code ' + httpResponse.status)
}
});
}
});
The problem is the success and error functions.
Things I have tried that have not worked:
Putting response as a second parameter in the afterSave Call (it says can not call .success of an undefined variable)
Getting rid of the response lines of code (Result: success/error was not called)
Calling Response as its own function response('Request failed with response code ' + httpResponse.status) it just says response is undefined.
I dont really care about having any response or not, I just want the code to work properly.
How is this 'response' variable supposed to be set up?
Thank you!

There was an extra url in the parameters, a reference to a probably undefined artistURL...
Parse.Cloud.afterSave("ArtPiece", function(request) {
var artistURL = 'http://www.gallery-admin-dev.iartview.com/Gilmans/imageSave.php';
var artPiece = request.object;
if (typeof request.image === "undefined") {
var pieceName = artPiece.get("piece_name");
var url = artPiece.get("imageURL");
var params = { pieceName : pieceName };
return Parse.Cloud.httpRequest({ url: artistURL, params: params });
}
});

Related

Getting a 403 Forbidden error on plugin request

I'm trying to fire a plugin request from my ICN plugin. The request goes as below. However, I'm getting a 403 Forbidden error from the server.
Forbidden
You don't have permission to access /navigator/jaxrs/plugin on this server.
https://<icnserver.com>/navigator/jaxrs/plugin?repositoryId=Demo&query=%5B%7B%22name%22%3A%22ID%22%2C%22operator%22%3A%22LIKE%22%2C%22values%22%3A%5B%22123434234%22%2C%22%22%5D%7D%5D&className=Checks&plugin=DemoPlugin&action=DemoService&desktop=Demo
Plugin JS:
aspect.around(ecm.model.SearchTemplate.prototype, "_searchCompleted", function advisingFunction(original_searchCompleted){
return function(response, callback, teamspace){
var args = [];
var templateName = response.templates[0].template_name;
var res = response;
var requestParams = {};
requestParams.repositoryId = this.repository.id;
requestParams.query = query;
requestParams.className = templateName;
Request.invokePluginService("DemoPlugin", "DemoService",
{
requestParams: requestParams,
requestCompleteCallback: lang.hitch(this, function(resp) { // success
res.rows = resp.rows;
res.num_results = resp.rows.length;
res.totalCount = resp.rows.length;
args.push(res);
args.push(callback);
args.push(teamspace);
original_searchCompleted.apply(this,args);
})
}
);
}
});
You need to provide a security_token to be able to call your service, so you need to login first.
Then, open your browser's debug and check the requests in the network tab.
There you can see that every request that targets the /navigator/jaxrs/* URI will contain it, so something like this will be among the headers:
security_token: 163594541620199174
So my bet is that you have not set it in your client (I recommend a postman to test your service, or I would add a test (ICN) feature page in the ICN plugin project in order to be able to call it properly). In your feature page, you can call your service directly using the ecm/model/Request OOTB navigator dojo/javascript class, as you can see in CheckinAction.js:
_checkInDocument: function (item, requestData)
{
var self = this;
var payLoadObject = {requestType: "Get", id: item.id};
Request.postPluginService("DocuSignPlugin", "UpdateSignedDocumentService", "application/json", {
requestParams: {
repositoryId : item.repository.id,
serverType : item.repository.type,
docId : item.docid,
envelopeId: item.attributes.DSEnvelopeID,
payLoad: json.stringify(payLoadObject)
},
requestCompleteCallback: function(response) {
if (response.returncode == 0)
{
item.attributeDisplayValues.DSSignatureStatus = "Checkedin";
item.attributes.DSSignatureStatus = 4;
item.update(item);
}
else if (response.returncode == -1)
{
items = [];
items.push(item);
self._showLoginDialog(items);
}
},
backgroundRequest : false,
requestFailedCallback: function(errorResponse) {
// ignore handline failures
}
});
},
As you can see, you don't have to add the security_token to the requestParams, the framework will do it for you.

Is there a way to show "Loading data.." option in Rally Grid(ext JS) while making the Ajax request to load the data?

I am trying to set the message to "Data Loading.." whenever the data is loading in the grid. It is working fine if I don't make an Ajax call. But, when I try to make Ajax Request, It is not showing up the message "Loading data..", when it is taking time to load the data. Can someone please try to help me with this.. Thanks in Advance.
_loadData: function(x){
var that = this;
if(this.project!=undefined) {
this.setLoading("Loading data..");
this.projectObjectID = this.project.value.split("/project/");
var that = this;
this._ajaxCall().then( function(content) {
console.log("assigned then:",content,this.pendingProjects, content.data);
that._createGrid(content);
})
}
},
_ajaxCall: function(){
var deferred = Ext.create('Deft.Deferred');
console.log("the project object ID is:",this.projectObjectID[1]);
var that = this;
console.log("User Reference:",that.userref,this.curLen);
var userObjID = that.userref.split("/user/");
Ext.Ajax.request({
url: 'https://rally1.rallydev.com/slm/webservice/v2.0/project/'+this.projectObjectID[1]+'/projectusers?fetch=true&start=1&pagesize=2000',
method: 'GET',
async: false,
headers:
{
'Content-Type': 'application/json'
},
success: function (response) {
console.log("entered the response:",response);
var jsonData = Ext.decode(response.responseText);
console.log("jsonData:",jsonData);
var blankdata = '';
var resultMessage = jsonData.QueryResult.Results;
console.log("entered the response:",resultMessage.length);
this.CurrentLength = resultMessage.length;
this.testCaseStore = Ext.create('Rally.data.custom.Store', {
data:resultMessage
});
this.pendingProjects = resultMessage.length
console.log("this testcase store:",resultMessage);
_.each(resultMessage, function (data) {
var objID = data.ObjectID;
var column1 = data.Permission;
console.log("this result message:",column1);
if(userObjID[1]==objID) {
console.log("obj id 1 is:",objID);
console.log("User Reference 2:",userObjID[1]);
if (data.Permission != 'Editor') {
deferred.resolve(this.testCaseStore);
}else{
this.testCaseStore = Ext.create('Rally.data.custom.Store', {
data:blankdata
});
deferred.resolve(this.testCaseStore);
}
}
},this)
},
failure: function (response) {
deferred.reject(response.status);
Ext.Msg.alert('Status', 'Request Failed.');
}
});
return deferred;
},
The main issue comes from your Ajax request which is using
async:false
This is blocking the javascript (unique) thread.
Consider removing it if possible. Note that there is no guarantee XMLHttpRequest synchronous requests will be supported in the future.
You'll also have to add in your success and failure callbacks:
that.setLoading(false);

Youtube-data API "part" request parameter doesn't accept "player" as the value

https://developers.google.com/youtube/v3/docs/videos#resource
The link above says I can set the part attribute in the request to be "player". But when I do this, I get a bad response.
My code is below:
$("form").on("keyup", function (e) {
e.preventDefault();
// prepare the request
if ($('#search').val() === '') {
$('#results').html("");
} else {
var request = gapi.client.youtube.search.list({
part: "snippet",
type: "video",
q: encodeURIComponent($("#search").val()).replace(/%20/g, "+"),
maxResults: 10,
videoEmbeddable: true,
order: "viewCount",
publishedAfter: "2000-01-01T00:00:00Z"
});
// execute the request
request.execute(function (response) {
var results = response.result;
$("#results").html("");
$.each(results.items, function(index, item) {
$("#results").append('<span>' + item.player.embedHtml + '</span>');
});
});
resetVideoHeight();
$(window).on("resize", resetVideoHeight);
}
});
});
The link your referring is for videos endpoint, but your code using search endpoint. The search endpoint only accept snippet.
https://developers.google.com/youtube/v3/docs/search#resource

Can't update a single doc in Mongo with Node

Hopefully someone can point out my error here.
In my app a user clicks on a button to insert a doc into the database. When they click on another button, a timestamp is added to an array.
Here's the code to create the doc (it works):
// Add User
function addUser(event) {
event.preventDefault();
ident = makeWords(2);
var newUser = {
'ident' : ident,
'group': '',
'timestamps': [],
'date_created': Date()
}
// Use AJAX to post the object to our adduser service
$.ajax({
type: 'POST',
data: newUser,
url: '/users/adduser',
dataType: 'JSON'
}).done(function( response ) {
if (response.msg === '') {
console.log('user added');
} else {
alert('Error');
}
});
};
And here's the route which handles it:
/*
* POST to adduser.
*/
router.post('/adduser', function(req, res) {
var db = req.db;
var collection = db.get('testcol'); //'testcol' is the name of my collection
collection.insert(req.body, function(err, result){
res.send(
(err === null) ? { msg: '' } : { msg: err }
);
});
});
I kind of thought that updating a doc would be just as easy. I'm grabbing the doc by the ident field, which will be unique to each user. However, I can't seem to make the client-side stuff pass to the server. Here's my client-side update:
function addError(event) {
event.preventDefault();
// If it is, compile all user info into one object
var errorUpdate = {
'$push': {'error_button': Date()}
}
// Use AJAX to post the object to our adduser service
$.ajax({
type: 'PUT',
data: errorUpdate,
url: '/users/errorUpdate',
dataType: 'JSON'
}).done(function( response ) {
if (response.msg === '') {
console.log("update sent, didn't receive an error");
}
else {
alert('Error');
}
});
};
This code executes, but the server-side just throws 500s. Here's that function:
/*
* update mongo doc
*/
router.put('/errorUpdate', function(req, res) {
var db = req.db;
var collection = db.get('testcol');
collection.update({'ident': ident},req.body, function(err, result){
if (err) {
console.log('Error updating menu: ' + err);
res.send({'users.js: error':'An error has occurred'});
} else {
console.log('doc has been updated');
res.send(item);
}
});
});
Any idea where I'm going wrong?
I solved this and it was a really really stupid mistake.
You might notice in my server-side code I use a variable called ident:
router.put('/errorUpdate', function(req, res) {
var db = req.db;
var collection = db.get('testcol');
collection.update({'ident': ident},req.body, function(err, result)...
ident is a global variable from my client-side stuff (global.js, which makes the ajax call), and it never made it to the server.
Further, I tried to send the Mongo update statement with the ident variable, which is totally unnecessary and just caused headaches.
Here's how I fixed it. This is client-side (where I only send the ident variable):
function addError(event) {
event.preventDefault();
// If it is, compile all user info into one object
var identifyMe = {
'ident': ident
}
// Use AJAX to post the object to our adduser service
$.ajax({
type: 'POST',
url: '/users/errors',
data: identifyMe,
dataType: 'JSON'
}).done(function( response ) {
// Check for successful (blank) response
if (response.msg === '') {
console.log('update sent, no errors received');
}
else {
console.log('Error detected. Response was: ' + response);
}
});
};
... and this is server-side, where I take that identifier and do the update (this works because all I'm doing is inserting a time stamp):
router.post('/errors', function(req, res) {
console.log(req.body);
var identifier = req.body.ident;
var db = req.db;
var collection = db.get('testcol');
collection.update({'ident': identifier}, {$push: {'error_button': Date()}}, function(err, result){
res.send(
(err === null) ? { msg: '' } : { msg: err }
);
});
});
You might notice that I'm pulling out that ident variable from the JSON that's being passed, with req.body.ident.
Hope this helps someone else struggling with updating a Mongo doc by posting to Express routes via Ajax with Node! :)

Random HTTP error 405 while using ajax request

I am getting HTTP error 405 verb not allowed. As sometimes code works and sometimes throws http 405 error, I need to understand whether this is programming problem or server configuration problem. I am using ajax with jquery. I have gone through all related posts here and tried all recommended options related with the code. Please help.
my javascript code is as follows
$(function() {
$('.error').hide();
$(".button").click(function() {
// validate and process form
// first hide any error messages
$('.error').hide();
var name = $("input#name").val();
if (name == "") {
$("label#name_error").show();
$("input#name").focus();
return false;
}
var email = $("input#email").val();
if (email == "") {
$("label#name_error").show();
$("input#email").focus();
return false;
}
var textquery = $("textarea#textquery").val();
if (textquery == "") {
$("label#name_error").show();
$("textarea#textquery").focus();
return false;
}
var dataString = name + email + textquery;
// alert (dataString);return false;
$.ajax({
type: "POST",
url: "samplemail.aspx",
data: dataString,
success: function() {
$('#contact_form').html("<div id='message'></div>");
$('#message').html("<h2>Contact Form <br> Submitted!</h2>")
.append("<p>We will be in touch soon.</p>")
.hide()
.fadeIn(1500, function() {
$('#message').append("<img id='checkmark' src='images/check.png' />");
});
}
});
return false;
});
});
runOnLoad(function(){
$("input#name").select().focus();
});
Problem solved
the way Of passing parameter was wrong i.e.data : datastring .
The correct way is data : { name : name, email: email, textquery: textquery}

Resources