JSON is undefined in IE7 - asp.net

It works fine in chrome, firefox and IE8. But comes up an error on IE7. Here is my jquery onchange event.
$('select#NationId').change(function () {
var nationId = $(this).val();
$.ajax({
url: 'LoadAreas',
type: 'POST',
data: JSON.stringify({ nationId: nationId }),
dataType: 'json',
contentType: 'application/json',
success: function (data) {
$('select#AreaId').get(0).options.length = 0;
$('select#AreaId').append('<option value="0">Select All</option>');
$.each(data, function (val, Areas) {
$('select#AreaId').append('<option value="' + Areas.Id + '">' + Areas.Name + '</option>');
});
}
});
});
controller
[HttpPost]
public ActionResult LoadAreas(int nationId)
{
var _Areas = (from c in SessionHandler.CurrentContext.ChannelGroups
join cgt in SessionHandler.CurrentContext.ChannelGroupTypes on c.ChannelGroupTypeId equals cgt.ChannelGroupTypeId
where cgt.Name == "Area" && c.ParentChannelGroupId == nationId
select new AreaName() { Id = c.ChannelGroupId, Name = c.Name }).OrderBy(m => m.Name);
if (_Areas == null)
return Json(null);
List<AreaName> managers = (List<AreaName>)_Areas.ToList();
return Json(managers);
}

The issue is that the JSON object is not available in IE 7. You'll want to include JSON2.js on your page for IE < 8 users.

If the browser doesn't implement the JSON object, you can always use a third-party library to provide it for you. If I recall correctly, this particular implementation is widely used and defers to the browser, so you just need to drop it in, no tweaking required.

Shouldn't
data: { "nationId": nationId },
just work?

$('select#NationId').change(function () {
var nationId = $(this).val();
var data = '{"nationId": "' + nationId + '"}';
$.ajax({
url: 'LoadAreas',
type: 'POST',
data: data ,
dataType: 'json',
contentType: 'application/json',
success: function (data) {
$('select#AreaId').get(0).options.length = 0;
$('select#AreaId').append('<option value="0">Select All</option>');
$.each(data, function (val, Areas) {
$('select#AreaId').append('<option value="' + Areas.Id + '">' + Areas.Name + '</option>');
});
}
});
});

Related

angularjs repeat does not show data at first time

First, I am so sorry because of my English.
I am showing a table that it's data come from server and shown with angular repeat.
I make a ng-click on each row of table that send an ajax request and get another list that I want to show in another table, until now all the thing are right,
but I have a little problem, my problem is that I must click twice on my first table's row to show second table data, at first time all the data comes from server but did not show in second table, my angular code is shown below.
angular.module("BI", [])
.controller("ListTables", function ($scope, $http) {
$scope.ReportLst = [];
$scope.myData = {};
$scope.myData.ReportLst = [];
$scope.myData.ReportDetail = [];
$scope.myData.ReportDetail2 = [];
$scope.selectedReportval = "";
$scope.Load = function () {
$http.post('MakeReport.aspx/LoadReportLst', { data: {} })
.success(function (data) {
$scope.myData.ReportLst = JSON.parse(data.d);
})
.error(function (data, status) {
alert('error');
});
}
$scope.SelectRepID = function (val) {
$.ajax({
type: "POST",
url: "MakeReport.aspx/GetReportDetail",
contentType: "application/json; charset=utf-8",
data: "{ 'val': '" + val + "'}",
dataType: "json",
success: function (data) {
$scope.myData.ReportDetail = JSON.parse(data.d);
},
error: function (data, status, jqXHR) {
alert(data.d);
}
});
$scope.selectedReportval = val;
}
});
In your second request you're using $.ajax instead of $http, because this isn't an Angular function a digest won't be triggered and your view won't be updated, in order to fix this you have to use $http there too.
$scope.SelectRepID = function (val) {
$http.post({
url: "MakeReport.aspx/GetReportDetail",
contentType: "application/json; charset=utf-8",
data: "{ 'val': '" + val + "'}",
dataType: "json"
}).then(
function(data) {
$scope.myData.ReportDetail = JSON.parse(data.d);
}, function(error) {
alert(error);
}
);
$scope.selectedReportval = val;
}
Update: Another way would be to use a $timeout in your $.ajax success function like so (this will trigger a digest).
success: function (data) {
$timeout(function() {
$scope.myData.ReportDetail = JSON.parse(data.d);
});
}

