I have web service asmx has method GetDataBySystemUser(SystsemUser systemUser) takes object parameter.
I can use Ajax to call this method passing object as JSON and working fine, but how to do that using xui and xhr like below code?
var url = "WebServiceTest.asmx/GetDataBySystemUser";
var SystemUser = new Object();
SystemUser.Name = "Web";
SystemUser.Status = "AWeb";
var FormData = JSON.stringify({ systemUser: SystemUser });
x$('#bodyMain').xhr(url, {
method: 'post',
data: FormData,
callback: function () {
alert(this.responseText.d);
}
});
Related
I have a fileupload HTML element in my DOM and it currently gets multiple files and calls "add" function for each file. For each file, a signed url is received from an ajax call to the related api. After the succesful ajax call to api, I want to call the data.submit() method of the parent function which is the function in fileupload method as first argument.
How may I be able to access that just after "xhr.setRequestHeader('Content-Type', file.type);" ?
The primary inspiration is from this link :http://kevindhawkins.com/blog/django-javascript-uploading-to-google-cloud-storage/
$("#fileupload").fileupload({
dataType: 'json',
sequentialUploads: true,
add: function(e, data) {
$.each(data.files, function(index, file) {
// pack our data to get signature url
var formData = new FormData();
formData.append('filename', file.name);
formData.append('type', file.type);
formData.append('size', file.size);
// Step 3: get our signature URL
$.ajax({
url: '/api/getsignedurl/',
type: 'POST',
processData: false,
contentType: false,
dataType: 'json',
headers: {
'X-CSRFToken': Cookies.get('csrftoken'),
},
context: 'hello',
data: formData,
}).done(function (data) {
// Step 5: got our url, push to GCS
const xhr = new XMLHttpRequest();
if ('withCredentials' in xhr) {
xhr.open("PUT", data.signed_url, true);
}
else if (typeof XDomainRequest !== 'undefined') {
xhr = new XDomainRequest();
xhr.open("PUT", data.signed_url);
}
else {
xhr = null;
}
xhr.onload = () => {
const status = xhr.status;
if (status === 200) {
//alert("File is uploaded");
} else {
}
};
xhr.onerror = () => {
};
xhr.setRequestHeader('Content-Type', file.type);
//data.submit();
});
});
},
If the $this = $(this) is defined prior to the $.each loop :
submit: function(e, data) {
var $this = $(this);
$.each(data.files, function(index, file) { ...
Then the following can be used to access the data in the parent function
this.primary_data.headers={'Content-Type': file.type};
this.primary_data.jqXHR = $this.fileupload('send', this.primary_data);
I am using Angular 2 and Django 1.10.6. I create a post method. after send request from front-end, showing CSRF token missing or incorrect.
user.html
<form #f="ngForm" (ngSubmit)="createUser(f.value, f.valid,f)" novalidate>
....
</form>
Angular2 components
createUser(model: User, isValid: boolean, f: any) {
// check if model is valid
// if valid, call API to save customer
if (isValid) {
this.userCreateService.createUser(model).subscribe(
res => {
this.success = "User Create Success";
this.user = new User();
this.errorMsg=null
},
err => {
this.errorMsg = err;
this.success=null;
});
}
}
This is my Angular2 service
#Injectable()
export class UserCreateService {
constructor(private http: Http) { }
// private instance variable to hold base url
private userCreateUrl = '/api/user/users/';
// Add a new User
createUser(body: Object): Observable<User> {
let bodyString = JSON.stringify(body); // Stringify payload
let headers = new Headers({ 'Content-Type': 'application/json' }); // ... Set content type to JSON
let options = new RequestOptions({ headers: headers }); // Create a request option
return this.http.post(this.userCreateUrl, body, options) // ...using post request
.map(this.extractData) // ...and calling .json() on the response to return data
.catch(this.handleError); //...errors if any
}
After few moment of asking question,I have resolved my issue this way.
created method in angular 2 service.
getCookie(name) {
let value = "; " + document.cookie;
let parts = value.split("; " + name + "=");
if (parts.length == 2)
return parts.pop().split(";").shift();
}
And replace
let headers = new Headers({
'Content-Type': 'application/json'}); // .Set content type to JSON
to
let headers = new Headers({
'Content-Type': 'application/json',
'X-CSRFToken': this.getCookie('csrftoken')
}); // ... Set content type to JSON
in createUser() angular service method.
I want to return a Partial View in ajax call in Sitecore, I am already using web APIs, i can return JSON object, but i want to return the view with HTML :
[HttpGet]
public ActionResult StoreSearchResultsPartial()
{
return PartialView("/views/components/StoreSearchResults.cshtml");
}
my ajax call :
var ajaxUrl = "/api/sitecore/components/StoreSearchResultsPartial"
$.ajax({
type: "GET",
url: ajaxUrl,
contentType: "application/json; charset=utf-8",
success: function (result) {
$("#searchResults").html(result);
},
error: function (result) {
}
});
i am using web API for other functionalities, so i added my routing :
public void Process(PipelineArgs args)
{
var config = GlobalConfiguration.Configuration;
RouteTable.Routes.MapHttpRoute(
name: "NamedActionApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
).RouteHandler = new SessionRouteHandler();
config.Routes.MapHttpRoute("DefaultApiRoute",
"api/{controller}/{id}",
new { id = RouteParameter.Optional });
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
}
When I comment this routing everything is working fine.
It is working fine now, I changed my routing to start with something not "api", so i changed this api/{controller}/{action}/{id} to be mywebapi/{controller}/{action}/{id}, then i was able to call : /api/sitecore/components/StoreSearchResultsPartial
I'm using Ember-simple-auth and trying to return data from my custom authenticator back into the controller that did the authenticating.
in my authenticator/custom.js:
authenticate(identification, password) {
return new Ember.RSVP.Promise(function (resolve, reject) {
var loginURL = 'https://domain.com/login';
var authObj = Ember.Object.create({"identity":identification,"password":password});
var hash = authObj.getProperties('identity', 'password');
var stringHash = JSON.stringify(hash);
var xhr = new XMLHttpRequest();
xhr.open("post", loginURL);
xhr.onreadystatechange = handler;
xhr.responseType = 'json';
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('Format', 'JSON');
xhr.send(stringHash);
function handler() {
if (this.readyState === this.DONE) {
if (this.status === 200) {
console.log('response is: ',this.response); /// <-- returns good response data
resolve(this.response);
} else {
reject( 'failed with status: [' + this.status + ']');
}
}
}
and in my login controller:
authenticate() {
let { identification, password } = this.getProperties('identification', 'password');
var session = this.get('session');
session.authenticate('authenticator:custom', identification, password).then((reason) => {
console.log('failed login',reason);
});
}
},
But I'd really like to be able to handle the resolve function and get it's value payload from the authenticate promise.
If I change the .catch to a .then the response function is successfully called but always has an undefined value as its payload:
session.authenticate('authenticator:custom', identification, password).then(
(response) => {
console.log('response: ',response); //// <---- always 'undefined'
this.setUserWithData(response);
},
(reason) => {
this.set('Login failed: ',reason);
}
);
}
Even if I restructure the promise, rearrange how the function is called, the first function from an RSVP is successfully called, but has an undefined payload. The second function from an RSVP always has a correct payload.
I tried reversing the resolve/reject:
Ember.RSVP.Promise(function (resolve, reject){
to
Ember.RSVP.Promise(function (reject, resolve){
and the function successfully carries the response, but the simple-auth now believes it has failed its authorization.
I'd like to be able to pass the response payload into my controller. Or, if that can't be done, how can I inject data from the response into my session and ember-data store? It didn't seem like good practice to call and insert data into the store from within the authenticate function of the authenticator.
The session's authenticate method doesn't resolve with a value. Check the API docs: http://ember-simple-auth.com/api/classes/SessionService.html#method_authenticate
In order to deal with the response from the authentication route, I used the function sessionAuthenticated to deal with the returned data.
So, the authenticate function in authenticators/custom.js
authenticate(identification, password) {
return new Ember.RSVP.Promise(function (resolve, reject) {
var loginURL = 'https://domain.com/login';
var authObj = Ember.Object.create({"identity":identification,"password":password});
var hash = authObj.getProperties('identity', 'password');
var stringHash = JSON.stringify(hash);
var xhr = new XMLHttpRequest();
xhr.open("post", loginURL);
xhr.onreadystatechange = handler;
xhr.responseType = 'json';
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('Format', 'JSON');
xhr.send(stringHash);
function handler() {
if (this.readyState === this.DONE) {
if (this.status === 200) {
console.log('200 response: \r',this.response);
resolve(this.response);
} else {
console.log('failure response',this.response);
reject(this.response);
}
}
}
});
},
With the sessionAuthenticated() event taking place in routes/application.js:
sessionAuthenticated: function(){
var session = this.get('session');
var data = session.get('data');
var response = data.authenticated;
console.log('sessionAuthenticated()',response);
},
sessionInvalidated: function(){
console.log('sessionInvalidated()',response);
},
From the sessionAuthenticated function, the response variable contains all the information passed to it from authenticate(response) inside the authenticator.
//Route
url: "https://xxxxxx.com/api/entries",
users: "https://xxxxxx.com/api/users/",
model: function(){
var localData = JSON.parse(localStorage.getItem("user"));
var data = { auth_token: localData.user_token };
return new Ember.RSVP.hash({
logs: Ember.$.ajax({ url: this.get('url'), headers: { "X-Api-Token": data.auth_token } }),
team: Ember.$.ajax({ url: this.get('users'), headers: { "X-Api-Token": data.auth_token } })
});
}
//controller
actions:{
deleteWorklog: function( worklogId ){
var model = this.get('model.logs');
var data = { auth_token: this.get('local_data').user_token };
Ember.$.ajax({
method: "DELETE",
url: this.get('url') + "/" + worklogId,
headers: { 'X-Api-Token': data.auth_token }
}).then(function(data){
//how do i do it?
})
},
loadMore: function(){
var model = this.get('model.logs');
var url = this.get('url');
var today = new Date();
today.setDate(today.getDate() - this.get('from'));
console.log(today);
url += "?from="+ today.toISOString();
Ember.$.ajax({
url: url,
headers: { "X-Api-Token": data.auth_token }
}).then(function(data) {
model.replace(0, model.length, data);
});
var initial = this.get('from') + 10;
this.set('from', initial);
}
}
}
I'm blocked after the request, i need to refresh my model but i've to do cmd + R to see the change, is there a method re-call the model or something like that?
I've added another things maybe help
There's two ways that I can think of. The first is just to call the refresh method on the route. This is by far the simplest. Just call it and Ember will re-call the model hook for that route and any child routes. In your case, I would send an action from your controller to your route, then have your route refresh itself in that action handler.
The second way would be to manually re-get your data and set it on the controller. Perhaps something like this:
// route.js
actions: {
refreshModel: function() {
var route = this;
Ember.$.ajax({ ... }).then(function(data) {
route.get('controller').set('model', data);
});
}
}
However, I wouldn't recommend this method over the first. There are too many variables when dealing with Ember routing and it's easier just to let Ember handle it all.
You either want to use model.reload to refresh the record from the server:
http://emberjs.com/api/data/classes/DS.Model.html#method_reload
Or you may want to delete the record local:
http://emberjs.com/api/data/classes/DS.Model.html#method_deleteRecord
Or you may want to use model.destroyRecord to let Ember do the delete request (remote + local):
http://emberjs.com/api/data/classes/DS.Model.html#method_destroyRecord
I think it would be the best to use model.destroyRecord, but I assume there's a reason you do this manually?