I'm getting some values from a WCF Data Service right, but I don't know how to handle this information. Here goes my ajax code:
$.ajax({
url: "../Services/ChannelWCF.svc/QuotaSet?$filter=month(Date) eq 12",
dataType: "json",
success: function (data) {
console.log(data)
}
And here that I get from the console:
An array with 2 objects that I'm not able to handle. I need to get the values from each object of the array returned and save it to another variables. I tried iterating in "data" with $each(....) but I always get "undefined" from the console when I try to print the values of each object.
Inside the data object there are two fields. value is the one you want. Use the following:
$each(data.value,function(){.....})
Related
I am trying to post some stringified data to an action method in my MVC controller. Below is the piece of JS Code
function SaveStateForGrid(pGridId, pIsAysnc) {
var grid = $('#' + pGridId).data("kendoGrid");
var tGridState = kendo.stringify(grid.getOptions());
$.ajax({
url: '/Home/SaveGridState',
type: 'POST',
dataType: 'json',
async: pIsAysnc,
data: { pGridState: tGridState, pGridName: pGridId },
success: function (data) {
console.log("Data Saved Successfully");
},
error: function (jqXHR, textStatus) {
console.log("Error while saving grid data " + pGridId);
}
});
}
I am trying to save gridstate info into the db and each grid in my app has different grid state info.
This works sometimes - as in, the post hits the controller method "SaveGridState" if I keep a breakpoint there and so on. On other occasions the breakpoint is not hit and the data is not saved in DB but the code does flow to "success" AJAX callback - no errors and I get a 200POST OK response in the network tab of chrome debugger.
I looked up the data being sent and figured out that on the occasions it fails, there is something about the data being posted which is causing it. Specifically the first param - "tGridState" - a stringified KendoGrid config data. If I replace this data from other successful calls, there is no issue. I have compared the data on different viewing tools and am not able to understand what in the data is breaking this.
Attaching a link to the zip file which contains both "Valid" and "Invalid" data. Any help pls ?
https://www.dropbox.com/s/whfglyk607bnd04/Downloads.zip?dl=0
Few months on from posting this - the module in question was on freeze.
I discovered that the stringified gridstate information (grid config data) included JS functions for grid related events which was causing issues in the stringified data. In fact stringification strips such functions from an object.
Somehow this was preventing me from hitting the breakpoint on the server side even if the data was posted "apparently".
So I wrote a JS function to strip all unnecessary data from my gridstate config data before stringification - and then the post works perfectly.
Voila !
I know this has been asked multiple times, but unfortunately it's still unclear to me. How do I pass array of integer as parameter to the url of an Ajax call? I need the elements of the array to show in the url.
This is inside script tags in the View :
function DeleteRoom(id, IDarray) {
$.ajax({
url: "/api/Room/DeleteRoom?RoomId=" + id + "&userDevicesId="+ IDarray,
type: "DELETE",
dataType: 'json',
data: IDarray, //data that will be passed to the array (?)
traditional: true, //if I get it right, this serializes the array
success: function (data) {
... }
});
}
This is the API
public void DeleteRoom (int id, [FromUri] int[] IDarray)
This only reads the first element in the array from database, and so it deletes only the first element. It's like I'm passing Int! Then the browser crashes (stop script) and I get this error
DELETE .../api/Room/RemoveRoomWithDevices?RoomId=2392&userDevicesId=1549
204 No Content 62ms
XML Parsing Error: no element found Location: moz-nullprincipal
Is the url syntax wrong? Or else, is there suggestions to make this work?
You can use JSON.stringify()
here is your url
url: "/api/Room/DeleteRoom?RoomId=" + id + "&userDevicesId="+ JSON.stringify(IDarray)
Btw why you are using again a data attribute in ajax call..? Since you have included data array in the url.
Am trying to return a json object to render to a grid in my template.
This is how i do it.
views.py
def ajax_up(request):
history_data=Upload_history.objects.all()
history=serializers.serialize("json",history_data)
return HttpResponse( history, mimetype='application/json' )
html
$(".reply").click(function(){
$.ajax({
url: "/ajax_up/",
type: 'GET', //this is the default though, you don't actually need to always mention it
dataType: "json",
success: function(data) {
alert("awasome"+ data)
},
failure: function(data) {
alert('Got an error');
}
});
so i declare an object to hold the data as
var data = {{history|safe}};
where history is returned from the ajax call as in view above
but when i do alert(data), i get [object object],[object object].....
can any one help please?
Sounds like it's working, but alert just displays a string. Since your data is not a string, it'll show [object Object].
Either serialize the data with JSON.stringify or use console.log instead of alert to see the data in your browser javascript console.
I've read a couple of posts here regarding how to do this and I can get it working only half-way.
This works (sending json object as text):
function go(itemid)
{
apiRoutes.controllers.Application.addItem(itemid).ajax({
data: '{"reqid":0,"iid":2,"description":"adsf"}',
dataType: 'text',
contentType:'application/json',
success: function(reply) {
alert(reply)
}
});
}
This does not (sending object as json):
function go(itemid)
{
apiRoutes.controllers.Application.addItem(itemid).ajax({
data: {"reqid":0,"iid":2,"description":"adsf"},
dataType: 'text',
contentType:'application/json',
success: function(reply) {
alert(reply)
}
});
}
And what I really want to do is something like this (I've already set up the proper combinators):
function go(itemid)
{
apiRoutes.controllers.Application.addItem(itemid).ajax({
data: #Html(Json.stringify(Json.toJson(item))),
dataType: 'text',
contentType:'application/json',
success: function(reply) {
alert(reply)
}
});
}
My controller looks like this:
def addItem(id: Long) = Action (parse.json) { implicit request =>
Logger.info("add item")
request.body.validate(Item.itemReads).map { item =>
thing.addItem(item)
Ok("Succesfully added item.")
}.recoverTotal{
e => BadRequest("Detected error:"+ JsError.toFlatJson(e))
}
}
In the second case, it never gets to the logging code. Instead it returns a 400 Bad Request immediately (this is likely something triggered in the Action (parse.json) bit I think).
I'd rather send the object as json because when I convert to string and description happens to have an apostrophe in it (') that messes things up. I could probaby escape the apostrophe, but hoping that I'm missing something simple about how to do this with an object rather than a string.
Thanks
As described in the API the dataType param is for setting:
The type of data that you're expecting back from the server.
For sending the json use your second approach (don't send it as a String). Use web browser inspector to validate if correct data were send. AFAIK you shouldn't have problem with Handling the JSON request after receiving valid JSON object
If you are trying to send a non-stringified JSON object in Jquery, $.ajax automatically tries to process it with $.param,
If your data in the ajax call looks like this:
data: {"reqid":0,"iid":2,"description":"adsf"}
This is what $.ajax is doing under the hood before sending:
$.param({"reqid":0,"iid":2,"description":"adsf"})
// "reqid=0&iid=2&description=adsf"
It takes the JSON and serializes it into a form-url-encoded format. Whereas your server is expecting JSON. I would suggest the best way to get around this is to just stringify before sending:
data: JSON.stringify({"reqid":0,"iid":2,"description":"adsf"})
Source: http://api.jquery.com/jQuery.ajax/#sending-data-to-server
I have a C# web application which uses ajax method to GET and POST data. Is there any difference between GET and POST methods in passing data (in case of contentType,data,dataType)?
$.ajax({
type: 'GET',
url: "url",
contentType: "application/json; charset=utf-8",
data: { value: "data" },
dataType:"json",
success: function (data) {
alert(data);
},
error: function (data) {
alert("In error");
}
});
});
GET encodes the information into the url, the more info you GET the longer your URL becomes.
POST stores data in an array and passes that array to the next page. your Url remains unmodified.
While that may not seem like a huge deal, URLs do have a maximum length and errors will ensue if you exceed it. In addition and call to a specific url may fail due to the modifications GET makes. Apart from that, They are similar enough in function to be interchangeable for most purposes.
In normal form method also GET is used to sent some insensitive small chunk of data to server in querystring, whereas POST is used for sending large and secure data to the server
In case of using ajax GET is commonly used, POST is feasible only when you have to do DB interactions on server or there's some sensitive data involved, read more here http://www.jquery4u.com/ajax/key-differences-post/