Passing a string from code behind to ajax - javascript

I am accessing a method on the server side. The only problem is that I don't have alot of experience in AJAx. I am unable to retrieve the returned string in the ajax from the .cs method
$.ajax({
type: 'GET',
url: '/frmGpsMap.aspx?name=load',
dataType: 'text',
success: function(data) {
alert(data.d);
}
});
protected void Page_Load(object sender, EventArgs e)
{
string crrName = Request.QueryString["name"];
if (!String.IsNullOrEmpty(crrName))
{
if (crrName.ToLower().Equals("load"))
{
string fh= loadKMLFileToString();
hdnUsername.Value = fh;
}
}
}
public string loadKMLFileToString()
{
return "hello world";
}
The alert is returning the html of the page. I want to display the "Hello World" string

To get the code behind method to work with ajax you need to use System.Web.Services.WebMethod. By default you need to use POST unless you specify HTTP GET attribute in code behind
[System.Web.Services.WebMethod]
public static string LoadKMLFileToString()
{
return "Hello World";
}
Here is the ajax method for call
$.ajax({
type: "POST",
url: "frmGpsMap.aspx/LoadKMLFileToString",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
alert(response.d),
failure: function(response) {
alert(response.d);
}
});
I hope it helps.
More examples: http://weblogs.asp.net/karan/calling-server-side-method-using-jquery-ajax

I think you can decorate your cs method with the WebMethod attribute and call it directly from ajax. Like this:
$.ajax({
...
url: '/frmGpsMap.aspx?loadKMLFileToString',
...
});
[System.Web.Services.WebMethod]
public string loadKMLFileToString()
{
return "hello world";
}
Cheers! =)

Related

POST call using jquery AJAX not working

I am trying to build an ASP.NET MVC web service in which I am trying to make a POST call in javascript using jQuery ajax as below.
$.ajax({
url: "/bug/CreateBug",
type: "POST",
data: rowData,
contentType: "application/json",
datatype: "json", //return type
success: function (data) {
console.log(data);
},
error: function (xhr) {
alert('error');
}
});
I keep getting the error TypeError: e is undefined. I tried adding a log statement just before this ajax call and things are working fine. Not sure what am I missing out on. My rowData looks something like below.
{
"Date": "2016-12-31",
"Id": "1234-csj4-sadf-random",
"Scenario": "abc",
"IsFixed": "No"
}
My C# code in the controller looks something like this
[HttpPost]
public JsonResult CreateBug(string jsonRequest)
{
var bugId = GetBugId(jsonRequest);
return this.Json(bugId, JsonRequestBehavior.AllowGet);
}
I tried to test the above POST call using Postman and I got jsonRequest as null. Could someone pls help me out here on how can I get the POST request to work?
Thanks in advance!
try it hope it works
$.ajax({
url: "/bug/CreateBug",
type: "POST",
data: JSON.stringify(rowdata),
contentType: "application/json",
datatype: "json", //return type
success: function (data) {
console.log(data);
},
error: function (xhr) {
alert('error');
}
});
------ on controller
do something like this or the best approach is to create model with all these property and MVC will bind it for you.
[HttpPost]
public JsonResult CreateBug(string Id, string Date, string IsFixed , string Scenario)
{
var bugId = GetBugId(jsonRequest);
return this.Json(bugId, JsonRequestBehavior.AllowGet);
}

Ajax POST 404 Error With asmx

