How to navigate different to view in JSONP request "callback" method - sencha-touch-2

//Below is my callback method which returns some response code.Now the thing is that i need to navigate to different view from the callback method.This logic i am using in userlogin. Provide me some solution that i can navigate to different view below i declared some code which i used to navigate to different view which works fine outside callback method not inside callback method.
Ext.data.JsonP.request({
url:'url',
method: 'POST',
callbackkey: 'callback',
params: {
userID: user_Id,
password: password,
format: 'json'
},
callback: function (response, value, request) {
//Logic should come here
}
else
{
}
},
failure: function (response, request) {
}
});
enter code here
//Below is the cofig entry
config: {
refs: {
homepage:'HP'
}
}
//I am adding below code in success block but getting error
var noteEditor = this.getHomepage();
Ext.Viewport.animateActiveItem(noteEditor, this.slideLeftTransition);

assuming you doing something like
Ext.data.JsonP.request({
url:'url',
method: 'POST',
callbackkey: 'callback',
params: {
userID: user_Id,
password: password,
format: 'json'
},
scope: this, /// fix handler scope
callback: function (response, value, request) {
if () {
//Logic should come here
var noteEditor = this.getHomepage();
Ext.Viewport.animateActiveItem(noteEditor, this.slideLeftTransition);
}
else
{
}
},
failure: function (response, request) {
}
});
you have to add a scope: this property to the ajax call.
Cheers, Oleg

Related

I cannot find a way to update calendar events on mssql. Posting to my razor page does not work (400 error)

Code to update with a custom button in the calendar:
myCustomButton: {
text: 'Save Events',
click: () => {
var allevents = calendar.getEvents();
$.ajax({
type: 'POST',
contentType: 'application/json',
dataType: 'json',
data: allevents,
url: '/Wishes/Individual/Update',
headers: {
'RequestVerificationToken': '#antiforgery.GetAndStoreTokens(HttpContext).RequestToken'
},
success: function (response) {
alert: ('success');
},
failure: function (response) {
alert: ('failure');
}
});
}
},
According to your description and code, it seems that you'd like to post all events within FullCalendar to your Razor Page handler by making AJAX Post Request(s), and then save/update events on database.
To achieve the requirement, you can refer to the following example.
On JavaScript Client
customButtons: {
myCustomButton: {
text: 'Save Events',
click: function () {
var allevents = calendar.getEvents();
var events = [];
$.each(allevents, function (index, event) {
//console.log(event);
// include only expected data (such as title, start and end etc) in json object `newevent`
// instead of all information of calendar event
var newevent = { "title": event.title, "start": event.start, "end": event.end };
events.push(newevent);
});
$.ajax({
type: 'POST',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify(events),
url: '/Wishes/Individual/Update',
headers: {
'RequestVerificationToken': '#antiforgery.GetAndStoreTokens(HttpContext).RequestToken'
},
success: function (response) {
alert: ('success');
},
failure: function (response) {
alert: ('failure');
}
});
alert('clicked the custom button!');
}
}
},
Razor page handler method
public IActionResult OnPostUpdate([FromBody]List<Event> events)
{
//code logic here
return Content("ok");
}
Custom Event class
public class Event
{
public string title { get; set; }
public string start { get; set; }
public string end { get; set; }
// defind other properties
// such as groupId, url etc based on your requirements
}
Test Result

globalize axios as API wrapper in vue project

