Sending Param to the Ajax of jQuery not effective - c#

I'm trying to use Ajax of jQuery, I have this code below and although I get no error in firebug it's not working, It seems the function in code behind doesn't get any params.
(document).ready(function () {
$("#S1").click(function
() {
$("#t1").toggle("fast");
$("#P1").toggle("fast");
$("#S1").css("background-color", "White");
var ID = $("#HiddenField1").attr("Value");
var params = { 'Key': ID };
$.ajax({
type: "POST",
url: "viewMessages.aspx/readen",
data: params,
dataType: "json"
});
});
});
and here is the code behind
[WebMethod(EnableSession = false)]
public static void readen(string Key)
{
DBController db = new DBController();
db.ReadenMes(Convert.ToInt32(Key));
}
the code below work but since I wanna use it in IE 6 I have to use the code above.
$(document).ready(function () {
$("#S2").click(function
() {
$("#t2").toggle("fast");
$("#P2").toggle("fast");
$("#S2").css("background-color","White");
var ID = $("#HiddenField2").attr("Value");
var params = new Object();
params.Key = ID;
var myJSONText = JSON.stringify(params);
$.ajax({
type: "POST",
url: "viewMessages.aspx/readen",
data: myJSONText,
contentType: "application/json",
dataType: "json"
});
});
});
where do you think i'm doing wrong?

3 mistakes to avoid when using jQuery with ASP.NET AJAX
$(document).ready(function () {
$("#S1").click(function
() {
$("#t1").toggle("fast");
$("#P1").toggle("fast");
$("#S1").css("background-color", "White");
var ID = $("#HiddenField1").val();
var params = "{ 'Key':'" + ID + "'}"; //changes here
$.ajax({
type: "POST",
url: "viewMessages.aspx/readen",
data: params,
dataType: "json",
contentType: "application/json; charset=utf-8"
});
});
});

If your issue only is that IE6 has no JSON.stringify method, than you can use json2.js from Douglas Crockford and then your second sample should work as expected in IE6 too.
$(function () {
$("#S2").click(function
$("#t2").toggle("fast");
$("#P2").toggle("fast");
$("#S2").css("background-color","White");
var ID = $("#HiddenField2").attr("Value");
var myJSONText = JSON.stringify({ Key: ID });
$.ajax({
type: "POST",
url: "viewMessages.aspx/readen",
data: myJSONText,
contentType: "application/json",
dataType: "json"
});
});
});
Another approach is do not use 'json' datatype, and then params should be serialized as regular query string.
$(function () {
$("#S2").click(function
$("#t2").toggle("fast");
$("#P2").toggle("fast");
$("#S2").css("background-color","White");
var ID = $("#HiddenField2").attr("Value");
var params = { Key: ID };
$.post("viewMessages.aspx/readen", params);
});
});

var ID = $("#HiddenField2").val();
$.ajax({
type: "POST",
url: "viewMessages.aspx/readen",
data: {"KEY":ID},
contentType: "application/json",
dataType: "json"
});
Also you don't need to stringify the data component nor do you need to declare an new Object.

Related

ASP.NET C# Ajax Call Error

I'm going straight to the point here.
I'm trying to get the value pass from my ajax to controller and console.log the value. however, when I try to console.log the value it gives me error 500..
here's my code:
I've been doing ajax on php for a long time.. however, I'm still new to asp.net C# mvc so please bear with me.
AJAX:
$("#Property_ProvinceID").on("change", function () {
var $this = $(this);
var province_id = $this.val();
var $url = "/Property/GetCities";
alert("get:" + province_id);
$.ajax({
url: $url,
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data:{id: province_id},
success: function (data) {
console.log(data);
}
});
});
CONTROLLER:
[HttpPost]
public ActionResult GetCities(int id)
{
return Json(new { success = true });
}
here's the error I don't know what's wrong with my controller though.
POST http://localhost:43969/Property/GetCities 500 (Internal Server
Error)
if using contentType: 'application/json; charset=utf-8' then use JSON.stringify to convert the data being sent to a JSON string.
$("#Property_ProvinceID").on("change", function () {
var $this = $(this);
var province_id = $this.val();
var $url = "/Property/GetCities";
alert("get:" + province_id);
var data = JSON.stringify({id: province_id});
$.ajax({
url: $url,
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: data,
success: function (data) {
console.log(data);
}
});
});
As mentioned in the comments by #StephenMuecke
It does not need to be stringified if contentType: 'application/json; charset=utf-8', is removed (so that it uses the default application/x-www-form-urlencoded; charset=UTF-8').
you can add error function to check for possible error on your ajax.
Ex.
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}

Pass Strongly Typed data and JSON string to controller from $.ajax funtion in View