Return JSON List and use on MVC 4 View Page

I have used JSON to return a list but unsure how to use the returned list on a MVC 4 view page. Is this possible?
View Page
var subjectId = value;
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/JobProfiles/FindJobProfiles/" + subjectId,
data: "{}",
dataType: "json",
success: function (data)
{
}
});
Controller
[HttpPost]
public ActionResult FindJobProfiles(int? subjectId)
{
if (subjectId.HasValue)
{
Subject subject = subjectRepository.Get(subjectId.Value);
IList<JobProfile> jobProfiles = jobProfileRepository.GetBySubject(subject.Id, false, false);
var jobProfileList = from c in jobProfiles select new { Id = c.Id, Title = c.Title };
return new JsonResult { Data = jobProfileList.ToList() };
}
else
{
return null;
}
}
View Page Display
foreach (JobProfile job in jobProfiles)
{
<a href="/JobProfiles/View/#job.Id" title="#job.Title">#job.Title
}
The correct data is returned but not sure how to access the list on the view page and display the data.
Add a div to the page for the result or the html element you would like to display it:
<div id="results" />
Add a success handler that loops the result and appends it:
var subjectId = value;
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/JobProfiles/FindJobProfiles/" + subjectId,
data: "{}",
dataType: "json",
success: function(data) {
$.each(data, function(index, item) {
$('#results').append('<a href"/JobProfiles/View/' + item.Id + '" title="' + item.Title +'">' + item.Title + '</a>');
});
}
});
I assuming, you want to display data in list.
For that you need to have div with some id say target-div in your html page.
Using jquery you can display list in target-div as shown below.
success: function (data){
var markup='<ul>';
for (var i = 0; i < data.length; i++)
{
markup+='<li>'+ data[i].itemName +'<li>';
//itemName is key here.
}
markup+='</ul>';
$('#target-div').html(markup);//this will place the list in div.
}

Fetch data from asp.net using backbone

$.ajax({
type: "POST",
url: "Home.aspx/loadSB",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
for (i = 0; i < msg.d.length; i++) {
$('#sidebar ul').append('<li class="inactive"><a>' + msg.d[i].Title + ' </a></li>');
}
}
});
I go through this
https://github.com/kjbekkelund/writings/blob/master/published/understanding-backbone.md
and
https://gist.github.com/ryandotsmith/1655019
tutorial and create a backbone as below, but is not working well as the model did not fetch data from asp.net, which part goes wrong? I still new to backbone
Menu = Backbone.Model.extend({
parse: function (data) { return data; }
});
MenuCol = Backbone.Collection.extend({
model: Menu,
url: "Home.aspx/loadSB",
parse: function (response) { return response.rows; }
});
MenuView = Backbone.View.extend({
initialize: function () {
this.collection.on('add', this.appendMenu, this);
},
appendMenu: function (msg) {
for (i = 0; i < msg.d.length; i++) {
this.$('ul').append('<li class="inactive"><a>' + msg.d[i].Title + ' </a></li>');
}
}
});
var mc = new MenuCol();
//mc.fetch();
//Update1:
new MenuView({ el: $('#sidebar'), collection: mc });
Update 1:
I had play around with fetch, but still not working well,
Menu = Backbone.Model.extend({});
MenuCol = Backbone.Collection.extend({
model: Menu,
url: "Home.aspx/loadSB",
});
var test = new MenuCol();
test.fetch();
It did not return the data that I want, instead of, it display the interface that my screen have
If i using the jquery.ajax without backbone, it return the json data to me, which part goes wrong? Any guide will be great
Update 2:
Ok, I had change the "fetch", and now I able to see the json data passing into backbone
var test = new MenuCol();
test.fetch({ type: 'POST', contentType: "application/json; charset=UTF-8" });
Ok, finally I had solved the problem,
define(['jquery', 'underscore', 'backbone'], function () {
Menu = Backbone.Model.extend({});
MenuCol = Backbone.Collection.extend({
model: Menu,
url: "Home.aspx/loadSB",
});
MenuView = Backbone.View.extend({
initialize: function () {
this.collection.on('add', _.bind(this.AppendMenu, this));
},
AppendMenu: function (msg) {
var feed = JSON.parse(JSON.stringify(msg));
for (var i = 0; i < feed.d.length; i++) {
this.$('ul').append('<li class="inactive"><a>' + feed.d[i].Title + ' </a></li>');
}
}
});
var test = new MenuCol();
test.fetch({ type: 'POST', contentType: "application/json; charset=UTF-8" });
new MenuView({ el: $('#sidebar'), collection: test })
});
by changing the fetch type to "POST" and contentType: "application/json; charset=UTF-8", finally i manage to populate web with the data I want

