Right now I'm trying to do a simple delete / update / get through the User Id but I'm not getting the data correctly and I don't know if it's because of the ajax function, if it's for my web Api or if it's because of gRPC ,
My question is similar to this link I already asked, so I'll maybe show the simplest part which is the delete and also show the ajax call
Old Link: gRPC and/or WebAPI: How to do a simple Update but using an Id
gRPC Delete:
public override async Task<Empty> Delete(UserFilter requestData,
ServerCallContext context)
{
var data = await _context.Users_5.FindAsync(requestData.UserID);
if(date == null)
{
throw new Exception("User Not Found");
}
_context.Users_5.Remove(data);
await _context.SaveChangesAsync();
return await Task.FromResult(new Empty());
}
WebApi:
[HttpDelete("{Id_user}")]
public async Task<ActionResult<Empty>> DeleteUser([FromBody] UserFilter Id_user)
{
_logger.Log(LogLevel.Information, "Request Received for AuthController::Delete");
/**
if(Id_user == null)
{
return BadRequest("Id not Found idk why");
}
if(Id_user.ToString() != Request.Cookies["LoginUserId"])
{
return BadRequest("Id's is Different");
}
*/
var results = await _userClient.DeleteAsync(Id_user);
_logger.Log(LogLevel.Information, "Sending Response from AuthController::Delete");
return Ok(results);
}
The Javascript Code:
var $users_A = $('#users_A');
var $Id_user = $('#Id_user')
$users_A.delegate('.remove', 'click', function () {
var $li = $(this).closest('li');
var self = this;
debugger;
$.ajax({
url: uri_7 + $Id_user,
type: 'DELETE',
success: function() {
$li.fadeOut(300, function () {
$(this).remove();
});
},
error: function (xhr, textStatus, errorThrown) {
console.log('XHR:' + JSON.stringify(xhr) + '\nTextStatus:' + textStatus + '\nErrorThrown:' + errorThrown);
}
});
});
The stupid error:
XHR:{"readyState":4,"responseText":"{"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1","title" :"One or more validation errors occurred.","status":400,"traceId":"00-82ac37132e06d497f2f7ec082e382273-ba6109fbfa7fd9f8-00","errors":{"$\ ":["The input does not contain any JSON tokens. Expected the input to start with a valid JSON token, when isFinalBlock is true. Path: $ | LineNumber: 0 | BytePositionInLine: 0."],"Id_user":["The Id_user field is required."]}}","responseJSON":{"type":"https://tools.ietf.org/ html/rfc7231#section-6.5.1","title":"One or more validation errors occurred.","status":400,"traceId":"00-82ac37132e06d497f2f7ec082e382273-ba6109fbfa7fd9f8-00","errors":{ "$":["The input does not contain any JSON tokens. Expected the input to start with a valid JSON token, when isFinalBlock is true. Path: $ | LineNumber: 0 | BytePositionInLine: 0."],"Id_user": ["The Id_user field is required."]}},"status":400,"statusText":"error"}
--Conclusion--
Idk what's happening, I have the post and the getAllUsers correct but getting a specific user it gives me a lot of pain, so how to correct this code??
Any Answer/Help is always welcome
Related
I have a problem with jQuery ajax function. I working with API that provides users and RBAC managment. By design this is separated functions, so when i create a user and assign a role for it i should call two requests - first i send 'create user' and it's return a {"success":"true", "id":"[id nuber]"} then i send 'assign role' with params like "{"item":"RoleName", "user_id":"[id from previous request]"}".
There is object "api" which have some methods for work with API. It is a simple wrapper which knocking on www.myurl.api/ and returns json. Because of it may take a long time api object methods takes a handlers that will be run on success and fail. If api now running a request then api.ready == false, otherwise api.aready == true. Result of last request stored in api.data as object.
Problem is that result not saved in api.data in case when two API request cascaded, like:
api.send(params, //params is json for user creation
function(){ //handler on this request result
... //creating another parms for assignment from api.data
api.send(params2, function(){//handler that works if api coorectly creates a new user
... //here i try send a request with params and it fails
})
}
);
code of api.send method:
send: function (entity, request, params, method, handler){
if (!method)
method='POST';
if (request.toLowerCase()=='get')
request = '';
if (request)
request += '-';
api.data = null;
params.apiKey = api.key;
api.ready = false;
api.handler = handler;
$.ajax({
url: this.url+request+ entity,
method: 'GET',
data: params
}).complete(function(msg) {
api.data = JSON.parse(msg.responseText);
if (api.data[0] && api.data[0].meta)
api.data.forEach(function (element, index, array){
element.meta = JSON.parse(element.meta)
});
api.ready = true;
api.handler.call();
});
}
and this is function that calls to create new user
function createUser(){
validateCreateForm();
if (!createValidated )
return;
var values = {
"username": $('#inputUsername').val(),
"password": $('#inputPassword').val(),
"comment": "Added by "+adderUsername
};
api.send('users','add', values, 'POST', function () {
if (api.data.success="true"){
//===========all in this if works ONLY if api works succesfully
//===========and api.data.id is exist and correct
message("success", "Was created username " + values.username);
$('#inputUsername').val('');
$('#inputPassword').val('');
//==========Problem is here
id = api.data.id; //in this var stores id
console.log('api.data.id is ' + id);//undefined, should be some int.
//if write something like id=42 rights will be correcttly assigned for user with id 42
//================================================================
if (!$('#inputRole').val())
return;
api.send('assignments',
'add',
{
"user_id": id,
"item_name": $('#inputRole').val()
},
'POST',
function () {
if (api.data.success="true"){
message("success", "Account was created and permissions granted");
}
else {
message("success", "Inner error. Please, try again later.");
}
}
);
}
else {
message("danger", "Inner error. Please, try again later.");
}
);
}
It is obvious that "result" is coming back as null from the query. If that is the case, why is it calling the "success" routine? I know that the course I am searching for does exist.
Any ideas?
var query = new Parse.Query("Courses");
var CourseObj = new Parse.Object("Courses");
query.equalTo("courseIdFromIOS", request.params.courseIdFromIOS);
query.first({
success: function (result) {
CourseObj = result;
response.success("course lookup good for: " + CourseObj.get("courseName"));
},
error: function () {
response.error("course lookup failed");
}
});
A query always enters success loop if we are able to connect to Parse servers and searched through all the rows even if our query was unsuccessful since there is no error code corresponding to unsuccessful query .Once check this guide and also error codes section.
https://www.parse.com/docs/js/guide#handling-errors
So in your case result is undefined
var query = new Parse.Query("MyClass");
var tmp = new Parse.Object("MyClass");
query.equalTo("username", "This does not exist in table");
query.first({
success: function (result) {
tmp = result;
alert("hii");
alert("course lookup good for: " + tmp.get("name"));
},
error: function () {
alert("helloooo");
}
});
Even in the above code it is entering success loop
So, I'm defining a cloud function that's supposed to make a call to the foursquare api and generate a list of restaurants (each restaurant is a ParseObject) from the returned JSON. I successfully do this, but I run into problems when trying to save these objects to my database and send them back to my phone by calling response.success(). The large code block below saves the list to my database, but if I try
Parse.Object.saveAll(restaurants)
response.success(restaurants)
I end the function before all of the restaurants are saved. I tried using this line instead
Parse.Object.saveAll(restaurants).then(response.success(restaurants))
, but only half of the restaurants get saved before I get the error "Failed with: Uncaught Tried to save an object with a pointer to a new, unsaved object." I also get this error if I call response.success(restaurants) without attempting to save the list. I read that this is a bug in parse preventing someone from printing or passing unsaved ParseObjects. Any ideas? I also tried using .then on the http request, but I get the same issues or a new error: "com.parse.ParseException: i/o failure: java.net.SocketTimeoutException: Read timed out. "
Parse.Cloud.define("callFourSquare", function(request, response) {
//The Parse GeoPoint with current location for search
var geo = request.params.location;
var geoJson = geo.toJSON();
var url = "https://api.foursquare.com/v2/venues/explore?ll=" + geoJson.latitude + ","
+ geoJson.longitude + "§ion=food&sortByDistance=1&limit=50&venuePhotos=1&categoryId=4d4b7105d754a06374d81259&client_id= C043AJBWKIPBAXOHLPA0T40SG5L0GGMQRWQCCIKTRRVLFPTH"
+ "&client_secret=Y1GZZRHXEW1I3SQL3LTHQFNIZRDCTRG12FVIQI5QGUX0VIZP&v=20140715";
console.log(url);
//Call to FourSquare api, which returns list of restaurants and their details
Parse.Cloud.httpRequest({
method: "GET",
url: url,
success: function (httpResponse) {
var restaurants = [];
var json = httpResponse.data;
var venues = json.response.groups[0].items;
console.log(venues.length)
for(i = 0; i < venues.length; i++) {
venue = venues[i].venue;
var RestaurantObject = Parse.Object.extend("Restaurant");
var rest = new RestaurantObject();
try {
rest.set("geoLocation",
new Parse.GeoPoint({latitude: venue.location.lat,
longitude: venue.location.lng}));
} catch(err) {}
try {
rest.set("address", venue.location.address + " " + venue.location.formattedAddress[1]);
} catch(err) {}
try {
rest.set("phoneNumber", venue.contact.formattedPhone);
} catch(err) {}
try {
rest.set("website", venue.url);
} catch(err) {}
rest.set("name", venue.name);
rest.set("lowerName", venue.name.toLowerCase());
try {
rest.set("priceLevel", venue.price.tier);
} catch(err) {}
try {
rest.set("rating", venue.rating/2);
} catch(err) {}
try {
rest.set("storeId", venue.id);
} catch(err) {}
try {
rest.set("icon", venue.photos.groups[0].items[0].prefix + "original"
+ venue.photos.groups[0].items[0].suffix)
} catch(err) {}
restaurants.push(rest);
}
Parse.Object.saveAll(restaurants);
},
error: function (httpResponse) {
response.error("Request failed with response code:" + httpResponse.status + " Message: "
+ httpResponse.text);
}
});
});
I believe your issue is that you aren't returning the Promise from Parse.Object.saveAll(restaurants) when your httpRequest() is complete. Try returning that saveAll() promise and see if it completes.
I can't see what the problem with this is.
I'm trying to fetch data on a different server, the url within the collection is correct but returns a 404 error. When trying to fetch the data the error function is triggered and no data is returned. The php script that returns the data works and gives me the output as expected. Can anyone see what's wrong with my code?
Thanks in advance :)
// function within view to fetch data
fetchData: function()
{
console.log('fetchData')
// Assign scope.
var $this = this;
// Set the colletion.
this.collection = new BookmarkCollection();
console.log(this.collection)
// Call server to get data.
this.collection.fetch(
{
cache: false,
success: function(collection, response)
{
console.log(collection)
// If there are no errors.
if (!collection.errors)
{
// Set JSON of collection to global variable.
app.userBookmarks = collection.toJSON();
// $this.loaded=true;
// Call function to render view.
$this.render();
}
// END if.
},
error: function(collection, response)
{
console.log('fetchData error')
console.log(collection)
console.log(response)
}
});
},
// end of function
Model and collection:
BookmarkModel = Backbone.Model.extend(
{
idAttribute: 'lineNavRef'
});
BookmarkCollection = Backbone.Collection.extend(
{
model: BookmarkModel,
//urlRoot: 'data/getBookmarks.php',
urlRoot: 'http://' + app.Domain + ':' + app.serverPort + '/data/getBookmarks.php?fromCrm=true',
url: function()
{
console.log(this.urlRoot)
return this.urlRoot;
},
parse: function (data, xhr)
{
console.log(data)
// Default error status.
this.errors = false;
if (data.responseCode < 1 || data.errorCode < 1)
{
this.errors = true;
}
return data;
}
});
You can make the requests using JSONP (read about here: http://en.wikipedia.org/wiki/JSONP).
To achive it using Backbone, simply do this:
var collection = new MyCollection();
collection.fetch({ dataType: 'jsonp' });
You backend must ready to do this. The server will receive a callback name generated by jQuery, passed on the query string. So the server must respond:
name_of_callback_fuction_generated({ YOUR DATA HERE });
Hope I've helped.
This is a cross domain request - no can do. Will need to use a local script and use curl to access the one on the other domain.
based on that a link!, I'm trying adapt this code to my project. however when I click save this error appears:
SyntaxError: missing ) in parenthetical Warning: main(): It is not
safe to rely on the system's timezone se
My js
function saveItem(index) {
var row = $('#dgusu').datagrid('getRows')[index];
var url = row.isNewRecord ? 'app/cadusuarios_acao.php?opcao=C' :
'app/cadusuarios_acao.php?opcao=A?id=' + row.id;
$('#dgusu').datagrid('getRowDetail', index).find('form').form('submit', {
url: url,
onSubmit: function () {
return $(this).form('validate');
},
success: function (data) {
data = eval('(' + data + ')');
data.isNewRecord = false;
$('#dgusu').datagrid('collapseRow', index);
$('#dgusu').datagrid('updateRow', {
index: index,
row: data
});
}
});
}
Someone can tell me where I am going wrong?
Thanks