How to read the JSON file using jQuery in ASP.NET? - json

I have tried this alot but always I am getting the failure problem .Can any one guide how can we read the json file using jQuery?I have a json file in my project as given in this image
i have written the code as given below
$(document).ready(function () {
$('#btnLoad').click(function () {
$.ajax({
url: "example.json",
dataType: "text/json",
type: "GET",
contentType: "application/json;charset=utf-8",
success: function (msg) {
AjaxSucceeded(msg);
},
error: AjaxFailed
});
});
});
function AjaxSucceeded(result) {
alert(result.d);
}
function AjaxFailed(result) {
alert(result.status + ' ' + result.statusText);
}
But It is always AjaxFailed is firing.

dataType should be 'JSON'
There are only 4 accepted values for dataType, which you can see here:
http://docs.jquery.com/Specifying_the_Data_Type_for_AJAX_Requests
Also, your error function takes 3 parameters:
errorFn(jqXHR, textStatus, errorThrown) {
// your code
}
Additionally, this:
success: function (msg) {
AjaxSucceeded(msg);
},
Can be this:
success: AjaxSucceeded
Your success function also takes 3 parameters:
success(data, textStatus, jqXHR)
For reference on $.ajax parameters: http://api.jquery.com/jQuery.ajax/

Related

Append additional HTML result in calling MVC action by Ajax in DNN8

I'm new in DNN development.
I have created a very simple module in Visual studio--- A textbox and a button.
I just want to call the action in a controller by click the button, then show the return result in the textbox.
The code call the action success, but not sure why append lots of HTML inforation in the result.
Here is the action in the controller:
public ActionResult test1()
{
return Content("Return something");
}
Here is the Ajax code from the View:
$(document).ready(function () {
$("#btnSub").click(function () {
//alert(this.action);
$.ajax({
type:"GET",
contentType:"application/text",
url: "#Url.Action("test1", "Sky")",
data:"",
dataType: "text",
success: function (data) { $("#txtResult").val(data); alert("Success!") },
error:function(){alert("Failed!")}
});
});
});
And here is the result show in the textbox:
Anyone can let me know why the HTML information returned? Actually, I don't need it.
Thanks
Unfortunately, as described in DNN8 MVC unsupported features, it's not yet possible to return a JsonResult. So the solution I used is to return an ActionResult (although the function returns Json):
public ActionResult Test()
{
return Json(new { success = true });
}
On jquery side, I setup ajax call to receive result as html. This avoid the browser to display a parsing error. Finally, just need to remove the html part and manually parse the response. It's not very clean, but the only solution I found until DNN support JsonResult.
$.ajax({
url: '#Url.Action("Index", "Contact")',
type: 'POST',
dataType: 'html',
data: $('#contact-form input').serialize(),
success: function (response) {
jsonPart = response.substring(0, response.indexOf("<!DOCTYPE html>"));
var data = JSON.parse(jsonPart);
if (data.success) {
alert("Great");
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Error!");
}
});
EDIT : Improved solution
DNN8 now support IMvcRouteMapper. You can then register a route in RouteConfig.cs. Once done, you can call the function using following URL :
/DesktopModules/MVC/ModuleName/Controller/Action
The action can return a JsonResult. But pay attention, if you just call that function, it will fail with a null exception on ModuleContext. You have to include in the ajax call the following header :
headers: {
"ModuleId": #Dnn.ModuleContext.ModuleId,
"TabId": #Dnn.ModuleContext.TabId,
"RequestVerificationToken": $("input[name='__RequestVerificationToken']").val()
}
You can find the module complete code here.
This is a working ajax call in DNN 9. You dont have to use #urlaction it will give whole html as well as data. dnn.getVar("sf_siteRoot", "/") +
"DesktopModules/MVC/ModuleName/Controller/Action", this does the trick and don't forget to add the header otherwise it will throw 500 error.
$.ajax({
url: dnn.getVar("sf_siteRoot", "/") +
"DesktopModules/MVC/ModuleName/Controller/Action",
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: "{ 'id':" + JSON.stringify(3543)+" }",
headers: {
"ModuleId": #Dnn.ModuleContext.ModuleId,
"TabId": #Dnn.ModuleCon`enter code here`text.TabId,
"RequestVerificationToken":
$("input[name='__RequestVerificationToken']").val()
},
success: function (response) {
debugger;
},
error: function (errmsg) {
alert("Error!");
}
});
Your controller should be
[HttpPost]
public ActionResult ActionName(int id)
{
var data = id;
return BuidJsonResult(true,data);
}
Happy Coding :)

JSON parseerror when % is in data content

I need to fix problem on site, and i can't figure out how. I have function which dynamically download articles, but when it contain % sign it throws parseerror. Can anyone help me to change this function to work with % sign and explain me that JSON behavior?
$('.funfan_more').click(function(){
if((offset*fun)+fun>=fun_count && (offset*fan)+fan>=fan_count){
$('.load_more').html('').css('height','30px').css('background','none');
}
ajaxLoader.show();
if(!loading) {
loading = true;
$.ajax('<?php echo URL::site('load_posts'); ?>',{
async: false,
type: 'GET',
data: {
offset: offset
},
dataType: 'json',
cache: false,
error: function( jqXHR, textStatus, errorThrown ) {
alert('Ups, some we have some' + textStatus + ' error here.');
},
success: function( data, textStatus, jqXHR ) {
$('.ff_left').append(data.a);
$('.ff_right').append(data.b);
offset++;
setTimeout(function(){
Cufon.refresh();
loading = false;
ajaxLoader.hide();
}, 1000);
}
});
}
return false;
});
I found the solution. Script wrongly preapared feed for site. It was a Kohana object pushed to string witch sprintf function, which was giving error if % was in website feed. Changing sprintf for normal casting to String type helped.