I have almost 13 Axios requests in my Vue application. which are almost the same
axios({
method: 'post',
url: `${this.$root.api_url}/v2/cameras/${this.selected.exid}/nvr/snapshots/extract`,
data: {
start_date: moment(this.fromDateTime).format(),
end_date: moment(this.toDateTime).format(),
schedule: this.schedule,
interval: this.interval,
create_mp4: this.create_mp4,
inject_to_cr: this.inject_to_cr,
jpegs_to_dropbox: this.jpegs_to_dropbox,
requester: this.$root.user.email,
api_key: this.selected.api_key,
api_id: this.selected.api_id
}
}).then(response => {
if (response.status == 201) {
this.showSuccessMsg({
title: "Success",
message: "Snapshot Extractor has been added (Local)!"
});
this.$events.fire('se-added', {})
this.clearForm()
} else {
this.showErrorMsg({
title: "Error",
message: "Something went wrong!"
})
}
})
I pass the method, URL and data.. and do a few things in response and in case of error.
How can I reduce that so much code? I have this idea to make an API file for this where, the method will accept, API.get(method, URL, data) and I will have {message, statusCode} in return. and then on the basis of that, I can do other stu7ff.
I tried to follow some documentation online but it didn't work. Is there any suitable way to reduce this code.
Is it even possible to give success and error message as well in API.get or post or delete that it would be very minimal when you send the API request?
EDIT: so i guess you need something like a class here:
class API {
static get(url, callback) {
axios({
method: "get",
url: url,
data: data
}).then(response => {
callback(response);
});
}
static post(url, data, callback) {
axios({
method: "post",
url: url,
data: data
}).then(response => {
callback(response);
});
}
}
API.post("url", data, response => {
console.log(response);
});
API.get("url", response => {
console.log(response);
});
I use yamlful
You make a .yml file which includes
events:
- method: get
get: /events/:id
then API calls become
const response = await this.$api.events.get(2)
Furthermore, I inject methods into my context
// api.js
async function populateEvents (app, id) {
const response = await app.$api.events.get(id)
return response
}
export default ({ app, store }, inject) => {
inject('populateEvents', id => populateEvents(app, id))
}
// any_file.vue
this.populateEvents(12)
and in api.js you can generalize your api calls, so if any 2 api calls do the same stuff, you can refactor that repeated code into a separate method

Difference between POST and GET (hapijs)

I'm new to the hapijs. Can someone tell me what's the difference between POST and GET in hapijs? For some reason my POST method doesn't work at all so I do is INSERT via GET function.
GET:
server.route({
method: 'GET',
path: '/index/{orderId}',
config: {
handler: test,
validate: {
params: {
orderId: Joi.string()
.required()
.description('Order indentifier')
}
}
}
});
And test function:
function test (request, reply) {
console.log(request.params.orderId);
var params = {orderId: request.params.orderId}
connection.query('INSERT QUERY HERE', function (err, res, fields) {
if (err) throw error;
console.log(res);
reply(res);
});
}

Hapi.js reply.redirect() is not working after image upload

I have the following code, in my server. I'm uploading an image using mongoose and s3 and then want to redirect the user to another page but this isn't happening. (the upload is successful).
Routes.js:
{path: '/success', method: 'GET', config: controller.success} ......
controller.js:
imageUpload: {
payload: {
maxBytes: 209715200,
output: 'file',
parse: true
},
handler: function(request, reply) {
var userName = request.auth.credentials.username;
members.findMemberByUsername(userName, function(err, member){
if (err) {
return reply.view('upload', {error: err});
} else if (member) {
var IDImagePath = request.payload.uploadedIDname.path;
console.log(IDImagePath);
members.addID(member, IDImagePath, function(err1){
console.log("add id error", err1);
if (err1){
return reply.view('upload', {error: err1, member: member});
} else {
console.log("SUCCESSFUL!");
return reply.redirect('/success');
}
});
}
});
}
},
success: {
handler: function (request, reply){
request.auth.session.clear();
console.log("success handler working!!");
return reply.view('success');
}
}
The code hits both console.log("SUCCESSFUL") and console.log("success handler working!!") in the controller but the redirect doesn't take place. By the way I'm using 'Jade' as the templating language so I have a success.jade. Thanks.
I found out what the problem was. I'm using AJAX on the client side but didn't have a 'success' method to reload the page:
$('#submitID').click(function(){
var formData = new FormData($('#uploadID')[0]);
$.ajax({
url: '/api/image',
type: 'POST',
xhr: function() { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){
console.log(myXhr.upload);
}
return myXhr;
},
success: function(data) {
window.location.href = "/success"
},
data: formData,
cache: false,
contentType: false,
processData: false
}, "json");
});
I needed window.location.href = "/success" to reload the page. Please note the jQuery Ajax SUCCESS method is different to my '/success' route, they just happen to be the same word.

