I'll try to explain the best I can
this is a .net application
I have a javascript function that calls a webmethod, and that method should return some results
I get response as multiple objects, with param_name and param_value (number of objects and different param_names depends on the request)
now I am having trouble with displaying that data on the page, currently I am trying to return results as a list of dictionaries but don't really now how to go through that and show it on page (I am used to work with datatables and grid, but didn't find a way to work with that and javascript/ajax yet)
i would like results to be shown in something like this
param_name1 param_name2 param_name3
parav_value1 param_value2 parav_value3
parav_value1 param_value2 parav_value3
parav_value1 param_value2 parav_value3
ajax
$.ajax({
type: "POST",
url: 'Reports.aspx/getReport',
data: "{'jsonObject':'" + rp + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (results) {
alert('success');
},
error: function (err) {
alert(err.status + " - " + err.statusText);
}
});
after this alert i should go through the results and show them
any suggestion is welcome, if there is some easier way I will be glad to listen to it
Related
Presently I am having the issue of trying to pass information back to the behind code, in this case a user selected name from a list. I have tried setting the data VN to an object and passing that, but that did not work either. Presently it seems to never send it to the behind code as it errors out instead. An example value for VN is: "Location1 Building"
This worked fine when the data part of the AJAX call wasn't used and the query was hardcoded into the behind code. I believe I am misunderstanding exactly how this functions. I have read over 8 similar threads but the fixes on those didn't quite work here either and lead to errors also listed below.
JAVASCRIPT
$("#btnClient_Report").click("click", function CallService() {
var Cn = document.getElementById('client_input');
var VN = Cn.value;
alert("C1 Name: " + VN);
$.ajax({
traditional: true,
type: "POST",
url: '/ClientChart.aspx/Getdata',
data: JSON.stringify(VN),
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
success: function (msg) {
alert("Success: " + msg.d);
CCData = msg.d;
bindClientChart();
},
error: function(ermsg){
alert(ermsg.responseText);
}
});
});
BEHIND CODE - C#
[WebMethod]
public static string[] Getdata(string VN) //test the connection and rerieve data requested.
{
var loc_name = VN;
//connect to DB and query more info.
At present the error is "Cannot convert object of type \u0027System.String\u0027 to type \u0027System.Collections.Generic/IDictonary'2..."
though attempting to change the ajax data to VN from JSON.stringify(VN) leads to
"INVALID JSON Primitive" error.
Attempting to change VN to a simple object like var VN = { ID:[Cn.value]}; leads to a similar error.
The jquery $.AJAX function documentation says is accepts type string, so I would like to learn about how I am messing up and understand this better. Thank you for any and all help!
After trial and error I learned my mistake was that the ajax data line needed to be:
data: '{VN:"' + $("#client_input").val() + '"}',
Inserting the string alone doesn't work properly as it needs the identifier even if you try passing a string as the same identifier name. Hop this may help someone in future learn from my foolish mistake
Do Something like this to Pass string to method..
$.ajax({
type: "POST",
url: "ClientChart.aspx/Getdata",
contentType: "application/json; charset=utf-8",
data: "{'VN':'" + VN + "'}",
async: true,
cache: true,
dataType: "json",
success: function (data) {
alert("Success: " + data.d);
bindClientChart();
},
error: function(ermsg){
debugger;
alert(ermsg.d);
}
});
I m trying to update bulk of data one by one using Jquery ajax,so that i can show update progress. every thing goes well at beginning but after 5 min, it throw an error like in
Image while checking network request/respond:.
Error on error function of ajax:.
MainData is array of json object and is contain around 3000 number of json object.
function DoPost()
{
$.each(MainData, function (key, value) {
var mainCode = value.MainCode;
var companyCode = value.CompanyCode;
$.ajax({
url: "Allotment.asmx/DoAllotment",
data: "{MainCode:'" + mainCode + "', sNoOfAllotment:'" + noOfAllot + "',CompanyCode:'" + companyCode + "'}",
dataType: 'text',
contentType: "application/json; charset=utf-8",
type: "Post",
success: function (res){
Progress(res); // this funtion will show progress of update.
},
error: function (res) {
console.log(res);
}
});
});
}
I am using web service of asp.net webform
The issue could be maximum number of concurrent connections to same URL. You can schedule next $.ajax() call when current $.ajax() completes.
See also multiple, sequential fetch() Promise
function DoPost(value) {
var mainCode = value.MainCode;
var companyCode = value.CompanyCode;
return $.ajax({
url: "Allotment.asmx/DoAllotment",
data: "{MainCode:'" + mainCode + "', sNoOfAllotment:'"
+ noOfAllot + "',CompanyCode:'" + companyCode + "'}",
dataType: 'text',
contentType: "application/json; charset=utf-8",
type: "POST",
success: function(res) {
Progress(res); // this funtion will show progress of update.
},
error: function(res) {
console.log(res);
}
});
}
var copy = MainData.slice(0);
var res = (function re(value) {
return DoPost(value).then(function() {
return copy.length ? re(copy.shift()) : "complete"
})
})(copy.shift());
res.then(function(complete) {
console.log(complete)
}, function(err, textStatus, jqxhr) {
console.log(err)
});
The error 0x2ee2 is IE's representation of timeout error. The occurrence of this error shows that the server has stopped responding to the requests due to a high number of requests sent from the same client. This is the server avoiding DOS attacks from the client.
The proper method is to optimize the code and try to utilize the maximum available bandwidth in order to minimize the number of requests to the server.
In the most of the websites when I see the browser 'view page source', a lot of java-script array or JSON data is populated dynamically. I think this data we can get it from the database and store it in java-script array. Can any one suggest me how to add data dynamically from jQuery ajax call and assign it in array variable..
I tried with array push() method. but no luck.
Can any one suggest me how to do it?
You can do it as follows:
$.ajax({
type: "GET",
url: // Your URL,
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var result = data.d; // your json data
$.each(result , function (index, value) {
myArray.push([value.property, value.property2]); // push array note `[]`
});
}
});
I'm trying to get a simple JSON request working with jQuery. I want to get the premiers of new shows from Trakt (API: http://trakt.tv/api-docs/calendar-premieres), but cannot navigate through the nodes. Seems that I might be needing a date attached after the API key in the URL, but I'm not sure, since dealing with JSON is quite new to me.
$.ajax({
type: "GET",
url: [url_with_actual_api_key],
dataType: "json",
async: true,
cache: false,
success: function(data){
$.each(data, function(data, value) {
$(".title").append("<div class='item'><span>Title:</span>" + value.title + "</div>");
});
}
I'm getting UNDEFINED of course, because I'm trying to retrieve data few levels 'deeper'. Also, value.episode shows nothing, getting the title is the closest I got. My question is, how do I get the whole data from the request for each episode on API's date?
Thanks a lot and a million highfives.
You need to iterate twice, since you have an array of date, containing an array of episodes:
success: function(data){
// for each date
$.each(data, function(index, broadcastDate) {
// broadcastDate.date has the date
// broadcastDate.episodes has the show data.
$.each(broadcastDate.episodes, function(index,episode) {
// episode contains show and episode objects
$(".title").append("<div class='item'><span>Title:</span>" + episode.show.title + "</div>");
});
});
I am reading a book about asp.net MVC and I found different methods for calling Action methods that return JSON:, either using Ajax OR getJSOn, so are these two methods equivalent to:-
$.ajax({
type: "GET",
url: "http://localhost:11279/test/testcall",
dataType: "json",
success: function (result) {
var message = result.Title + ": $" + result.CurrentPrice;
$('#Result').html(message);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Error: " + errorThrown);
}
});
And the getJSON is:-
<script type="text/javascript">
$(function () {
$.getJSON("http://localhost:11279/test/testcall",
function (data) {
$.each(data, function (key, val) {
var str = val.Description;
$('<li/>', { html: str }).appendTo($('#auctions'));
});
});
});
</script>
Second question
if I want to call the above action method or an external web service from a controller class instead of using javaScript, so which c-sharp methods I should use ?, and how I am going to pass the returned JSON from the controller class to the view.
BR
getJson-
Method allow get json data by making ajax call to page. This method allows only to pass the parameter by get method posting parameter is not allowed.
Ajax ()- This method provide more control than all other methods we seen. you can figure out the difference by checking the list of parameter
Provide more control on the data sending and on response data.
Allow to handle error occur during call.
Allow to handle data if the call to ajax page is successfull.
Answer to 2
You can make use of jquery + Ajax() function to consume it in your html page..
here is article for you : Steps to Call WCF Service using jQuery.
something like this
function WCFJSON() {
var userid = "1";
Type = "POST";
Url = "Service.svc/GetUser";
Data = '{"Id": "' + userid + '"}';
ContentType = "application/json; charset=utf-8";
DataType = "json"; varProcessData = true;
CallService();
}
//function to call WCF Service
function CallService() {
$.ajax({
type: Type, //GET or POST or PUT or DELETE verb
url: Url, // Location of the service
data: Data, //Data sent to server
contentType: ContentType, // content type sent to server
dataType: DataType, //Expected data format from server
processdata: ProcessData, //True or False
success: function(msg) {//On Successfull service call
ServiceSucceeded(msg);
},
error: ServiceFailed// When Service call fails
});
}