I want to memorize the response of an ajax request, how I can do it?
In the code above, I found "" in the console...
How can I do it? any suggests?
var jsoncolumnset = '';
Ext.Ajax.request({
scope: this,
url: 'index.php',
params: {
m: 'Columnset',
a: 'readDefault'
},
reader: {
type: 'json',
root: 'rows'
},
success: function(response){
//Passo tutto il json (dovrebbe essere fatto un decode, ma viene gestito da Alfresco)
jsoncolumnset = response.responseText;
this.getStore('Documents').proxy.extraParams.columnset = response.responseText;
},
failure: function(){
//TODO: gestione fallimento chiamata
}
});
console.log(jsoncolumnset);
Ajax is asynchronous so while you have started the request in your Ext.Ajax.request call, the response has not come back by the time console.log(jsoncolumnset) is being executed.
The 'success' method will execute when the server response comes back to the browser which could be milliseconds or seconds later - either way the code mapped to the 'success' event is executed after the console.log executes.
So it appears the snippet is from code nested in some object since you have the "this" scope in place. .
You can add some event based logic that works nicely with ajax. Here is an idea:
// add this custom event in line with other bindings or in the objects constructor or a controllers init method
this.on('columnsready', this.logColumns);
// add this method to the main object
handleColumnResponse: function () {
//Passo tutto il json (dovrebbe essere fatto un decode, ma viene gestito da Alfresco)
this.jsoncolumnset = response.responseText;
this.getStore('Documents').proxy.extraParams.columnset = response.responseText;
// fire the custom event
this.fireEvent('columnsready');
},
// add this as an example of where you would put more logic to do stuff after columns are setup
logColumns: function () {
console.log(this.jsoncolumnset);
},
Ext.Ajax.request({
scope: this,
url: 'index.php',
params: {
m: 'Columnset',
a: 'readDefault'
},
reader: {
type: 'json',
root: 'rows'
},
// map to the handler method in the main object
success: this.handleColumnResponse,
failure: function(){
//TODO: gestione fallimento chiamata
}
});
Related
Is it possible to call a function in success callback of ajax request?
For example I have something like that :
constructor(private http: HttpClient,private serviceComposition: CompositionService) { }
[...]
save() {
var isValid = this.isValidCompo();
if (true) {
var toSend = JSON.stringify(this.setupComposition);
$.ajax({
url: "/api/setup/composition/addSetupComposition",
type: 'POST',
dataType: "json",
data: 'setupComposition=' + toSend,
success:function(response){
//console.log("Success Save Composition");
},
error: function(XMLHttpRequest,textStatus,errorThrown){
console.log("Error Save Compo");
}
}).done(function(data){
this.serviceComposition.changeValue(isValid);
})
}
}
I want to call a function of my service (named : changeValue() ) if my ajax request is a success.
But I have this error message : core.js:12632 ERROR TypeError: Cannot read property 'changeValue' of undefined
Do you know if it's possible to resolve that ?
I am suspecting this binding is going wrong in call backs,
prefer using arrow function because of "this" operator binding.
if (true) {
var toSend = JSON.stringify(this.setupComposition);
$.ajax({
url: "/api/setup/composition/addSetupComposition",
type: 'POST',
dataType: "json",
data: 'setupComposition=' + toSend,
success:function(response){
//console.log("Success Save Composition");
},
error: function(XMLHttpRequest,textStatus,errorThrown){
console.log("Error Save Compo");
}
}).done((data) => {
this.serviceComposition.changeValue(isValid);
})
}
if not u can store this reference in a variable and call it
var self = this;
if (true) {
var toSend = JSON.stringify(this.setupComposition);
$.ajax({
url: "/api/setup/composition/addSetupComposition",
type: 'POST',
dataType: "json",
data: 'setupComposition=' + toSend,
success:function(response){
//console.log("Success Save Composition");
},
error: function(XMLHttpRequest,textStatus,errorThrown){
console.log("Error Save Compo");
}
}).done(function(data){
self.serviceComposition.changeValue(isValid);
})
}
Use an arrow function to access this of your parent scope. In your example, this is referring to your jQuery XHR object.
So:
// [parent scope]
$.ajax({
...
}).done((data) => {
// [child scope]
// `this` now refers to [parent scope], so the following is valid
this.serviceComposition.changeValue(isValid);
});
Another common practice prior to arrow functions (ES6) would've been assigning a const self = this; variable in the [parent scope] area to be accessed in the child method. Either method works the same.
Also check out the MDN docs on this. It's a confusing topic for many.
My App Flow
In my App - Dashboard,
I have the SignalR scripts included which fetches new data as and when new data arrives from the device
It also has ajax script that hits on the Controller to fetch data from the back end - when a Get button is clicked.
Ajax Call mentioned in #2 above takes more than 2 minutes if new data keeps getting in (i.e when SignalR is continuously fetching data and publishing to all connected clients).
Else
the Ajax Call Point#2 above takes very less time to get the data.
Any ideas, better way, ... on how I can avoid the slowness in the ajax call #2 even if SignalR continuously fetches data.
This is my #2 Ajax Call ==> Call to the Home Controller Action Method SignalList
$('#DeviceID').on('change', function () {
$('#DeviceName').text("Device : " + $('#DeviceID option:selected').text());
$.ajax({
url: "/Home/SignalList",
type: "POST",
data: { deviceID: $('#DeviceID').val() },
//contentType: "application/json; charset=utf-8",
dataType: "html",
//cache: false,
//async: true,
success: function (result) {
//alert("AAA");
$('#signalCheckListBox').html(result);
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
This is SignalR script
(function () {
// Defining a connection to the server hub.
var signalHub = $.connection.signalHub; //alert("ACCC");
// Setting logging to true so that we can see whats happening in the browser console log. [OPTIONAL]
$.connection.hub.logging = true;
// Start the hub
$.connection.hub.start();
// This is the client method which is being called inside the SignalHub constructor method every 3 seconds
signalHub.client.SendSignalData = function (signalData) {
dModel = signalData;
updateSignalData(signalData);//<============ # Statekemnt A
};
$.connection.hub.disconnected(function () {
setTimeout(function () {
$.connection.hub.start();
}, 5000); // Restart connection after 5 seconds.
}); }());
The statement A marked above is a method which (1)updates different html elements in the UI and also (2)sends an email on a condition.
For sending the email too it hits the same controller Home (??? Would that be the problem???)
The email ajax call is below ==> Its a call to Home Controller Action Method Communicate
function email(alarmSignalInfo) {
$.ajax({
url: "/Home/Communicate",
type: "POST",
dataType: "json",
//data: { alarmSignalInfo: JSON.stringify(alarmSignalInfo) },
data: { alarmSignalInfo: alarmSignalInfo },
//cache: false,
//async: true,
success: function (result) { onSuccess(result); }
}); }
I have a piece of code which goes as following:
var o_titular = {id:'01',fecha:'2014-01-01'};
var o_dependientes = [
{id:'02',fecha:'2014-02-02'},
{id:'03',fecha:'2014-03-03'}
];
var o_fecha = '2014-05-05';
$("#documento-antiguedad").ajaxSubmit({
dataType: 'json',
data: {
titular: o_titular,
dependientes: o_dependientes,
fecha: o_fecha
},
success: function(r) {
alert("yay success");
}
});
I'm forced to make this ajaxSubmit (this is a simplified code, but the complete case involves file uploading and such) but when I see the data I send in the POST request i got the following:
titular [object Object]
dependientes [object Object],[object Object]
fecha 2014-05-05
of course I want to fiddle with the content of the objects, not the object itself. How can I send this parameters as JSON objects with ajaxSubmit?
Thank you in advance
EDIT:
When I make a regular ajax call:
var o_titular = {id:'01',fecha:'2014-01-01'};
var o_dependientes = [
{id:'02',fecha:'2014-02-02'},
{id:'03',fecha:'2014-03-03'}
];
var o_fecha = '2014-05-05';
$.ajax({
url:'/pendientes/index/creatependienteantiguedad/',
dataType: 'json',
data: {
titular: o_titular,
dependientes: o_dependientes,
fecha: o_fecha
},
success: function(r) {
alert("yay success");
}
});
I get the following:
dependientes[0][fecha] 2014-02-02
dependientes[0][id] 02
dependientes[1][fecha] 2014-03-03
dependientes[1][id] 03
fecha 2014-05-05
titular[fecha] 2014-01-01
titular[id] 01
That's exactly what I want to get, but with ajaxSubmit instead of Ajax.
You could use:
JSON.stringify(o_dependientes);
That will turn the JSON object into a string
I'm using MooTools 1.4.1. I want to create an ajax post requst, but I can't figure out how to construct the "data" attribute, which I wish to contain the name value pairs of a form whose id is "myForm".
$('save').addEvent('click', function(event) {
var req = new Request({
method: 'post',
url: 'save',
data: { ... },
onRequest: function() {
// on request
},
onComplete: function(response) {
alert(response);
});
});
Anyone know how I should populate the "data" attribute? Thanks, - Dave
You can use
$('myForm').toQueryString();
Alternatively, The MooTools More package has a Form.Request() class to send a Form using Ajax.
As Savageman commented, you can throw your form element into toQueryString() and send it through in the data property, or by running .send() or .post() on the request object.
You also seem to be missing a closing squiggly bracket.
Anyhow, this is how I make AJAX requests:
new Request({
url: 'http://url/to/ajax/script.php',
onSuccess: function(data) {
doStuff();
}
}).post('action=foo&bar=baz');
I'd recommend you use Request.JSON if you're planning on sending stuff back. It's less "shotgun approach"-ey.
You can just pass form element to "data" property, and conversion is automatic.
var req = new Request({
method: 'post',
url: 'example.com/form.php',
data: $('myForm'),
onRequest: function() {
// on request
},
onComplete: function(response) {
alert(response);
}
});
data - (mixed: defaults to '') The default data for Request:send, used when no data is given. Can be an Element, Object or String.
If an Object is passed the Object:toQueryString method will be used to convert the object to a string.
If an Element is passed the Element:toQueryString method will be used to convert the Element to a string.
http://mootools.net/docs/core/Request/Request
I need to assign the ajax response to a global variable so that i can use it thoughout my application. The obvious problem is that ajax requests are async thus complicating things.
I have tried to initialize an object before the ajax call, then assigning the response fron inside the success but that didn't work either.
Any ideas?
Example code
var p = {};
loadLang('en');
function loadLang(code) {
Ext.Ajax.request({
url : '/LoadLanguage.html',
method : 'POST',
params :{'code':code},
timeout : 250,
success : function(response, opts) {
obj = Ext.decode(response.responseText);
p = obj;
},
callback : function(o,s,r)
{
}
});
}
var myValue={item:"pie"};
Ext.Ajax.request({
url: 'test.php',
params: {
id: 1
},
success: function(response){
alert(response);
window.myValue.response=response; //yay for global scope.
console.log(window.myValue);//This has to be here,
//else it gets logged before the call gets completed.
}
});