I have this code to get two parts of data, these two ajax requests get data from php class.
{
xtype: 'button',
formBind: true,
id: 'saveLicenceBtn',
text: 'Save',
listeners: {
click: function (c) {
//first ajax request
var d = Ext.Ajax.request({
url: 'system/index.php',
params: {
class: 'generatemultiple',
method: 'getSession'
},
success: function (response) {
var object = Ext.decode(response.responseText, true);
console.log(object);
},
failure: function (response) {
var object = Ext.decode(response.responseText, true);
console.log(object);
}
});
//second ajax request
Ext.Ajax.request({
url: 'system/index.php',
method: 'POST',
params: {
class: 'generatemultiple',
method: 'add',
data: Ext.encode({
count: Ext.getCmp('count').getValue(),
start_date: Ext.getCmp('startdateTextField').getValue(),
end_date: Ext.getCmp('enddateTextField').getValue(),
duration: Ext.getCmp('durationTextField').getValue(),
expiry_date: Ext.getCmp('expirydateTextField').getValue(),
product_id: Ext.getCmp('productidTextField').getValue(),
company_id: Ext.getCmp('companyidtf').getValue(),
token: d
})
},
success: function (response) {
Ext.MessageBox.alert('Status', 'Success');
Ext.getStore('LicenseStore').reload();
Ext.getStore('LicenseAllStore').reload();
Ext.getStore('LicenseFeaturesStore').reload();
Ext.getStore('HardwareStore').reload();
Ext.getStore('DropdownLicenseStore').reload();
Ext.getStore('GridHardwareStore').reload();
Ext.getStore('HardwareAllStore').reload();
Ext.getCmp('addLicenseWindow').close();
},
failure: function (response) {
Ext.MessageBox.alert('Status', 'Failure');
Ext.getCmp('addLicenseWindow').close();
}
});
}
}
}
The first ajax request gets a session variable from the webpage, and the second ajax request sends this token with the ajax request. What I need to know is how do I do what is shown here without getting this error.
Uncaught RangeError: Maximum call stack size exceeded
I know what the error means and I am aware of the reason why its occuring, but i cant find a solution. it keeps occuring because I have two functions calling each other so it errors in the web console.
What i tried alternatively was this
ONCLICK
click: function (c) {
Ext.Ajax.request({
url: 'system/index.php',
method: 'POST',
params: {
class: 'generatemultiple',
method: 'add',
data: Ext.encode({
count: Ext.getCmp('count').getValue(),
start_date: Ext.getCmp('startdateTextField').getValue(),
end_date: Ext.getCmp('enddateTextField').getValue(),
duration: Ext.getCmp('durationTextField').getValue(),
expiry_date: Ext.getCmp('expirydateTextField').getValue(),
product_id: Ext.getCmp('productidTextField').getValue(),
company_id: Ext.getCmp('companyidtf').getValue(),
token: '<?php echo $_SESSION["user_id"] ?>'
})
},
success: function (response) {
Ext.MessageBox.alert('Status', 'Success');
Ext.getStore('LicenseStore').reload();
Ext.getStore('LicenseAllStore').reload();
Ext.getStore('LicenseFeaturesStore').reload();
Ext.getStore('HardwareStore').reload();
Ext.getStore('DropdownLicenseStore').reload();
Ext.getStore('GridHardwareStore').reload();
Ext.getStore('HardwareAllStore').reload();
Ext.getCmp('addLicenseWindow').close();
},
failure: function (response) {
Ext.MessageBox.alert('Status', 'Failure');
Ext.getCmp('addLicenseWindow').close();
}
});
}
forgive the indentation. End goal of what I am trying to do is send the session variable from the php with this ajax request
You can make first ajax request as a synchronous call So that second ajax request will wait for the first ajax request to complete. Set async: false in the first request.
Related
I'm developing a drill down chart using Canvasjs and MVC5. I have a Controller called JsonController that contains several Tasks that return Json. They're all quite similar, but accept more arguments as the layers increase. Layer 0 is the default layer.
[HttpPost]
public async Task<IActionResult> GetLayer0(string datePassedIn)
{
string orgCode = User.Identity.GetOrgCode();
DateTime? processDate;
DateTime defaultDate = DateTime.Today.AddDays(-1); //default yesterday
try
{
processDate = DateTime.ParseExact(datePassedIn, inputDateFormat, cultureProvider);
}
catch (FormatException ex)
{
_logger.LogError(ex, "Error formatting date {datePassedIn} did not match {inputDateFormat}. using default date {defaultDate}", null);
processDate = defaultDate;
}
List<DataPoint> dataPoints = new List<DataPoint>();
IEnumerable<EventTypeLayer1> results = await _context.EventTypeLayer1Results
.FromSql($"usp_dd_EventType_0 #p0, #p1", orgCode, processDate)
.ToListAsync();
foreach (EventTypeLayer1 result in results)
{
dataPoints.Add(new DataPoint(result.Value, result.Title, result.Colour));
}
return Json(dataPoints);
}
In the javascript, the ajax calls are managed with an array
var ajaxOptions = [
{
url: "~/Views/Json/GetLayer0",
data: {
layer: 0,
processDate: encodeURIComponent(formatDateInput(param.processDate)),
orgCode: encodeURIComponent(param.orgCode)
},
callback : handleLayer0
},
{
url: "~/Views/Json/GetLayer1",
data: {
layer: 1,
processDate: encodeURIComponent(formatDateInput(param.processDate)),
orgCode: encodeURIComponent(param.orgCode),
eventType: encodeURIComponent(param.eventType)
},
callback : handleLayer1
},
{
url: "~/Views/Json/GetLayer2",
data: {
layer: 2,
processDate: encodeURIComponent(formatDateInput(param.processDate)),
orgCode: encodeURIComponent(param.orgCode),
eventType: encodeURIComponent(param.eventType),
driverId: encodeURIComponent(param.driverId)
},
callback : handleLayer2
}
];
function doAjax( layerIndex) {
$.ajax({
type: "POST",
cache: false,
dataType: "json",
url: ajaxOptions[layerIndex].url,
data: ajaxOptions[layerIndex].data,
success: function (serverResponse) {
//once a successful response has been received,
//no HTTP error or timeout reached,
//run the callback for this request
ajaxOptions[layerIndex].callback(serverResponse);
},
complete : function () {
//note that the "success" callback will fire
//before the "complete" callback
console.log("Ajax call complete");
}
});
}
When the ajax fires, I'm getting Errors
https://localhost:44388/~/Views/Json/GetLayer0 error 404
https://localhost:44388/Json/GetLayer0 error 405
#Url.Action("GetLayer0", "JsonController") renders blank
I'm a bit confused. What should I do?
Edit: Here's the actual AJAX call
function doAjax( layerIndex) {
$.ajax({
type: "POST",
cache: false,
dataType: "json",
url: ajaxOptions[layerIndex].url,
data: ajaxOptions[layerIndex].data,
success: function (serverResponse) {
//once a successful response has been received,
//no HTTP error or timeout reached,
//run the callback for this request
ajaxOptions[layerIndex].callback(serverResponse);
},
complete : function () {
//note that the "success" callback will fire
//before the "complete" callback
console.log("Ajax call complete");
}
});
}
You are callig view urls instead of controller functions
It should be like
{
url: "/youcontrollername/GetLayer0",
data: {
layer: 0,
processDate: encodeURIComponent(formatDateInput(param.processDate)),
orgCode: encodeURIComponent(param.orgCode)
},
callback : handleLayer0
},
I have 2 functions: one to add and another to delete. I would like to reuse the same ajax call to send the parameters that are added or deleted. How can I optimize my function?
Here is my code at the moment
jQuery(document).ready(function () {
function ajaxCall(action, callback) {
jQuery.ajax('/index.php', {
type: 'POST',
dataType: 'json',
data: {
option: 'quotes',
view: 'request',
task: action,
format: 'raw',
tmpl: 'component'
},
success: function (response) {
if (response.error == true) {
alert(response.errors.join('\n'));
}
else if (response.status == "DONE") {
callback(false);
}
},
error: function (xhr) {
console.log("Error: ", JSON.stringify(xhr));
callback(true);
}
});
}
jQuery('#ajax_add').click(function (event) {
event.stopPropagation();
var id = jQuery('#id').val();
var price = jQuery('#price').val();
//I want to send two variables: id, price
ajaxCall("addData", function (error) {
if (error) {
alert("Error!.");
}
else {
alert("It's OK!");
}
});
});
});
The function to delete is similar to "addData" function, it also calls "ajaxCall" and will send parameters to remove.
I'm blocked and I do not know how to solve it, I hope you can give me some help, thanks
You could add a new argument to the ajaxCall function and send the parameters as an object them merge them with the data you've in the function like :
function ajaxCall(action, params, callback) {
Then in the ajax call :
jQuery.ajax('/index.php', {
type: 'POST',
dataType: 'json',
data: $.extend(params, {
option: 'quotes',
view: 'request',
task: action,
format: 'raw',
tmpl: 'component'
}),
...
The call inside the event will be like :
ajaxCall("addData", {id: id, price: price}, function (error) {
I have to veryfiy the response of the ajax call in my sencha test.
plz advise how to do it.. below is my sample code
beforeEach(()=> {
sim = Ext.ux.ajax.SimManager.init({});
controller = Ext.create('xxxx.controller.Search');
AutoLink = Ext.create('xxxx.model.search.AutoLink', {
objectType: 'myobj'
});
});
it('Should run processResponse when doSearch executes', function() {
const callback = () => {};
sim.register({
'abc.com/myurl.aspx': {
status: 401,
responseText: JSON.stringify({
'success': true,
'data': [{
'autoLink': false, 'status': 'OK', 'objectType': 'Person',
'results': [{ 'ref': 12345, 'managedBy': '01', 'ethnicAppearance': '1', 'gender': '1', 'rules': ['Forename, surname','nickname, DOB']}],
'gridDescriptor': [{'fields': [{'name': 'surname','text': 'Surname','width': 100}],
'sortOrders': ['surname','forename1']
}]
}]
})
}
});
spyOn(controller, 'doSearch'); // internal method which calls the Ext.Ajax
spyOn(controller, 'processResponse'); // internal method which process the response
controller.doSearch(AutoLink, callback, this); // making an ajax call
setTimeout(function () {
expect(controller.processResponse).toHaveBeenCalled();
}, 1000);
});
now when run the test case processResponse gets called, which is fine, but i want to verify the ajax response.
This is how I am doing it:
$.ajax({
url: _spPageContextInfo.webServerRelativeUrl + "/_api/web/lists/getbytitle('Test%203')/items(" + itemId + ")/FieldValuesAsText",
method: 'GET',
headers: {
'accept': 'application/json;odata=verbose'
}
}).then(function (data) {
console.log(data);
}
I don't know if this will help you to achieve exactly what you are looking for. But I would suggest giving it a shot. Then you can go to your console and save the data object to a variable (just for debugging purposes) or just from the console itself look at the object chain and check the data which was returned by your ajax call. So in my case I would find let's say name of the employee here:- data.d.results[0].PreferredName. Then if I want to use it I can just save it in a variable. Make sure you do it in the 'then' function. Here's a sample for save the name to a var:
.then(function (data) {
empName = data.d.results[0].PreferredName;
}
I am working with Extjs4.1 MVC. What I am trying to do is save some data to the server but I do not know the proper format or how I should go about submitting the data to the server.
Here is what I am thinking but I do not believe the Ajax call should be in the controller, it should be in the model or in the store file?
method in my controller:
submit: function(value) {
data = {"id": 100, "tdt": "rTk", "val": "445"} // test data
Ext.Ajax.request({
url: 'http://test.myloc.com/providerSvc/dbproxy.php',
params: {
'do':'insert',
'object': 'stk',
'values': data
},
success: function(response){
alert('response.responseText);
}
})
}
My store:
Ext.define('STK.store.Stack', {
extend: 'Ext.data.Store',
model: 'STK.model.Stack',
autoLoad: true,
proxy: {
type: 'ajax',
api: {
read: 'http://test.myLoc.com/providerSvc/dbproxy.php?do=get&object=stack'
},
reader: {
type: 'json',
root: 'data',
successProperty: 'success'
},
writer: {
type: 'json'
}
}
});
my model:
Ext.define('STK.model.Stack', {
extend: 'Ext.data.Model',
fields: ['id', 'tdt', 'val']
});
store.sync() works only when the endpoints for GET and POST are same.
What you can do is, for GET,
set the extraParams by concatenating to the URL or by creating an object like
extraParams[urlKeys] = paramObject[urlKeys];
store.getProxy().setExtraParams(extraParams);
then,
Store.getProxy().setUrl(StoreUrlForGET);
Store.load({
callback : function(rec, operation, success) {
if (success) {}
else {}
});
and for POST write an AJAX request as,
Ext.Ajax.request({
url : StoreURLForPOST,
method : 'POST',
jsonData : Ext.JSON.encode(YourPostData),
success : function(response, request) {},
failure : function(response, request) {}
});
for this AJAX request you can,
Ext.Ajax.setDefaultHeaders({
"TokenId" : TokenValue
});
All of this code goes into your controller.
I think the store is the proper place to make the ajax call.
You can "save" one record by adding it to the store, and then calling the "sync()" function.
Something like this (beware: code not tested):
var store = Ext.create("STK.store.Stack");
var record = Ext.create("STK.model.Stack");
record.set(xvalues);
record.isDirty = true;
record.setDirty(true); // I don't know if this line is required
store.add(record);
store.sync({
success: function(batch, options){
alert("OK!")
},
failure: function(batch, options){
alert("failure!")
}
});
I have found the following script which is apparently written using the javascript framework prototype.
Event.observe(window, 'load', function() {
Event.observe( 'btnSubmit', 'click', purchaseCD);
connectToServer();
});
function connectToServer()
{
new Ajax.Updater(
{ success: 'CD Count', failure: 'errors' },
'server_side.php',
{
method: 'get',
onSuccess: function(transport)
{
if (parseInt(transport.responseText)) connectToServer();
}
});
}
function purchaseCD()
{
new Ajax.Updater(
{ success: 'CD Count', failure: 'errors' },
'server_side.php',
{
method: 'get',
parameters: { num: $('txtQty').getValue() }
});
}
Is anyone here able to convert this script to use jQuery instead of prototype? I don't know prorotype at all so I don't understand it.
Ajax.Updater takes, as parameter 1, two containers into which it will update the successful or failed response of a request to the URL given in parameter 2.
What this script does is that upon page load (I translated it below to DOMReady which is not exactly the same, but jQuery convention) an AJAX request is sent to server_side.php. If it gets a response that it understands, it immediately sends off another request, in order to keep the session alive.
This looks like a terrible design. If you're going to do something like that, you definitely want a timeout between the requests.
Another thing that's not very neat with this script is that every AJAX request is handled by the same page - server_side.php - relying on different parameters for instructions on what action to perform. It would appear cleaner to simply request different pages for different actions.
$(function() {
$('#btnSubmit').click(purchaseCD);
connectToServer();
});
function connectToServer() {
$.ajax({
url: "server_side.php",
success: function(res) {
$('#CD Count').html(res);
if(parseInt(res))
connectToServer();
},
error: function(xhr) {
$('#errors').html(xhr.responseText);
}
});
}
function purchaseCD() {
$.ajax({
url: "server_side.php",
success: function(res) {
$('#CD Count').html(res);
},
data: { num: $('#txtQty').val() },
error: function(xhr) {
$('#errors').html(xhr.responseText);
}
});
}