I am attempting to create a webmethod that I can call/POST to from javascript code, but I obtain the following error in console whenever the test() function is called:
"POST http://localhost:53093/TestMethods.asmx/HelloWorld 404 (Not Found)"
I have checked multiple questions similar to mine, but none of the solutions seem to work. Any help would be appreciated.
TestMethods.asmx.cs
[WebService(Namespace = "http://testdomain.com/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[ScriptService]
public class TestMethods : System.Web.Services.WebService
{
[WebMethod()]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string HelloWorld()
{
return "Hello World";
}
}
Javascript (game.js)
function test()
{
$.ajax({
url: "TestMethods.asmx/HelloWorld",
type: 'POST',
data: "{}",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (result) {
alert(result);
}
});
}
File Structure Image

Calling a C# method from .js file

I have a aspx page and in that i have method UpdateScreenAlertStatus();
I want to have a file called dtml.js and in that i have function openmodelpopup().
I want to call UpdateScreenAlertStatus(); in javscript method openmodelpopup().
function MyMethod() {
$.ajax({
type: "POST",
url: "abc.aspx/UpdateScreenAlertStatus ",
contentType: "application/json; charset=utf-8",
dataType: "json"
});
}
Call the above ajax in your js function openmodelpopup().
[WebMethod]
public static void UpdateScreenAlertStatus()
{....}
Make it a web method
[WebMethod]
public static string UpdateScreenAlertStatus()
{....}
Refer this MSDN article.
From javascript you can access this as YourPage.aspx/UpdateScreenAlertStatus or through PageMethods in same aspx page. You can call this with the following javascript.
function openmodelpopup() {
$.ajax
({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "YourPage.aspx/UpdateScreenAlertStatus",
success: (function (data) {
$("#statusDiv").text(data.d);
$("#statusDiv").show();
}),
error: (function () {
alert("Error occurred in server!");
})
});
}
I'm assuming here, 1. your C# method is static and marked WebMethod. 2. Code is compiled properly. 3. You are using jQuery. 4. The url in javascript is correct. 5. Your C# method returns a string status. 6. You are trying to update html element statusDiv with that string.

C# Web method is not calling in javascript

i create a web method and now i'm calling this in my java script file but it give an path error,it is not able to find path what i'm giving ..
Web method code is :
[System.Web.Services.WebMethod]
public static int ItemCount(string itemId)
{
int val = 0;
Item itm = Sitecore.Context.Database.GetItem(itemId);
val = itm.Children.Count;
return val;
}
java script function calling like as:
function GetItemCount(itemId) {
var funRes = "";
debugger;
try {
if (itemId != null) {
jQuery.ajax({
cache: false,
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Views/GetItem.aspx/ItemCount",
data: { itemId: itemId },
dataType: "json",
async: false,
success: function (data) {
funRes = data.result;
},
error: function(err) {
alert(err.responseText);
}
});
}
} catch (ex) {
alert(ex.message);
}
return funRes;}
while i'm giving exact path for the C# method class but it's not working give an error on console, can anyone suggest me what i'm missing here..
There are few rules for ajax to work with asp.net.
Your WebMethod should be public and static.
If your WebMethod expects some parameter(s) than these parameter(s) must be passed as data in ajax.
Name of parameter(s) should be same in WebMethod and in data part of ajax.
Data passed from ajax should be in json string.For this you can use JSON.stringify or you will have to surround the values of parameter(s) in quotes.
Please check the below sample ajax call
function CallAjax()
{
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/CallAjax",
data: JSON.stringify({ name: "Mairaj", value: "12" }),
dataType: "json",
async: false,
success: function (data) {
//your code
},
error: function (err) {
alert(err.responseText);
}
});
}
[WebMethod]
public static List<string> CallAjax(string name,int value)
{
List<string> list = new List<string>();
try
{
list.Add("Mairaj");
list.Add("Ahmad");
list.Add("Minhas");
}
catch (Exception ex)
{
}
return list;
}
EDIT
If you use GET in ajax than you need to enable your webmethod to be called from GET request. Add [System.Web.Script.Services.ScriptMethod(UseHttpGet = true)] on top of WebMetod
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod(UseHttpGet = true)]
public static int ItemCount()
Just Modify the javascript function as below
function GetItemCount(itemId) {
var funRes = "";
debugger;
try {
if (itemId != null) {
jQuery.ajax({
type: "GET",
url: "/Views/GetItem.aspx",
data: 'itemID=' + itemId,
contentType: "application/html",
dataType: "html",
success: function (response) {
funRes= response.result;
}
});
}
} catch (ex) {
alert(ex.message);
}
return funRes;
}
I am not sure it is a solution for every question subject which web method not fire. But I discovered today when there is ' char in the string. Web Method not firing.

How to call this.Page (server page) from javascript

I have methos to display content of page at server side like
DisplayDetails(Page PageNema)
{
///
}
How can i call this function from javascript as well as how can i pass Page argument from Javascript
If it's WebForm you must set this method as WebMethod, so then you can call this method from jQuery. Something like that:
Client Side.
$.ajax({
type: "POST",
url: "PageName.aspx/MethodName",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something interesting here.
}
});
Server side:
public partial class _Default : Page
{
[WebMethod]
public static string DisplayDetails()
{
//your code to retrieve details here
return Details;
}
}
[WebMethod]
public static string DisplayDetails(parameter1,parameter2,etc...)
{
return something;
}
Client side code
<script type="text/javascript">
function functionName(callback) {
$.ajax({
type: "POST",
url: 'PageName.aspx/DisplayDetails',// your function name
data: '{"argument1","argument2",etc...}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
// If u want something from serverside function then write your code here
},
error: function (e) {
}
});
}
</script >

Categories