Pass the argument from ajax function to aspx.cs file - javascript

I have created some code in HTML, JS and AJAX, yet it does not work how I want it to.
<script type="text/javascript">
function DeleteSelectedRecord(id) {
alert(id);
$.ajax({
type: "POST",
url: "PrintTasks.aspx/DeleteRecord",
data: '{"id":"' + id + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
alert("Deleted!");
},
failure: function () {
alert("Failure!");
}
});
}
function CreateATableFromDataBase() {
var deserializedData = '<%=serializedList %>';
deserializedData = JSON.parse(deserializedData);
for (var i = 0; i < deserializedData.length; i++) {
document.write(
"<tr>" +
"<th scope=\"row\">" + i.toString() + "</th>" +
"<th>" + deserializedData[i]["Name"] + "</th>" +
"<th>" + deserializedData[i]["Where"] + "</th>" +
"<th>" + deserializedData[i]["Destination"] + "</th>" +
"<th><input type=\"button\" class=\"btn btn-primary\" onclick=\"DeleteSelectedRecord(" + deserializedData[i]["Id"] + ")\" value=\"Delete\"/></th>" +
"</tr>"
);
}
}
</script>
The second function passes the argument "id" to the first one. I have used alert method so as to check, whether at least it works properly. It does. The problem starts when I want to pass the parameter to my super method called DeleteRecord in PrintTasks.aspx.cs file...
[System.Web.Services.WebMethod]
public static void DeleteRecord(int id)
{
very sophisticated code...
}
It is not important what is inside. The most curious thing is that it does not read my parameter.
Thank you!

Just change This Line of code. It will work
data: '{"id":"' + id + '"}',
Change to
data: { id:id},
First id is the parameter name you set in .cs file method.. and second
one is value you are going to pass...

Try as mentioned below :
$.ajax({
type: "POST",
url: "PrintTasks.aspx/DeleteRecord?id=" + id,
success: function () {
alert("Deleted!");
},
failure: function () {
alert("Failure!");
}
});
Or
$.ajax({
type: "POST",
url: "PrintTasks.aspx/DeleteRecord",
data: JSON.stringify({id:id}),
contentType: "application/json;",
dataType: "json",
success: function () {
alert("Deleted!");
},
failure: function () {
alert("Failure!");
}
});

Use $.param() function for sending data to server.
Here is the code:
$.ajax({
type: "POST",
url: "PrintTasks.aspx/DeleteRecord",
data: $.param({"id": id}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
alert("Deleted!");
},
failure: function () {
alert("Failure!");
}
});

Try by changing your ajax code
$.ajax({
type: "POST",
url: "PrintTasks.aspx/DeleteRecord",
data: '{"id":"' + ParseInt(id) + '"}',//change your code here
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
alert("Deleted!");
},
failure: function () {
alert("Failure!");
}
});

Related

Calling a javascript function from a global file and return it to append to html

I have a global javascript file 'Global.js' with a Global Handler 'GlobalHandler.ashx',
what i am trying to do is to render some data in the back-end (inside the handler ), than return text data using context.Response.Write(MyString)
The question is how to append the data to my html element .
I looked into the response (200) and the data is there , but i don't know the reason of not appending my text into the html element
I have tried to append them like the classic way success:function(data){
$(elementID).html(data);}
But that doesnt work
Here In Global.js
function GetProfession(elementID) {
$.ajax({
url: "/Handlers/GlobalHandler.ashx",
dataType: "JSON",
contentType: "application/json;charset=utf-8",
//responseType: ResponseType,
data: {
functionName: "GetProfession"
},
success: function (data) {
return $("#" + elementID).html(data);
}
});
}
Here In MyPage.aspx
$(document).ready(function () {
GetProfession("Profession");
});
HERE In the Handler
string functionName = context.Request["functionName"];
GroupDAO GroupDAO = new GroupDAO();
if (functionName.Equals("GetProfession"))
{
var ListOfGroups = GroupDAO.GetGroups();
string Builder = "";
foreach (var group in ListOfGroups)
{
Builder+="<option value='" + group.GroupID + "'>" + group.GroupName + "</option>";
}
context.Response.Write(Builder);
}
I am expecting to have those options appended to the html element 'Profession'
but this unfortunately it does not happening
I found the answer , i did not recognize the logical reason of such behaviour ,
but the data was not in the success method even if the statuc code was 200 .
in fact it was in the error: properties of ajax request .
what i have done is :
instead of appending the data in success to the html element .
i did it in the response text
.
Here is the code before not working :
function GetProfession(elementID) {
$.ajax({
url: "/Handlers/GlobalHandler.ashx",
dataType: "JSON",
contentType: "application/json;charset=utf-8",
//responseType: ResponseType,
data: {
functionName: "GetProfession"
},
success: function (data) {
return $("#" + elementID).html(data);
}
});
}
Here is the one that works
function GetProfession(elementID) {
$.ajax({
url: "/Handlers/GlobalHandler.ashx",
dataType: "JSON",
contentType: "text/html; charset=utf-8",
//responseType: ResponseType,
data: {
functionName: "GetProfession"
},
success: function (data, fata, meta) {
},
error: function (err) {
$("#Profession").html(err.responseText);
//alert(err.responseText);
}
});
}

