Ajax method to a webmethod in asmx is not firing - javascript

I have a strange problem with the below AJAX jQuery method to call a webmethod in an asmx service. It's not firing when I try to call it, but the moment I uncomment any of the alert in code to debug, it works all of sudden.
It confuses me, what would be the problem? Am I missing something here..
Code:
var endXsession = function() {
var fwdURL = "";
$.ajax({
type: "POST",
url: "Session.asmx/RemoveSession",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msge) {
//alert(msge.d);
fwdURL = msge.d;
},
error: function(response) {
//alert(response.responseText);
fwdURL = response.responseText;
}
});
//alert(fwdURL);
return fwdURL;
};

response.responseText is undefined ... it's response.statusText ..
function endXsession() {
var fwdURL = "";
$.ajax({
type: "POST",
url: "Session.asmx/RemoveSession",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msge) {
// alert(msge.d);
fwdURL = msge.d;
}
,
error: function (response) {
// alert(response.statusText);
fwdURL = response.statusText;
}
});
// alert(fwdURL);
return fwdURL;
}
console.log(endXsession());

Related

Passing data with ajax and read it with Request.Form[""]

I try to pass parameters into aspx.cs page from js script. When I omit:
contentType: "application/json; charset=utf-8"
in ajax request I get by Request.Form["ORDER"] sth like {%7b%22ORDER_ID%22%3a126333%7d}. It means that this data comes to aspx.cs, but it is not decoded.
When I add contentType I get nothing in request.
Below I attach request.
It is important to read parameters from Request.Form["ORDER"] in aspx.cs;
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ ORDER_ID: orderKeyId }),
dataType: "json",
url: sUrl,
success: function (data) {
var s = 0;
},
error: function () {
var s = 0;
}
});
According to #Rory McCrossan comment, below ajax state worked:
$.ajax({
type: 'POST',
contentType: "application/x-www-form-urlencoded",
data: "ORDER_ID=" + encodeURIComponent(orderKeyId),
url: sUrl,
success: function (data) {
var s = 0;
},
error: function () {
var s = 0;
}
});

reusable ajax and javascript function in CSHTML(RAZOR)

Im new in js and razor,part of my code should be repeated and this imposed more lines of code to my project,it could be nice if i can make it reusable,for example Ajax,where should i create a ajax to a specific URL to just call it when i need?in a separated razor file?in the following code,i have two click events and my ajax call and url is repeating,i want to get rid of this repeat:
function seriesClick(e) {
var _clicketBarChart = e.series.categoryField;
$.ajax({
dataType: "json",
type: "POST",
url: "#Url.Action("faultstatistics","Dashbrd")",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ "name": _clicketBarChart }),
success: function (result) {
faultstatChart(result);
}
});
function changeEvent(e) {
var _clicketCellGrid = e.categoryCell;
$.ajax({
dataType: "json",
type: "POST",
url: "#Url.Action("faultstatistics","Dashbrd")",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({"name": _clicketCellGrid }),
success: function (result) {
faultstatChart(result);
}
});
}
You have to create single method that can handle two situations, please refer to this example (based on your):
var ajaxHandler = function(targetName) {
$.ajax({
dataType: "json",
type: "POST",
url: "#Url.Action("faultstatistics","Dashbrd")",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({"name": _clicketCellGrid }),
success: function (result) {
faultstatChart(result);
}
});
}
var seriesClick = function(e) {
var targetName = e.series.categoryField;
ajaxHandler(targetName);
}
var changeEvent = function(e) {
var targetName = e.categoryCell;
ajaxHandler(targetName);
}

Html for response when i want a string

I have the function below:
function getHtmlFromMarkdown(markdownFormat, requestUrl) {
const dataValue = { "markdownFormat": markdownFormat }
$.ajax({
type: "POST",
url: requestUrl,
data: dataValue,
contentType: "application/json: charset = utf8",
dataType: "text",
success: function (response) {
alert(response);
document.getElementById("generatedPreview").innerHTML = response;
},
fail: function () {
alert('Failed')
}
});
}
And i have this on my server:
[WebMethod]
public static string GenerateHtmlFromMarkdown(string markdownFormat)
{
string htmlFormat = "Some text";
return htmlFormat;
}
I have on response html code, not the string that i want. What am I doing wrong?
And if i change the "dataType: json" it doesn't even enter either the success nor fail functions
Your data type of ajax must be json like this
function getHtmlFromMarkdown(markdownFormat, requestUrl) {
var dataValue = { "markdownFormat": markdownFormat }
$.ajax({
type: "POST",
url: requestUrl,
data: JSON.stringify(dataValue),
dataType: "json",
success: function (response) {
alert(response);
document.getElementById("generatedPreview").innerHTML = response;
},
error: function () { alert("Failed"); }
});
}
try with this.
function getHtmlFromMarkdown(markdownFormat, requestUrl) {
var obj={};
obj.markdownFormat=markdownFormat;
$.ajax({
type: "POST",
url: requestUrl,
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.d);
document.getElementById("generatedPreview").innerHTML = response.d;
},
failure: function () {
alert('Failed')
}
});
}

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.

How to get return value in a function with inside Ajax call - JQuery

this may sound very easy to few of you, but i am not able to figure out why I am not able to get the return value, even after chceking many posts :(
function getMessageCount() {
var count;
$.ajax({
type: "POST",
url: "http://localhost:43390" + "/services/DiscussionWidgetService.asmx/GetMessageCount",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
count = data.d;
} //success
});
return count;
}
Now if I call var count = getMessageCount();
it gives me undefinted :(
while inside the method count is coming correct, i.e. service is working fine.
I agree with the first line by ahren that
'That's because the $.ajax() call is asynchronous.'
you could try adding a setting - async:false
which is true by default. This makes the call synchronous.
you can edit your code as :
function getMessageCount() {
var count;
$.ajax({
type: "POST",
url: "http://localhost:43390" + "/services/DiscussionWidgetService.asmx/GetMessageCount",
dataType: "json",
async:false,
contentType: "application/json; charset=utf-8",
success: function (data) {
count = data.d;
} //success
});
return count;
}
That's because the $.ajax() call is asynchronous.
If you edit your code to something like:
function getMessageCount(callback) {
var count;
$.ajax({
type: "POST",
url: "http://localhost:43390" + "/services/DiscussionWidgetService.asmx/GetMessageCount",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
count = data.d;
if(typeof callback === "function") callback(count);
} //success
});
}
Then when you call it:
getMessageCount(function(count){
console.log(count);
});
use a callback:
call function like:
getMessageCount(function(result) {
//result is what you put in the callback. Count in your case
});
and the other like:
function getMessageCount(callback) {
var count;
$.ajax({
type: "POST",
url: "http://localhost:43390" + "/services/DiscussionWidgetService.asmx/GetMessageCount",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
count = data.d;
if (callback) {
callback(count);
}
} //success
});
}
Why you don't just pass it to a function?
function getMessageCount() {
var count;
$.ajax({
type: "POST",
url: "http://localhost:43390" + "/services/DiscussionWidgetService.asmx/GetMessageCount",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
count = data.d;
countMessages(count);
} //success
});
}
function countMessages(counted) {var counted = counted; console.log(counted);}
function ajax_call(url,data){
return $.ajax({ type: "POST",
url: url,
data: data,
async:false,
success: function(status){
}
}).responseText;
}
Now you will get the response text from server side via ajax call

Categories

Resources