Crossdomain request

I try to load static html pages from another server.I make crossdomain request.
$(document).ready(function (){
$("div[src]").each(function(){
var staticFileURL = $(this).attr('src');
$.ajax({
url: staticFileURL,
dataType: 'jsonp',
data: {},
error: function(xhr, status, error) {
alert(error);
},
success: function() {
alert("success");
},
jsonp: false,
jsonpCallback: 'jsonpCallback'
});
});
});
But I got in chrome error "SyntaxError:Unexpected token <".
In FF "SyntaxError:Invalid xml attribute value".
What's wrong.Could somebody help me?
JSONP is to get json data from the server, it looks like you are trying to received HTML data.
Try to put your HTML data inside JSON object on the server and then read that HTML on the success callback:
for example, your json data from the server:
{ html: "<html><head>...</head></html>" }
also, your success callback should look like:
success: function(**data**){
}

Success function in .ajax() doesn't execute

When I debug using Firebug I see the control jumping to error section after hitting success. I am unable to find out what is going wrong. Can some body please point out what is wrong with this code.
$(function(){
$.ajax({
type: "POST",
url: "service/MyService.asmx/GetAsgInfo",
data: "{id: " + parseInt($('#AsgId').val()) + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// var s = eval('(' + msg.d + ')');
alert(msg.d[0].SubmittedCount);
},
error: function (e) {
alert("error : " + e);
}
});
});
POST :
{id: 5301}
RESPONSE :
{"d":[{"__type":"Proxies.AFARServiceRef.AssignmentInfo","ExtensionData":
{},"AssignDate":"\/Date(1319526000000)\/","AssignFileName":null,"ClaimId":"MH001025","ClaimantName":"Deborah C Plaid","FirstContactDate":"\/Date(1319526000000)\/","FirstContactTime":
{"Ticks":420000000000,"Days":0,"Hours":11,"Milliseconds":0,"Minutes":40,"Seconds":0,"TotalDays":
0.4861111111111111,"TotalHours":11.666666666666666,"TotalMilliseconds":42000000,"TotalMinutes":700,"TotalSeconds":42000},"Id":5301,"InspectionDate":"\/Date(1319612400000)\/","StatusId":1,
"SubmittedCount":4,"UploadedCount":14}]}
Instead of using the success and error functions, try using complete:
complete: function(jqXHR, textStatus) {
alert(textStatus);
}
I had a similar problem with handling json, and it turns out I wasn't setting the content-type properly on the server side. Even valid json sometimes causes weird errors when it is in a response labeled as "text/plain" or even "text/json". Make sure your content type is right.

JSON returned data it is in {d:"data"} format

I am trying to get JQueryUI's Autocomplete code working with an ASMX web service. I am getting close, but hit yet another wall yesterday. The JSON data is being returned in {d:"data"} format (see http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx). My data now looks like:
d: "[{"DOTNumber":"001061010","JobTitle":"Project Architect"},{"DOTNumber":"003061005","JobTitle":"Principal Electrical Engineer"}]"
My code is:
$(function() {
function log(message) {
$("<div/").text(message).prependTo("#log");
$("#log").attr("scrollTop", 0);
}
});
$("#dotmatch").autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
url: "/AutoSuggestJSTest/AutoSuggest.asmx/DOTFind",
contentType: 'application/json',
dataType: "json",
data: JSON.stringify({ prefixText: request.term, count: 20 }),
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
},
success: function(data) {
var safe = data;
response($.map(safe.d, function(item) {
return {
label: item.JobTitle + "(" + item.DOTNumber + ")",
value: item.DOTNumber
}
}));
}
});
},
minLength: 2,
select: function(event, ui) {
log(ui.item ?
"Selected: " + ui.item.value + " aka " + ui.item.id :
"Nothing selected, input was " + this.value);
$get("DOTNumber").value = ui.item.value;
},
});
The problem lies in the success function.
What is the right syntax to get past the "d" issue?
Your data should look like this:
{"d":[{"DOTNumber":"001061010","JobTitle":"Project Architect"},"DOTNumber":"003061005","JobTitle":"Principal Electrical Engineer"}]}
It appears you are missing quotes around your "d" and you have extra quotes around your array.
Don't eval() your data - this opens you up to more security issues than the d: prevented.. You should have access to JSON.parse() or if not jQuery.parseJSON() (which wraps JSON.parse() if available... depends on your target platform(s)).
This has been an incredibly difficult process, but I finally got it working. There were a number of hurdles:
1) My JSON return string was getting wrapped in an XML blanket, so it would not parse
2) Solving this problem required the contentType: 'application/json' line
3) With that content type, a POST was required. GET would not work
4) POST required putting the data together using the JSON.stringify. I am still not sure about this one, but I found some code somewhere that did it.
5) Data coming back from the POST was prefixed with a "d " (see: http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
6) getting access to the data itself required the "eval(data.d)" line.
$("#dotmatch").autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
url: "/AutoSuggestJSTest/AutoSuggest.asmx/DOTFind",
contentType: 'application/json',
dataType: "json",
data: JSON.stringify({ prefixText: request.term, count: 20 }),
success: function(data) {
var output = eval(data.d);
response($.map(output, function(item) {
return {
label: item.JobTitle + "(" + item.DOTNumber + ")",
value: item.DOTNumber
}
}));
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2
});
If I ever have this much trouble writing a few lines of code again, I am going to take a very large guage shotgun to my computer!
Bob Jones
If you use a WCF JSON service with the webHttpBehavior (instead of enableWebScriptBehavior), it will not emit the "d"