How to remove current row from a html table in jQuery json? - c#

I want to write code for multipledelete by using jquery json.
This is the jquery code:
function DeleteSelected() {
var categories = new Array();
debugger;
// iterate all checkboxes and obtain their checked values, unchecked values are not pushed into array
$("input[type='checkbox']").each(function ()
//$('input[type=checkbox]').prop("checked", this.checked)
{
this.checked ? categories.push($(this).val()) : null;
});
// assume urldata is your web method to delete multiple records
var urldata = "WebForm5.aspx/deleteRecord";
debugger;
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: urldata,
data: "{ 'Id':'"+JSON.stringify( categories)+"' }", // used to convert array into proper JSON format
dataType: "json",
success: function (dt) {
// done whatever tasks if succeeded
alert("entry deleted");
debugger;
$("#example1").DataTable();
//$("#example1").bind;
debugger;
},
error: function (result) {
alert("Error");
}
});
}
This is aspx code(codebehind for multiple delete):
[WebMethod]
// note clear difference between single and multiple selections
public static void deleteRecord(List<int> Id)
{
clsCategoryBL objproject = new clsCategoryBL();
// iterate through input list and pass to process method
for (int i = 0; i < Id.Count; i++)
{
objproject.CategoryDelete(Id[i]);
}
}
I want to pass the id to aspx page but the problem is that output comes error popup.
error: function (result) {
alert("Error");
}

The below line will return JSON for the array categories
"{ 'Id':'"+JSON.stringify( categories)+"' }"
Validate the value with http://jsonlint.com/ and check if the result is valid JSON.
Since you had declared the method as public static void deleteRecord(List<int> Id) that means the expected input will be like [1,2,3]
Also use below line to get exact error coming
error: function (xhr, ajaxOptions, thrownError) {
alert("error # " + xhr + ajaxOptions + thrownError);
}
UPDATE 1:
Below is working code
var categories = new Array();
// do your logic to push
categories.push(1);
categories.push(2);
categories.push(3);
var valuetxt = "{ \"Id\":\"" + JSON.stringify(categories) + "\" }";
var urldata = "WebForm1.aspx/deleteRecord";
$.ajax({
type: "POST",
url: urldata,
data: valuetxt, // used to convert array into proper JSON format
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
// in result you will get same data which is posted
alert(result.d);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("error # " + xhr + ajaxOptions + thrownError);
}
});
[WebMethod]
// change the parameter to string, convert back JSON to Integer Array
public static string deleteRecord(string Id)
{
// do something - for sample here returning same JSON of integer
return Id;
}

Related

Map Json data to an object using AJAX and C#