I have ASP.NET-MVC5 application. I have strongly typed form and I successfully can pass back to controller. Now I have JavaScript array variable that I need to also send so I need to post back both information from view to controller using .$ajax post function.
I have update code as to add avaScript array variable, since then I am getting null value for form data.
View
var AdditionalTenentList = {
StudentUWLID: []
};
$('#CreateStudentRentingApplicationForm').submit(function (e) {
e.preventDefault();
var AdditionalTenentJsonList = JSON.stringify(AdditionalTenentList);
alert(AdditionalTenentJsonList);
var formURL = $(this).attr("action");
$.ajax({
url: formURL,
type: "POST",
data: { ApplicationModelData: $(this).serialize(), TenentJSONList: AdditionalTenentJsonList },
}).done(function (data, textStatus, jqXHR) {
//// my other code here.....
}
</script>
In another function thats how I am pushing value to array
AdditionalTenentList.StudentUWLID.push(StudentUWLID);
Controller
[Authorize]
[HttpPost]
public ActionResult ApplyForAccommodation(AccommodationApplicationViewModel ApplicationModelData, string TenentJSONList)
{
return null;
}
with the following code I get header response as
$.ajax({
url: formURL,
type: "POST",
dataType:"JSON",
data: JSON.stringify({ TenentJSONList: AdditionalTenentList }),
}).done(function (data, textStatus, jqXHR) {
..........
public ActionResult ApplyForAccommodation(string [] TenentJSONList)
{
var a = "d";
return null;
}
I have found the answer as following;
var AdditionalTenentList = new Array();
$('#CreateStudentRentingApplicationForm').submit(function (e) {
e.preventDefault();
var formURL = $(this).attr("action");
var formData = $(this).serialize();
$.ajax({
url: formURL,
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ TenentJSONList: AdditionalTenentList, ApplicationModelData: $("#CreateStudentRentingApplicationForm").serializeObject() }),
}).done(function (data, textStatus, jqXHR) {
// .........my rest of code
...
[Authorize]
[HttpPost]
public ActionResult ApplyForAccommodation(string[] TenentJSONList, AccommodationApplicationViewModel ApplicationModelData)
{

Object obect error on jquery ajax request on dropdown change?

I'm using jquery ajax on dropdown change function.The problem is that even before hitting the url mentioned in the ajax request I'm getting Object object error.
The ajax request is as follows
$("#locationList").change(function () {
var locationNo = document.getElementById('<%=locationList.ClientID%>').value;
$.ajax({
url: "HealthReport.aspx/GetCashsafes",
data: "{ 'Location': '" + locationNo + "'}",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert("Success");
response($.each(data.d, function (key, value) {
$("#CashSafeList").append($("<option></option>").val(value.CashsafeId).html(value.CashsafeDisplaySerialNo));
}));
},
error: function (result) {
alert(result);
$("#CashSafeList").append($("<option></option>").val("-1").html("Select one"));
}
});
});
The server side code is as follows
[WebMethod]
public static string GetCashsafes(string Location)
{
Decimal userId = (Decimal)AMSECSessionData.userId;
List<Cashsafe> lstCashSafe = DropDown.getCashSafeListLocationwise(userId, Convert.ToDecimal(Location));
List<CashSafeSelect> lstCashSafeSelect = new List<CashSafeSelect>();
lstCashSafeSelect = lstCashSafe.Select(item => new CashSafeSelect()
{
CashsafeId=(decimal)item.CashsafeId,
CashsafeSerialNo=item.CashsafeSerialNo.ToString()
}).Distinct().ToList();
System.Web.Script.Serialization.JavaScriptSerializer jSearializer =
new System.Web.Script.Serialization.JavaScriptSerializer();
string sjson=jSearializer.Serialize(lstCashSafeSelect);
return sjson;
}
I've checked the string sjson and the data is returning correctly in json format.
Since the error is showing even before the url is hit,i'm confused on how to proceed further.
Any help will be appreciated.
Change the data like this
data: JSON.stringify({ 'Location': locationNo }),
Then your code will look like
$("#locationList").change(function () {
var locationNo = document.getElementById('<%=locationList.ClientID%>').value;
$.ajax({
url: "HealthReport.aspx/GetCashsafes",
data: JSON.stringify({ 'Location': locationNo }),
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert("Success");
response($.each(data.d, function (key, value) {
$("#CashSafeList").append($("<option></option>").val(value.CashsafeId).html(value.CashsafeDisplaySerialNo));
}));
},
error: function (result) {
alert(result);
$("#CashSafeList").append($("<option></option>").val("-1").html("Select one"));
}
});
});
Edit
Since your dataType is json, you should return json, not string. Change your server side code like this,
[WebMethod]
public static List<CashSafeSelect> GetCashsafes(string Location)
{
Decimal userId = (Decimal)AMSECSessionData.userId;
List<Cashsafe> lstCashSafe = DropDown.getCashSafeListLocationwise(userId, Convert.ToDecimal(Location));
List<CashSafeSelect> lstCashSafeSelect = new List<CashSafeSelect>();
lstCashSafeSelect = lstCashSafe.Select(item => new CashSafeSelect()
{
CashsafeId=(decimal)item.CashsafeId,
CashsafeSerialNo=item.CashsafeSerialNo.ToString()
}).Distinct().ToList();
return lstCashSafeSelect;
}
You dont have to serialize those lists
Issue solved,Thanks to every one who replied especially #Anoop.
Issue was that I've set Autopostback=true for the dropdown where the ajax call is made.I've removed the autopostback property of the dropdown and now the code is working fine.
I wonder how a fresh day,clear mind helps to solve the issues.

How to use a JSON object created in code behind?

In Info.aspx.cs i get a compressed file from the WebService. After decoding the content i have an xml File. Using XmlToJSON and JavaScriptSerializer the result is a JSON object. How can i use this object in Info.aspx?
Suppose your json is n below format
var A={
propertyOne: "propertyOne",
propertyTwo: "propertyTwo"
}
Use as below:
A.propertyOne
A.propertyTwo
Try this,
var returnValue = new Object();
returnValue.entityfirst = $("#entityfirst ").val();
returnValue.entitysecond = $("#entitysecond ").val();
returnValue.entitythird = $("#entitythird").val();
var request = $.ajax({
url: ..., //access method url
type: 'POST',
cache: false,
data: JSON.stringify(returnValue),
dataType: 'json',
contentType: 'application/json; charset=utf-8'
});
In you aspx page you have to use javascript if you do a dynamic load.
for example you call and recieve like this (jQuery) :
$.ajax({
url: "myUrlPageForCallJsonService",
type: 'POST',
data: "yourParamsForGettingJson"
dataType: 'json',
complete: function (results) { console.log('complete'); },
success: function (data) { //You logic in the success function
for (var i = 0; i < data.length; i++) {
console.log("success");
_html += '<li>'+ data[i].Param1 + '</li>';
}
_html += '</ul>';
$('#renderbody').html(_html);
},
fail: function (data) { console.log("fail"); }
});
Hope that's help

jQuery.ajax "data" parameter syntax

I am trying to pass the contents of a javascript variable to the server for processing. I can pass static strings no problem but when I pass a variable containing a string, the WebMethod is not called. Here is my code:
(Client)
function expand(checkbox)
{
var selectedrow = checkbox.parentNode.parentNode;
var rowindex = selectedrow.rowIndex;
var parent = document.getElementById("parentTable");
var NextRow = parent.rows[rowindex + 1];
var cols = selectedrow.cells[1];
var ID = cols.firstElementChild.attributes.value;
$.ajax({
type: "post",
url: "Playground.aspx/childBind",
data: "{sendData: ID}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) { alert("successful!" + result.d); }
})
NextRow.style.visibility = "visible";
}
(Server)
[WebMethod]
public static string childBind(string sendData)
{
return String.Format("Hello");
}
Now, if I were to try data: "{sendData: "ok"}", the WebMethod gets called and returns a response. How is my syntax wrong?
You don't have to pass it as a string. Since ID is a javascript variable you have to pass its value. When you pass data as "{sendData: ID}" it will not pass the value of ID.
Try this
data: { sendData: ID }
You were sending a string instead of an object ("{sendData: ID}" instead of {sendData: ID}). And the data you were sending wasn't JSON. So remove the contentType line and change the data line. You should re-write this as:
$.ajax({
type: "post",
url: "Playground.aspx/childBind",
data: {sendData: ID},
dataType: "json",
success: function (result) { alert("successful!" + result.d); }
})
You can also write this, if you want to send JSON:
$.ajax({
type: "post",
url: "Playground.aspx/childBind",
data: $.getJSON({sendData: ID}),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) { alert("successful!" + result.d); }
})
Since you are using jQuery run these tests for the answer:
var ID = 45;
var x = "{sendData: ID}";
alert(jQuery.isPlainObject(x)); // false
var y = { sendData: ID};
alert(jQuery.isPlainObject(y)); // true
Here is the jsFiddle:
http://jsfiddle.net/3ugKE/
You are passing in 'ID' as a string rather than a variable.
All you need to do is remove the quotes around your data object.
Further reading on JSON and javascript objects:
http://www.json.org/
http://www.w3schools.com/js/js_objects.asp
you can use this code :
$.ajax({
type: "post",
url: "Playground.aspx/childBind",
data: JSON.stringify({sendData: ID}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) { alert("successful!" + result.d); }
})

Categories