How to simplfy the passing of parameter

I have these method in c# which requires 3 parameters
public void Delete_AgentTools(int ID,int UAM,int mode)
{
some code etc.
}
and I use javascript ajax to call this method and pass the parameter
function Delete_AgentTools(toolAccess, toolId, UAM) {
$.ajax({
type: "POST",
url: "IROA_StoredProcedures.asmx/Delete_AgentTools",
data: "{'toolAccess':'" + toolAccess + "', 'toolId':'" + toolId + "', 'UAM':'" + UAM + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success:function()
{
alert("Tool has been successfully delete");
},
error: function (XMLHttpRequest)
{
alert("error in Delete_AgentTools()");
console.log(XMLHttpRequest);
}
});
}
you see for me I want to simpilfy on how I pass the parameter in javascript. Is it possible to pass it as an object to the c# or simplify the passing of parameters in javascript
You can convert a js object as a JSON using JSON.stringify
var data = {};
data.toolAccess = value1;
data.toolId = value2;
data.UAM = value3;
$.ajax({
type: "POST",
url: "IROA_StoredProcedures.asmx/Delete_AgentTools",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
success:function()
{
alert("Tool has been successfully delete");
},
error: function (XMLHttpRequest)
{
alert("error in Delete_AgentTools()");
console.log(XMLHttpRequest);
}
});
function Delete_AgentTools(toolAccess, toolId, UAM) {
var data = {};
data.mode = toolAccess;
data.ID = toolId;
data.UAM = UAM;
$.ajax({
type: "POST",
url: "IROA_StoredProcedures.asmx/Delete_AgentTools",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
success:function()
{
alert("Tool has been successfully delete");
},
error: function (XMLHttpRequest)
{
alert("error in Delete_AgentTools()");
console.log(XMLHttpRequest);
}
});
No need to change in your C# code.

Need assistance with understanding .each() and issue with duplicate in Ajax GET

I have an ajax code as below :
<script>
$(document).ready(function () {
EmployeeStates("Available", 1, 15);
});
function EmployeeStates(state, pageNumber, pageSize) {
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "http://localhost:58102/api/EmployeeState?state=" + state + "&pageNumber=" + pageNumber + "&pageSize=" + pageSize,
//data: JSON.stringify({ "state": state,"pageNumber":pageNumber,"pageSize":pageSize }),
dataType: "json",
success: function (data) {
$.each(data, function (index, emp) {
$("#ReservationDesignation").append(emp.employee.designation.designationName);
});
},
fail: function (error) {
Console.Log(error);
}
})
}
</script>
While assigning the Designation name (emp.employee.designation.designationName) to #ReservationDesignation, I am getting a duplicate.
ie, ArchitectArchitect. The actual result should be Architect.
I am not familiar with .each() function.
Can anyone help me to remove the duplicate from the result?
Thank You.

Bootstrap Table remove row if column have no data

Hi have this WCF Service and consuming that is working. My problem is column 7 may be empty, so in the client side i want to remove all rows that have column 7 empty. Any help will be welcome.
function GetPedidosAll(muser) {
jQuery.ajax({
cache: false,
type: "GET",
url: "/_vti_bin/XP/Requests.svc/GetPedidosListAll/" + muser +
"/" + $("#sel_state").val() + "/" + $("#sel_project").val(),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#lista_pedidos").bootstrapTable({
data: data
});
},
error: function (jqXhr, status) {
$("#img_Progress").hide();
MessPopups("e", status.message);
}
});}
Thank You,
JL
success: function (data) {
data = jQuery.grep(data, function (a) {
return a.Permissao !== "";
});
$("#lista_pedidos").bootstrapTable({
data: data
});
}

GetCitiesByRegion is not defined?

I have a page, and i've got a link looking like:
<span>Nordjylland</span>
And in my Javascript file, i've got a function called GetCitiesByRegion(), however, when clicking the link, i get an error, saying that GetCitiesByRegion is not defined?
The function looks like this:
function GetCitiesByRegion(id) {
var params = '{"id":"' + id + '"}'
var request = {
type: "GET",
async: false,
cache: false,
url: "http://" + location.hostname + "/webservices/services.svc/GetCitiesByRegion",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: params,
success: function (result) {
alert("Data Loaded: " + result);
},
error: function (xhr, status, error) {
alert('Fejl ved webservice: error: ' + error);
}
};
$jq.ajax(request);
}

Categories

Resources