This question already has an answer here:
How to load grid data with json data on ajax sucess
(1 answer)
Closed 4 years ago.
I have a grid where I bind my store in this manner.
bind: {
store:'{myStoreViewModel}'
},
Now in myStoreViewModel I defined like this.
myStoreViewModel:{
autoLoad: false,
proxy: {
type: 'ajax',
url: 'myUrl',
timeout: 240000,
paramsAsJson: true,
actionMethods: {
read: 'POST'
},
reader: {
type: 'json'
}
},
listeners: {
load: 'myLoad',
}
},
Here I am getting my serviceStatus failure. Then i further investigate this with normal Ajax.
Here is my normal Ajax
myNormalAjax : function(myJSON){
Ext.Ajax.request({
url: 'retrievemsgsummary.do',
method: 'POST',
dataType: 'json',
timeout: ProcessConstants.VALBIZDT_TIMEOUT,
jsonData: myJSON,
success: function(response) {
var responseText = Ext.JSON.decode(response.responseText);
if (responseText.serviceStatus == 'SUCCESS') {
this.messageSummaryDetails(this,responseText);
}
},
failure: function(response) {
},
scope: this
});
},
Here I am passing jsonData and serviceStatus is coming sucess.
then In my viewModel also I am trying pass jsonData but no luck. This how i am passing jsonData there.
dataObj : function(myJSONDATA){
var myStoreStore = this.getViewModel().getStore('myStoreViewModel');
myStoreStore.proxy.jsonData = myJSONDATA;
}
Can anybody suggest how to bind my store for my grid.
**
You can pass additional params (extra params) to store's proxy either using the proxy's extraParams config at store/proxy definition, or later in the life cycle using setExtraparam or setExtraparams methods. So, in your case, it could be something like this:
dataObj : function(myJSONDATA){
var myStoreStore = this.getViewModel().getStore('myStoreViewModel');
myStoreStore.getProxy().setExtraParams(myJSONDATA);
}
Related
I want to pass a lot of parameters from my ajax function to my controller. Initially, I thought I would just do this using a query string but that wasn't giving me the result I wanted, although it worked it was creating an unattractive URL the more data I added.
I thought the better approach would be to take all this data I need to pass, store it as an object and pass that payload into the controller from an ajax function.
The ajax function is triggered from the .event() attribute of the KendoGrid.
Kendo Grid
#(Html.Kendo().Grid<MyProject.Models.Car>()
.Name("requirement-grid")
.Columns(columns =>
{
columns.Bound(c => c.Name);
columns.Command(command => command
.Custom("Test").Click("payload"));
})
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("GetCars", "cars"))))
As you can see from the above code, there is a custom command that I've used which triggers a function when you click on it. The function is payload and the code is as follows:
payload
function payload(e) {
e.preventDefault();
//Get row data
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
//Create Object
var obj = {
Name: dataItem.Name,
BHP: dataItem.BHP,
YearOfBuild: dataItem.YearOfBuild
}
//Post via Ajax
$.ajax({
type: 'POST',
url: '/Controller/Method/',
data: JSON.stringify({
array: obj
}),
cache: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log("Success");
},
error: function (ob, errStr) {
console.log(ob.responseText);
}
});
}
I access the data of the row that was clicked on and pass it down via the events parameter, from there I create an object and add the data to it. I then create an ajax call and try to pass it to the controllers.
The controller expects the parameter, the code is as follows but shortened for brevity.
Controller
public ActionResult Create(object[] obj)
{
return View(obj);
}
If I use "POST" in my ajax function I get an error regarding a anti-forgery token which is missing. If I use "GET" the obj parameter is always null.
The required anti-forgery cookie "__RequestVerificationToken" is not present.
Is there a better way to be doing this or is my approach incorrect?
So this should be a relatively simple change to your code. I am assuming you have an anti-forgery token loaded onto the page and the action you are posting to is protected by this. You have two solutions here:
1) Remove the requirement for the token if it isn't needed from the action in your controller
2) Provide the token as part of the data package you are sending back to the server by changing your code from
$.ajax({
type: 'POST',
url: '/Controller/Method/',
data: JSON.stringify({
array: obj
}),
cache: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log("Success");
},
error: function (ob, errStr) {
console.log(ob.responseText);
}
});
to:
$.ajax({
type: 'POST',
url: '/Controller/Method/',
data: {
array: JSON.stringify(obj),
__RequestVerificationToken: $('input[name=__RequestVerificationToken]').val()
},
cache: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(data) {
console.log("Success");
},
error: function(ob, errStr) {
console.log(ob.responseText);
}
});
Notice I have just added a reference to the anti-forgery token as part of the data package for you and this should be read by the controller and allow the command to complete successfully for you if you have the token on the page. if not then just add the #Html.AntiForgeryToken() to the view and you should be fine.
I have a litte problem.
I call an file and this file has to know from which level it was called.
I'm developing in an special tool, and thats how it works here.
for example:
var Url = baseUrl + "?func=ll&objId=" + WebreportId + "&objAction=RunReport";
jQuery.ajax({
url: Url,
type: "GET",
data: { level: 'dossier' },
success: function(response){
$('#thirdPartyContent').html($(response).find('#cvDossier').html());
}
});
In my JavaScript Functions in the Call, i have to know from which level it was called. Like here "dossier".
How can i read out an string in the call? With the URL Parms i can just check the superior url, and not the url from the ajax call, isn't it?
I hope you understand my probs.
Try utilizing beforeSend option of $.ajax()
jQuery.ajax({
url: Url,
type: "GET",
data: { level: 'dossier' },
beforeSend: function(jqxhr, settings) {
// set `data` property at `jqxhr` object
jqxhr.data = settings.url..match(/=.*/)[0].split(/=|&.*/).filter(Boolean)[0];
},
success: function(response, textStatus, jqxhr){
// do stuff with `jqxhr.data` : `"dossier"`
console.log(jqxhr.data);
$('#thirdPartyContent')
.html($(response).find('#cvDossier').html());
}
});
For example, I'm currently implementing client side javascript that will use a POST if the additional parameters exceed IE's safety limit of 2048ish charachers for GET HTTP requests, and instead attach the parameters to the body in JSON format. My code looks similar to the following:
var URL = RESOURCE + "?param1=" + param1 + "¶m2=" + param2 + "¶m3=" + param3();
if(URL.length>=2048) {
// Use POST method to avoid IE GET character limit
URL = RESOURCE;
var dataToSend = {"param3":param3, "param1":param1, "param2":param2};
var jsonDataToSend = JSON.stringify(dataToSend);
$.ajax({
type: "POST",
data: jsonDataToSend,
dataType: 'json',
url: URL,
async: true,
error: function() {
alert("POST error");
},
success: function(data) {
alert("POST success");
}
});
}else{
// Use GET
$.ajax({
type: "GET",
dataType: 'json',
url: URL,
async: true,
error: function() {
alert("GET error");
},
success: function(data) {
alert("GET success");
}
});
}
Is there a way of me avoiding writing out this ajax twice? Something like
if(URL.length>=2048) {
// Use POST instead of get, attach data as JSON to body, don't attach the query parameters to the URL
}
N.b. I'm aware that using POST instead of GET to retrieve data goes against certain principles of REST, but due to IE's limitations, this has been the best work around I have been able to find. Alternate suggestions to handle this situation are also appreciated.
The $.ajax method of jQuery gets an object with properties. So it's quite easy, to frist generate that object and a "standard setting" and modify them based on certain logic and finally pass it to one loc with the ajax call.
Principle:
var myAjaxSettings = {
type: "POST",
data: jsonDataToSend,
dataType: 'json',
url: URL,
async: true,
error: function() {
alert("POST error");
},
success: function(data) {
alert("POST success");
}
}
if ( <condition a> )
myAjaxSettings.type = "GET";
if ( <condition b> )
myAjaxSettings.success = function (data) { ...make something different ... };
$.ajax(myAjaxSettings);
I need to call ajax method couple of places. So want to try to minimize the code by creating separate method for it. If use directly, it works perfect. but when I separate it won't work.
data: columns[5],
type: 'autocomplete',
options: { items: 100 },
source: function (query, process) {
$.ajax({
url: "/EditInitiatives.svc/GetLocationData?clientId=" + $value.val(),
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: {
query: query
},
success: function (response) {
process(response.d);
}
});
},
strict: true
}
it doesn't work, if I call this way. It says Microsoft JScript runtime error: 'query' is undefined, how to fix it?
{
data: columns[4],
type: 'autocomplete',
options: { items: 100 },
source: callAutoCompleteAjaxMethod(query, process, "/EditInitiatives.svc/GetLocationData?clientId=" + $value.val()),
strict: true
},
callAutoCompleteAjaxMethod = function (query, process, url) {
$.ajax({
url:url,
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: {
query: query
},
success: function (response) {
process(response.d);
}
});
},
You call
source: callAutoCompleteAjaxMethod(query, ...
But you never gave 'query' a value, give it a value and it will work.
You are calling the function instead of assigning it to the source property. And at this moment the variable query is not defined.
You have to assign a function, so that the plugin can call it later:
source: function (query, process) {
callAutoCompleteAjaxMethod(
query,
process,
"/EditInitiatives.svc/GetLocationData?clientId=" + $value.val()
);
}
(I hope $value is defined somewhere)
Parenthesis ( () ) after a function reference always calls the function immediately. If you want to pass a reference to the function, you don't put parenthesis after it.
I'm using jQuery to grab some JSON data. I've stored it in a variable called "ajaxResponse". I cant pull data points out of it; I'm getting ajaxResponse.blah is not defined. typeof is a string. Thought it should be an object.
var getData = function (url) {
var ajaxResponse = "";
$.ajax({
url: url,
type: "post",
async: false,
success: function (data) {
ajaxResponse = data;
}
});
return ajaxResponse;
},
...
typeof ajaxResponse; // string
ajaxResponse.blah[0].name // ajaxResponse.blah is not defined
make sure you specify option dataType = json
$.ajax({
url: url,
type: "post",
dataType: "json",
async: false,
success: function (data) {
ajaxResponse = data;
}
});
Q8-coder has the right of it, but to give you some details: your server is really passing back a string that you've formatted into JSON. You'll need to tell jQuery what to expect, otherwise it just assumes it received a string.
Add the following to your $.ajax options:
dataType: "json"
Also, refer to the jQuery API for examples and documentation for these options.