Webmethod did not work with jquery - javascript

I am using webmethod with Jquery. I have write a alert in success function and I got that alert when I run the project but My Webmthod did not call and So code is not work for me. I have put degub a point in Webmethod but it did not hit. I did not get any error nor my method call.
Below is my code of Jquery and Webmethod:
<script type='text/javascript' src="Scripts/jquery-1.4.1.min.js"></script>
function onDialogClosed(sender, args) {
$(document).ready(function () {
$.ajax({
type: "POST",
url: "SpellChecker.aspx/Save",
data: { DocName: $("#txttest").val() },
success: function (msg) {
alert($("#txttest").val());
},
error: function (a,b,c) {
alert(a+ b+ c);
}
});
});
}
WebMEthod :
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string Save(string DocName)
{
try
{
GeneralDataTraveler objDataTraveller = new GeneralDataTraveler();
objDataTraveller.Field1 = Convert.ToString(DocName);
new ServiceCenter().SessionSetGeneralDataTraveller(objDataTraveller);
return "HEllo";
}
catch (Exception ex)
{
return null;
}
}

Try as below specifying content type, datatype and data as below format. It is working for me
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "order_form.aspx/GetAutoCompleteData",
data: '{DocName: "' + $("#txttest").val() + '" }',
dataType: "json",
success: function(data) {
//response(data.d);
alert('success');
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});

Try with following:
1.Enable Webmethod to be called from Script using:
[System.Web.Script.Services.ScriptService]
2.Enable the webservice PAGE METHOD to be called on page with scripting:
<cc1:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server" EnablePageMethods="true">
</cc1:ToolkitScriptManager>
Hope this helps!

Related

Ajax success event doesn't fire

Doing Okta Authentication on WebForms
The login works but the redirect part doesnt
I tried with void and to return json object/string but doenst work
if i delete contentType and dataType from ajax method the success event works but then i can't debbug the method and it wasn't doing what was suppose to do
My objective is at the end of the webmethod to redirect to SignedIn.aspx tried with this code but couldn't make it work either that's why im doing client side through ajax success method
HttpContext.Current.Response.Redirect("SignedIn.aspx");
Ajax:
function FormSubmit() {
$.ajax({
type: "POST",
url: "Example.aspx/Login",
data: "{hiddenSessionTokenField:'" + $('#hiddenSessionTokenField').val() + "'}",
dataType: "json",
async:false,
contentType: "application/json; charset=utf-8",
success: function (response) {
alert("Method Called Sucessfully" + response);
window.location.href = "http://localhost:8080/SignedIn.aspx";
},
error: function (response) {
alert("error " + response);
}
});
}
WebMethod
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static void Login(string hiddenSessionTokenField)
{
//var result = new { url = "http://localhost:8080/SignedIn.aspx" };
if (!HttpContext.Current.User.Identity.IsAuthenticated)
{
var properties = new AuthenticationProperties();
properties.Dictionary.Add("sessionToken", hiddenSessionTokenField);
properties.RedirectUri = "~/SignedIn.aspx";
//Okta Authentication
HttpContext.Current.GetOwinContext().Authentication.Challenge(properties,
OpenIdConnectAuthenticationDefaults.AuthenticationType);
//System.Web.Script.Serialization.JavaScriptSerializer s = new System.Web.Script.Serialization.JavaScriptSerializer();
//return s.Serialize(result));
}
//return s.Serialize(result));
}
$('#test').on('click', function () {
$.ajax({
type: "POST",
url: "TEST.aspx/Login",
data: "{hiddenSessionTokenField:'" + $('#hiddenSessionTokenField').val() + "'}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
// alert("Method Called Sucessfully");
window.location.href = "http://localhost:8080/index.aspx";
},
error: function (response) {
alert("error " + response);
}
});
})
public static void Login(string hiddenSessionTokenField) {
int x = 0;
}

Error function called when I parse the parameters using jquery AJAX function to asp.net behind code