how can I use the Json formatted data sent by an AJAX request in C#?
Here's the View with the JQuery and AJAX
<script type="text/javascript">
$(function () {
$("#btnGet").click(function () {
var values =
{
"Name": "Manuel Andrade",
"DateOfBirth": "12/01/1995"
}
$.ajax({
type: "POST",
url: "/api/WebApi/GetAge",
data: values,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("Hello: " + response.Name + ".\nCurrent Date and Time: " + response.DateTime);
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
});
</script>
Here's the Controller:
public class PersonController : ApiController
{
[System.Web.Http.Route("api/WebApi/GetAge")]
[System.Web.Http.HttpPost]
public Person GetAge(Person person)
{
//person = new Person();
//person.Name = "Luis";
JsonTest(person);
//int ageInMonths = calculateAgeInMonths(person);
//int ageInYears = calculateAgeInYears(person);
//System.Diagnostics.Debug.WriteLine(ageInMonths);
//System.Diagnostics.Debug.WriteLine(ageInYears);
return person;
}
}
The Person Model has exactly the same attributes as the Json variable in the view. Shouldn't it create an object automatically? The method JsonTest() works properly, it is used to serialize the data. If I uncomment the person instantiation and assignation to Luis the method does return a Json with that data to the view. But if I try to use the person parameter just like that it throws a null Exception. How can I pass the var values in the View to the GetAge method so I can assign it to an object?
It worked fine for me when I removed the contentType: "application/json; charset=utf-8", line.
It isn't returned as application/json by default.

Error: Undefined object! while parsing JSON using jquery

This should be simple but I cannot seem to get this to work correctly.
Given a JSON string that looks like this:
{
"?xml":
{
"#version":"1.0",
"#encoding":"ISO-8859-1"
},
"results":
{
"title":"AOL Movies - Closest Theater and Showtimes",
// etc,
"theater":
{
"theaterId":"10650",
"id":"10650",
// etc
},
"movie":
[
{
"studios":"Warner Bros.",
"movieId":"61683"
}
]
}
I continually get undefined objects when trying to get to any value, for example:
data.movie, or data.results.title.
Everything "looks" ok in the output.
jQuery.ajax({
type: 'GET',
contentType: 'application/json',
url: 'handler.ashx',
data: 'zip=' + postalCodes.join(','),
success: function (payload) {
var data = that.objectifyJSON(payload); // this returns typeof = object
that.constructMoviesArray(data);
},
error: function (error) {
alert(error.responseText);
}
});
this.constructMoviesArray = function (data) {
var key, movie, theater = null;
var movies = {};
movies.items = {};
movies.length = 0;
alert(data[0].movie); // FAIL - there's clearly an array but nothing displays
I hope this is enough information; I am not experienced with JSON and jQuery so I'm struggling to figure out why I can't seem to resolve this.
Add the json dataType. http://api.jquery.com/jquery.ajax/
The server response is probably still a string even though you set the contentType.
jQuery.ajax({
type: 'GET',
contentType: 'application/json',
url: 'handler.ashx',
data: 'zip=' + postalCodes.join(','),
dataType: 'json', // <--- UPDATE ME
success: function (payload) {
var data = that.objectifyJSON(payload); // this returns typeof = object
that.constructMoviesArray(data);
},
error: function (error) {
alert(error.responseText);
}
});
If that doesn't help, try adding a console.log or a breakpoint to the success callback. You'll be able to take a closer look at what kind of data you are working with in payload.
success: function (payload) {
console.log(payload);
},
Hope that helps!
Try Like
var geocodingAPI = "http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true";
$.getJSON(geocodingAPI, function (json) {
// Set the variables from the results array
var address = json.results[0].formatted_address;
console.log('Address : ', address);
var latitude = json.results[0].geometry.location.lat;
console.log('Latitude : ', latitude);
var longitude = json.results[0].geometry.location.lng;
console.log('Longitude : ', longitude);
// Set the table td text
$('#address').text(address);
$('#latitude').text(latitude);
$('#longitude').text(longitude);
});
Demo

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.

Iterate returned c# serialized List<string> in jQuery

I have a webmethod which will read the first line in a csv file to get the column titles then store each item in the list which I will return to the ajax call. This is the code:
[WebMethod]
public static string getAvailableSensors()
{
List<string> sensors = new List<string>();
try
{
string path = "C:\\.....\\TestData3.csv";
string line;
using (StreamReader sr = new StreamReader(path))
{
line = sr.ReadLine();
sensors = line.Split(',').ToList();
}
}
catch (Exception ex)
{
string error = ex.Message;
}
JavaScriptSerializer jss = new JavaScriptSerializer();
string output = jss.Serialize(sensors);
return output;
}
This is what the data looks like when it is returned to the ajax call:
This is what my ajax looks like :
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "WebSockets.aspx/getAvailableSensors",
async: false,
data: "{ }", // send an empty object for calls with no parameters
success: function (result) {
debugger;
data = result.d;
for (var i in result.d) {
sensors.push(result.d[i]);
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert("an error has occured: " + xhr.responseText);
}
});
but this only populates the array 1 character at a time which is not what I am trying to do.
I cannot figure out how to iterate the damn json so that I can populate my var sensors = new Array(); with the columns. ex( sensor[0] should be "Time", sensor[ 1 ] should be "X Accel LH" ) etc.
First of all you need to make that string as an object. Use jQuery.parseJSON() to make it as object.
data=jQuery.parseJSON(data);
In your case, you can use the data like a string array
In your AJAX options you should set dataType: 'json' so that the response is automatically converted to JSON before being handed to your callback. This is probably what you expected the contentType to do, but in reality that sets the type of the content being sent, not what you expect to be returned. You might also want to apply a ScriptMethodAttribute and specify the result being returned is JSON - I believe this will set the Content-Type header so that jQuery can automatically detect the format in the absence of specifying it in your options.
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string getAvailableSensors()
{
...
}
JavaScript
$.ajax({
type: "POST",
dataType: "json", // <-- this
contentType: "application/json; charset=utf-8",
url: "WebSockets.aspx/getAvailableSensors",
async: false,
data: "{ }", // send an empty object for calls with no parameters
success: function (result) {
debugger;
data = result.d;
for (var i in result.d) {
sensors.push(result.d[i]);
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert("an error has occured: " + xhr.responseText);
}
});
If you're using a newer version of jQuery you might want to look into replacing your success and error callbacks with the done and fail methods.
$.ajax({
type: "POST",
dataType: "json", // <-- this
contentType: "application/json; charset=utf-8",
url: "WebSockets.aspx/getAvailableSensors",
async: false,
data: "{ }", // send an empty object for calls with no parameters
})
.done(function(result) {
debugger;
data = result.d;
for (var i in result.d) {
sensors.push(result.d[i]);
}
})
.fail(function(xhr, status, error) {
alert("an error has occured: " + xhr.responseText);
});
You could just return an IList<string> from your web method instead of serializing manually.
[WebMethod]
public static IList<string> getAvailableSensors()
{
List<string> sensors = new List<string>();
string path = "C:\\.....\\TestData3.csv";
string line;
using (StreamReader sr = new StreamReader(path))
{
line = sr.ReadLine();
sensors = line.Split(',').ToList();
}
return sensors;
}
Also, your error handling is not exaclty correct. For the client, the operation succeeded even if there is an error on server side. I just removed you try catch to let the exception propagate to the client.

How to read json response as name value pairs in JQuery ajax

I want to read json response as name and value pairs in my JQuery code. Here is my sample JSON response that I return from my dotnet code:
const string format = "\"HasCases\": \"{0}\"";
StringBuilder json = new StringBuilder(128);
json.Append("{");
json.AppendFormat(format, JSONString("true"));
json.Append("}");
Response.Clear();
Response.AppendHeader("Content-type", "application/json; charset=utf-8"); Response.Write(json.ToString());
Response.End();
To get Json value ,is it necessary to use Response code?In my Json page , I am able to get the output as HasCases : true.
Here is my JQuery code
<span id="testSpan" runat="server">inactive</span>
<script type="text/javascript">
inactive
$.ajax({
type: 'POST',
url: "~/Pages/UserCaselistnonEmptyAjax.aspx",
dataType: "json",
success: function (response){
$('#testSpan').innerHTML = response.HasCases;
},
error: function (e1, e2, e3) {
$('#testSpan').innerHTML = 'Error';
}
});
</Script>
When I am debugging form firebug My control does not going to "$('#testSpan').innerHTML = response.HasCases; ".It is coming out from the loop.
jQuery objects don't implement .innerHTML. Use .html() instead:
$('#testSpan').html(response.HasCases);
I am returning my json using
return (new JavaScriptSerializer().Serialize(request));
in my c# code.and I am calling the function returning this value at page load event.
and the output is this
{"registration_ids":["1","2"],"data":{"message":"Your message","tickerText":"Your ticker","contentTitle":"Your content"}}
but I am unable to read this returned json fomrat with jquery ajax
my ajax is below
function as()
{
$.ajax({
type:"get",
url:"mydjson.aspx",
contentType: 'application/json;charset=utf-8',
dataType: {'json':'datas'},
//data: JSON.stringify(request),//{ get_param: 'value' },
success:function (msg) {
$("#table").html("<h1>" + msg+ "</h1>").fadeIn("slow");
},
// function (data, status)
error: function (xhr, textStatus, error)
{
var errorMessage = error || xhr.statusText;
$("#table").html("<h3>" + errorMessage + "</h3>").fadeIn("slow");
}
});
return false;
// });
}
I am getting the error "Ivalid json" plus the content of page" mydjson.aspx".help me for this.

Categories