How to make texbox to null after I got success in jQuery AJAX method

I am strangling when I added my comments with AJAX method of jQuery, after stressful, I want to make this textbox to null
my Ajax method like this :
function AddComments() {
$(".Comment input[type=text]").keypress(function (e) {
if (e.which == 13) {
var comment = $("#" + this.id).val();
var textId = "#" + this.id.replace("txt", "div");
$(textId).append(comment);
$.ajax({
type: "POST",
url: "Posts.aspx/AddComments",
data: "{'id': '" + this.id.replace("txt", "") + "','comments': '" + comment + "'}",
dataType: "json",
contentType: "application/json",
success: function (response) {
$("#" + this.id).val("");
//alert(response.d);
}
});
}
});
}
what I want is on Success, I want make current textbox to NULL
$("#" + this.id).val("");
This is a scoping issue. this in the success handler holds a reference to the window object, not the input the keypress fired on. You just need to cache the input in a variable you can use in the success handler. Try this:
function AddComments() {
$(".Comment input[type=text]").keypress(function (e) {
if (e.which == 13) {
var $input = $(this);
var comment = $input.val();
var textId = "#" + this.id.replace("txt", "div");
$(textId).append(comment);
$.ajax({
type: "POST",
url: "Posts.aspx/AddComments",
data: "{'id': '" + this.id.replace("txt", "") + "','comments': '" + comment + "'}",
dataType: "json",
contentType: "application/json",
success: function (response) {
$input.val("");
//alert(response.d);
}
});
}
});
}
you can't access this in jquery ajax do it like this save your object in any variable
function AddComments() {
$(".Comment input[type=text]").keypress(function (e) {
if (e.which == 13) {
var Element=this;
var comment = $("#" + this.id).val();
var textId = "#" + this.id.replace("txt", "div");
$(textId).append(comment);
$.ajax({
type: "POST",
url: "Posts.aspx/AddComments",
data: "{'id': '" + this.id.replace("txt", "") + "','comments': '" + comment + "'}",
dataType: "json",
contentType: "application/json",
success: function (response) {
$(Element).val("");
//alert(response.d);
}
});
}
});
}
Your success function is in another context, you can't use this, you have to send the id on the json response and do something like:
success: function (response) {
$('#'+response.div_id).val("");
}
and your json response should include the div_id that's passed on the ajax request

why jquery can't return string/text?

default.aspx
<button id="getGrouper">GetGroupers</button>
<script type="text/javascript">
$(document).ready(function () {
$("#getGrouper").click(function () {
$.ajax({
type: "post",
url: "Groupers.aspx/groupers",
data: "{pid:25}",
dataType: "text",
success: function (data) { alert(data); },
error: function (err) { alert("err:" + err); }
});
return false;
});
});
</script>
groupers.aspx.cs
[WebMethod]
public static string groupers(
int project_id)
{
string employees = "";
foreach (string s in ids.Split(','))
{
u = user.getUserbyUid(Convert.ToInt32(s));
employees += "<a class=\"reply_notify_delete\" href =showuser.aspx?uid=" + u.Uid + "&pid=" + p.Pid + ">" + u.userName + "</a> ";
}
return employees;
}
want to get groupers by a project_id
i want to get string type ,then append it, but i debug the code , it doesn't work , no response , and i set breakpoin , it doesn't go into "groupers" static Method , why ?
Where you have
"{pid:25}",
dataType: "text",
change it to
'{"project_id":25}',
dataType: "json",

Resources