Relational query with Parse - javascript

So I am trying to get the comments associated with a blog, Using Parse Javascript SDK
here is my code
var Blog = Parse.Object.extend("Blog");
var query = new Parse.Query(Blog);
query.get("tFlENZ3ege", {
success: function(blog) {
// Next, retrive comment based on blog
var commentQuery = new Parse.Query(Comment);
commentQuery.equalTo("parent", blog);
commentQuery.find({
success: function(comments) {
console.log("Success getting comments");
},
error: function(object, error) {
console.log(error);
}
});
},
error: function(object, error) {
}
});
I am able to retrieve the blog object based on the objectId.
However, I can't figure out how to get the associated comment objects

Related

How to send Image ( Photo parameter) to javascript adapter from a cordova app using Post Method

I am facing an issue with sending image to javascript adapter from Cordova App using WLResourceRequest with WLResourceRequest.GET
Error:
Response Error :
{"status":414,"statusText":"Request URI too
long","responseText":"Request URI is too long","responseHeaders":
{"cache-control":"no-cache,no-store","content-length":"23","content-
type":"text/html","expires":"now","pragma":"no-
cache"},"errorMsg":"Request URI too long","errorCode":"414"}
Cordova App Source Code:
var invocationData = {
"LOCALE":locale,
"CHANNEL":channel,
"CLIENT_OS":os,
"TYPE":type,
"ISSUE_TYPE":issueType,
"LOCATION":loc,
"CONTRACT_ACC_NO":accNo,
"PHOTOS":photo
};
var resourceRequest = new WLResourceRequest(
"/adapters/Report/makeReport",WLResourceRequest.GET);
resourceRequest.setQueryParameter("params", [invocationData]);
resourceRequest.send().then((response) => {
this.content = response.responseJSON;
deferred.resolve(this.content);
},
function(error){
deferred.reject(error);
}
);
Java Script Adapter Source Code:
function invokeBackend(args, proc){
var path = "SEB-Middleware/api/" + proc;
var input = {
method : 'post',
returnedContentType : 'json',
path : path,
body : {
contentType:"application/json; charset=UTF-8",
content: JSON.stringify(args)
}
};
var response = MFP.Server.invokeHttp(input);
return response ;
}
Above code working successful response without passing image(PHOTOS) parameter,
Also tried below code using POST method :
var formParams = {"params": [invocationData]};
var resourceRequest = new WLResourceRequest(
"/adapters/Report/makeReport",WLResourceRequest.POST;
resourceRequest.sendFormParameters(formParams).then(
function(response) {
console.log('return result');
console.log(JSON.stringify(response));
// success flow
},
function(error) {
// fail flow
console.log('return error');
console.log(JSON.stringify(error));
}
);
Response error: "Error: Invalid invocation of method
WLResourceRequest.sendFormParameters; Form value must be a simple
type.
Another Method:
var formParams = {"params": [JSON.stringify(invocationData)]};
var resourceRequest = new WLResourceRequest("/adapters/Report/makeReport",WLResourceRequest.POST);
resourceRequest.sendFormParameters(formParams).then((response) =>
{
this.content = response.responseJSON;
deferred.resolve(this.content);
},
function(error){
deferred.reject(error);
}
);
Response error: "Error: Invalid invocation of method
WLResourceRequest.sendFormParameters; Form value must be a simple
type.
Please can you advise for how to pass the image(PHOTOS) parameter from cordova app to javascript adapter using WLResourceRequest with POST ?

How can i get result's body and status with jQuery

I've been developing a simple RESTful API with NodeJS and Express. When the backend was done and operative, my next step was to make HTML forms to fill the database and consume the API. I decided that using jQuery to submit the data would be a nice idea to get some practice .
So basically I want to get from a $.post the body and status that my app's backend generates whenever it recieves a POST request. Here's the form's script:
$('#addcube').submit(function(event){
//Stop the default behaviour of the submit button
event.preventDefault();
//Get the input values
var $form = $(this),
postData = {
nombre: $form.find('input[name="nombre"]').val(),
brand: $form.find('input[name="brand"]').val(),
capas: $form.find('input[name="capas"]').val(),
kind: $form.find('input[name="kind"]').val()
},
url = $form.attr('action');
$.ajax({
url: url,
type: 'post',
data: JSON.stringify(postData),
contentType: "application/json",
done: function(cube, textStatus, jqxhr){
console.log(JSON.parse(cube));
},
fail: function(jqxhr, textStatus, errorThrown){
console.log(errorThrown.msg);
}
});
});
And here's the backend route for that post:
app.post('/api/cube', cubeController.addCubo);
Which is controlled by this script:
module.exports.addCubo = function(req, res){
var Cube = require('../models/cube');
console.log('POST');
try{
console.log(req.body);
var cubo = new Cube({
nombre : req.body.nombre,
brand : req.body.brand,
capas : req.body.capas,
kind : req.body.kind
});
cubo.save(function(err){
if(!err){
console.log('Nuevo cubo guardado.');
res.send(JSON.stringify(cubo));
res.status(200);
}else{
console.log('Error al guardar: '+err);
res.send('{"status":"400","msg":"bad_request"}');
res.status(400);
}
});
}catch(err){
res.send('{"status":"500","msg":"internal_server_error"}');
}
};
No body property exists at response, use . Set $.post() type to json, or use JSON.parse() at .done(). Also, if sending error, use .fail() to log messages
var send = $.post(url, {
nombre : name,
brand : marca,
capas : layers,
kind : tipo
}, "json"); // set expected response type to `"json"`
// Try to get the result
send.done(function(cube, textStatus) {
console.log(cube, textStatus)
});
// handle errors
send.fail(function(jqxhr, textStatus, errorThrown) {
console.log(textStatus, errorThrown, errorThrown.msg)
});

parse-server updating an existing user field?

What I am trying to do: I am using parse server with javaScript SDK to change a field value for an already existing user.
The code that i am using
var query = new Parse.Query(Parse.User);
query.equalTo("username", "someUserName");
query.find({
success: function(users){
console.log("user found", users);
users.set("name", "new name");
users.save(null,{
success: function(updated){
//worked
},
error: function(error, updated){
//didn't work
}
});
},
error: function(error, users){
console.error("error at querying: ", error);
}
});
The issue : this does not update the name field value.
What i have discovered from researching this issue
: seems like i have to utilize the sessioToken or/and masterKey like this(show below) but that also did not work.
users.save(null,{useMasterKey:true}{
success: function(updated){
//worked
}
I am quite confused at the moment, any help would be appreciated.
Your master key or session token should be the first parameter.Have a look at the Parse.Object.save API
https://www.parse.com/docs/js/api/classes/Parse.Object.html
Try something like this
users.save({useMasterKey:true}, {
success: function(updated){
//worked
}
error: function(err){
}
});

Asynchronous Add/Update save method not updating

I am building a .NET page for a project that adds a new City and State for a new user or updates the City and state if their ID is already in the database. Everything is working fine except for the fact that if a past user clicks submit to update their information, an entirely new entry is added to the database.
I have created the method already in the repository listed below.
public async Task<LocationViewModel> SaveLocationAsync(LocationViewModel model)
{
try
{
var location = new Location()
{
City = model.City,
State = model.State
};
if (model.Id != 0)
{
location.Id = model.Id;
}
_dbcontext.Location.AddOrUpdate(location);
await _dbcontext.SaveChangesAsync();
return model;
}
catch (Exception ex)
{
model.Error = true;
model.ErrorMessages = new List<string>()
{
string.Format("Something went wrong - Message: {0} \n Stack Trace: {1}", ex.Message,
ex.StackTrace)
};
return model;
}
}
I have also built a controller that saves and updates existing records asynchronously shown below.
[System.Web.Mvc.AllowAnonymous]
[System.Web.Http.HttpPost]
public async Task<LocationViewModel> SaveLocationApiAsync(LocationViewModel model)
{
var result = new LocationViewModel();
if (ModelState.IsValid)
{
result = await _locationRepository.SaveLocationAsync(model);
}
return result;
}
In addition, I have added added all of my routes and references.
Why is a new entry put in the database instead of the current one updating? The Javascript is shown below.
self.Submit = function () {
if (self.errors().length !== 0) {
self.errors.showAllMessages();
return;
}
if (isNumber(locationId)) {
self.Location().LocationId(locationId);
swal("Success", "Thank you for your submission \nYour information has been updated.", "success");
}
var newData = ko.mapping.toJSON(self.Location());
var url = "/Admin/SaveLocationApiAsync/Post/";
$.ajax({
url: url,
method: "POST",
data: newData,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
if (result.Error === true) {
swal("Error", result.ErrorMessages.join('\n'), "error");
} else {
//TOdo
}
},
error: function () {
swal("Error", "Something went wrong.\nPlease contact help.", "error");
}
});
};
I apologize if it is a lot. I have checked everything repeatedly and have fixed all bugs. I am out of ideas.
Thanks in advance.
Your url looks to the controller action seems incorrect. You have var url = "/Admin/SaveLocationApiAsync/Post/"; when it should be var url = "/Admin/SaveLocationApiAsync";
Another approach to getting the correct url would be:
var url = '#Url.Action("SaveLocationApiAsync", "<ControllerName>")';
Also, in your ajax error handler you can get the HTTP status code and error message, which would help.
error: function (jqXHR, textStatus, errorThrown) {
swal("Error", "Something went wrong.\nPlease contact help.", "error");
}
EDIT:
I should have prefaced that using Url.Action works when your JavaScript is in a view (assuming Razor view in this case).
Fiddler is great tool to use when debugging ajax calls.

Update StackMob User Object JS-SDK

I am trying to update a user object using the JS-SDK but I am getting Duplicate key for schema error. What is the correct way to update a user object using StackMob JS-SDK? Below is my code
var Usr = StackMob.Model.extend({schemaName: 'user'});
var rid = window.localStorage.getItem("devicetoken");
var usr = new Usr({ username: rid });
usr.set({sendnotification: true });
usr.save({
success: function(model, result, options) { console.log('saved'); },
error: function(model, result, options) {console.debug('failed:'+result.error);}
});
Figured out the answer, you need to use the User object directly. There is no need to extend the model
var user = new StackMob.User({ username: rid, sendnotification: true});
user.save({
success: function(model, result, options) { console.log('saved'); },
error: function(model, result, options) {console.debug('failed:'+result.error);}
});

Categories