This is my aspx page code
function grid(datas)
{
var datass = {datas: datas};
var myJSON = JSON.stringify(datass);
$.ajax({
url: 'EditCustomerBills.aspx/LoadGrid',
method: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: myJSON,
success: function (data) {
alert("Success");
},
error:function(error){
alert("failed");
}
});
}
and this is my behind code
[WebMethod]
public static string LoadGrid(string datas)
{
//GetCustomerBillDetail(data);
string datass = datas.ToString();
return datass;
}
I'm using code perfectly, but output is failed. I'm struggling for four days. please help me. thank you.
I don't know what is your "myJSON" is . according to me your code should be sometinhg like this.
[System.Web.Services.WebMethod]
public static string GetCurrentTime(string datas)
{
return "Hello " + datas + Environment.NewLine + "The Current Time is: "
+ DateTime.Now.ToString();
}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
<script type = "text/javascript">
function ShowCurrentTime() {
$.ajax({
type: "POST",
url: "CS.aspx/GetCurrentTime",
data: '{datas: "Your Data" }', // your data should be here.
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function(response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
alert(response.d);
}
</script>
below picture will give you a idea how we can call the server side method.
for more reference please see this.
edit as follows and share with f12 in console output?
error: function (error) {
console.log(error);
}

How do I call a server side VB.net function from jquery in an asp.net form?

I am trying to call a method in my server-side vb code from jquery.
import System.Web.Services
...
'my VB.net Code
<WebMethod()> _
Public Shared Function SubmitReport_Click()
'this is where my code will go
Return Nothing
End Function
In my javascript code the alert is being called but the SubmitReport_Click is not being called.
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
<script type="text/javascript">
$("#<%= FileInput.ClientID%>").on('filebatchselected', function (event) {
alert("file input");
pagemethods.SubmitReport_Click();
})
</script>
I'd make a function that fires on the click event and calls over to your web method using AJAX, and use JSON to pass any relevant data.
$(".clickMe").click(doWebMethod);
function doWebMethod () {
var data = { 'name': 'jessikwa' , 'location': 'ny' }
var params = "{'dataPackage': '" + JSON.stringify(data) + "'}";
$.ajax({
type: "POST",
url: webMethodUrl,
async: true,
data: params,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
},
error: function () {
alert("fail");
}
});
}
//VB HERE
<WebMethod()> _
Public Shared Function SubmitReport_Click(ByVal dataPackage as String) as String
Dim rtnStr As String = "OK"
//deserialize data package here
Return rtnStr
End Function
You can use an Ajax request. I just typed this up, so you may need to Google the syntax in case I messed it up.
$.ajax({
type: "GET",
url: "FileName.aspx/SubmitReport_Click",
success: function(){
alert('It Worked!');
},
failure: function() {
alert('It Failed!');
}
});

Making a Simple Ajax call to controller in asp.net mvc

I'm trying to get started with ASP.NET MVC Ajax calls.
Controller:
public class AjaxTestController : Controller
{
//
// GET: /AjaxTest/
public ActionResult Index()
{
return View();
}
public ActionResult FirstAjax()
{
return Json("chamara", JsonRequestBehavior.AllowGet);
}
}
View:
<head runat="server">
<title>FirstAjax</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var serviceURL = '/AjaxTest/FirstAjax';
$.ajax({
type: "POST",
url: serviceURL,
data: param = "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
alert(data);
}
function errorFunc() {
alert('error');
}
});
</script>
</head>
I just need to print an alert with the controller method returning data. Above code just print "chamara" on my view. An alert is not firing.
UPDATE
I modified my controller as below and it start working. I don't have an clear idea why it's working now. Some one please explain. The parameter "a" does not related i added it because i can not add two methods with same method name and parameters.I think this might not be the solution but its working
public class AjaxTestController : Controller
{
//
// GET: /AjaxTest/
[HttpGet]
public ActionResult FirstAjax()
{
return View();
}
[HttpPost]
public ActionResult FirstAjax(string a)
{
return Json("chamara", JsonRequestBehavior.AllowGet);
}
}
Remove the data attribute as you are not POSTING anything to the server (Your controller does not expect any parameters).
And in your AJAX Method you can use Razor and use #Url.Action rather than a static string:
$.ajax({
url: '#Url.Action("FirstAjax", "AjaxTest")',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
From your update:
$.ajax({
type: "POST",
url: '#Url.Action("FirstAjax", "AjaxTest")',
contentType: "application/json; charset=utf-8",
data: { a: "testing" },
dataType: "json",
success: function() { alert('Success'); },
error: errorFunc
});
After the update you have done,
its first calling the FirstAjax action with default HttpGet request
and renders the blank Html view . (Earlier you were not having it)
later on loading of DOM elements of that view your Ajax call get fired and displays alert.
Earlier you were only returning JSON to browser without rendering any HTML. Now it has a HTML view rendered where it can get your JSON Data.
You can't directly render JSON its plain data not HTML.
Use a Razor to dynamically change your URL by calling your action like this:
$.ajax({
type: "POST",
url: '#Url.Action("ActionName", "ControllerName")',
contentType: "application/json; charset=utf-8",
data: { data: "yourdata" },
dataType: "json",
success: function(recData) { alert('Success'); },
error: function() { alert('A error'); }
});
If you just need to hit C# Method on in your Ajax Call you just need to pass two matter type and url if your request is get then you just need to specify the url only. please follow the code below it's working fine.
C# Code:
[HttpGet]
public ActionResult FirstAjax()
{
return Json("chamara", JsonRequestBehavior.AllowGet);
}
Java Script Code if Get Request
$.ajax({
url: 'home/FirstAjax',
success: function(responce){ alert(responce.data)},
error: function(responce){ alert(responce.data)}
});
Java Script Code if Post Request and also [HttpGet] to [HttpPost]
$.ajax({
url: 'home/FirstAjax',
type:'POST',
success: function(responce){ alert(responce)},
error: function(responce){ alert(responce)}
});
Note: If you FirstAjax in same controller in which your View Controller then no need for Controller name in url. like url: 'FirstAjax',
First thing there is no need of having two different versions of jquery libraries in one page,either "1.9.1" or "2.0.0" is sufficient to make ajax calls work..
Here is your controller code:
public ActionResult Index()
{
return View();
}
public ActionResult FirstAjax(string a)
{
return Json("chamara", JsonRequestBehavior.AllowGet);
}
This is how your view should look like:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var a = "Test";
$.ajax({
url: "../../Home/FirstAjax",
type: "GET",
data: { a : a },
success: function (response) {
alert(response);
},
error: function (response) {
alert(response);
}
});
});
</script>
It's for your UPDATE question.
Since you cannot have two methods with the same name and signature you have to use the ActionName attribute:
UPDATE:
[HttpGet]
public ActionResult FirstAjax()
{
Some Code--Some Code---Some Code
return View();
}
[HttpPost]
[ActionName("FirstAjax")]
public ActionResult FirstAjaxPost()
{
Some Code--Some Code---Some Code
return View();
}
And please refer this link for further reference of how a method becomes an action. Very good reference though.
View;
$.ajax({
type: 'GET',
cache: false,
url: '/Login/Method',
dataType: 'json',
data: { },
error: function () {
},
success: function (result) {
alert("success")
}
});
Controller Method;
public JsonResult Method()
{
return Json(new JsonResult()
{
Data = "Result"
}, JsonRequestBehavior.AllowGet);
}
instead of url: serviceURL,
use
url: '<%= serviceURL%>',
and are you passing 2 parameters to successFunc?
function successFunc(data)
{
alert(data);
}
Add "JsonValueProviderFactory" in global.asax :
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());
}