how to get the server response.responseText after store load extjs 4

I'm having one problem with getting the response.responseText from the server response in extjs 4.
Below is my code to load the store:
store.load({
params: {
'projectid': this.projectid
},
callback: function (records, operation, success, response) {
console.log(records);
console.log(response.responseText);
}
});
Actually, when I made the request with the below function, I properly get the reponse.responseText.
Ext.Ajax.request({
url: 'login/GetLoginCheck.action',
method: 'GET',
params: {
'username': values['username'],
'password': values['password']
},
scope: this,
success: function(response) {
Ext.Msg.alert(response.responseText);
var redirect = response.responseText;
window.location.href = "" + redirect + ".jsp";
},
failure: function(response) {
Ext.Msg.alert('INVALID USERNAME OR PASSWORD');
}
});
So please suggest me how can I get the response.responseText from the store.load() having a callback function.
callback has 3 parameters...
try this :
store.load({
params: {
'projectid': this.projectid
},
callback: function (records, operation, success) {
console.log(operation.response.responseText);
}
});
I have faced a similar problem using Model.load(...), but in my case, operation.response was not defined. So, I have found another way to get it :
Model.load(1, {
success: function () {
// I haven't tested inside this callback yet
},
failure: function (record, operation) {
var response = operation.request.proxy.reader.rawData;
alert(response.message);
}
});
You may also try this..
Ext.create('Ext.data.Store',{
fields[],
proxy:{url:'store_url.json', reader:{type:'json',root:'data'}},
autoLoad:true,
listeners:{
load:function(store, record, success, opts){
var response_text = store.proxy.reader.rawData;
console.log(response_text);
}
}
})
In extjs 3.4 you can use this:
this.historyInvoiceHeaderGrid.store.load({
params:{start:0, limit:20},
callback: function (records, operation, success) {
console.log(this.reader.jsonData);
}});
This property store.reader.jsonData will return full response.
Maybe for someone it would be usefull in extjs 3.
You must set messageProperty in proxy reader in your 'Ext.data.Store'.
reader: {
type: 'json',
root: 'myDataList',
totalProperty: 'myTotalRecord',
successProperty: 'mySuccess',
messageProperty : 'myMsg'
}
when mySuccess returns false then invoked callback: function.
store.load({
params: {start: 0, limit: 15},
callback: function (records, operation, success) {
if (!success) {
try {
Ext.Msg.alert('Sorry !', operation.getError());
// operation.getError() returns myMsg value
}catch (e){
Ext.Msg.alert('Exception !', e);
}
}
}
});
Here is a json return from Java Servlet.
Map<String, Object> myDataMap = new HashMap<>(3);
try {
// Something
myDataMap.put("mySuccess", true);
myDataMap.put("myMsg", "Whats up khomeni !");
} catch (Exception e) {
myDataMap.put("mySuccess", false);
myDataMap.put("myMsg", "Whats wrong with me.");
}
String json = new Gson().toJson(myDataMap);
In Extjs 4.x it is working like this
myStore.load({
url: 'myurl',
method: 'GET',
callback: function(records, operation, success) {
var jsonStr = Ext.JSON.decode(operation.response.responseText);
alert(jsonStr.message);
}
});
In Extjs 5 you have to do like this
myStore.load({
url: 'myurl',
method: 'GET',
callback: function(records, operation, success) {
var message=forecastMethodStore.getProxy().getReader().rawData.message;
}
});
But the key point here is you should set the message in JSON response from java side.
Sample: {"Root":[], "message":"duplicates"}"
Hope this will help someone.