$.ajax not calling WebService in ASP.Net

I am trying to call webservice through jQuery but it is not showing any results or errors. My code is:
<script type="text/javascript" language="javascript">
var empId = '<%= Session["UserName"] %>';
</script>
<script type="text/javascript">
alert(empId);
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: "ServiceGetUser.asmx/GetEmployee",
data: "{'employeeId': '" + empId + "'}",
success: function (data) {
alert("Employee name: " + data.d);
},
error: function () {
alert("Error calling the web service.");
}
});
</script>
I'm getting a value from session printing it successfully then passing it to the webservice and in return printing name Jane Developer as shown in my webservice code:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
namespace MentorMentee
{
/// <summary>
/// Summary description for ServiceGetUser
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class ServiceGetUser : System.Web.Services.WebService
{
[WebMethod]
public string GetEmployee(string employeeId)
{
return "Jane Developer";
}
}
}
what's wrong is going on hopes for your suggestions
Thanks
You can put this in doc ready block:
$(window).load(function(){
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: "ServiceGetUser.asmx/GetEmployee",
data: {'employeeId': '<%= Session["UserName"] %>'}, //<-- try it
success: function (data) {
alert("Employee name: " + data.d);
},
error: function () {
alert("Error calling the web service.");
}
});
});
dataType is given as json. Which means that jquery will parse the response received from server into json. But you are returning string in your service. So parse error will be thrown by jQuery.
Try attaching complete(jqXHR jqXHR, String textStatus) callback. And look at textStatus
Try using
<script type="text/javascript" language="javascript">
var empId = '<%= Session["UserName"] %>';
</script>
<script type="text/javascript">
alert(empId);
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: "ServiceGetUser.asmx/GetEmployee",
data: "{'employeeId': '" + empId + "'}",
success: function (data) {
alert("Employee name: " + data.d);
},
error: function () {
alert("Error calling the web service.");
} ,
complete: function(xhr, textStatus) {
alert(textStatus);
}
});
</script>
Try this:
<script type="text/javascript" language="javascript">
var empId = '<%= Session["UserName"] %>';
</script>
<script type="text/javascript">
alert(empId);
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "ServiceGetUser.asmx/GetEmployee",
data: '{employeeId: "' + $("#<%=employeeId.ClientID%>")[0].value + '" }',
success: function (data) {
alert("Employee name: " + data.d);
},
error: function () {
alert("Error calling the web service.");
}
});
</script>
First try to stringify your json like this
alert(JSON.stringify(data)) then maybe u can find your mistake..

Categories

Resources