$.ajax not calling WebService in ASP.Net - javascript

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..

Related

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 use recaptcha asp.net?

How to implement validate Google RECaptcha version 2.0 on Client Side using JavaScript and jQuery in ASP.Net?
The Google RECaptcha version 2.0 allows to validate the Captcha response on client side using its Callback functions.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
var onloadCallback = function () {
grecaptcha.render('dvCaptcha', {
'sitekey': '<%=ReCaptcha_Key %>',
'callback': function (response) {
$.ajax({
type: "POST",
url: "Default.aspx/VerifyCaptcha",
data: "{response: '" + response + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var captchaResponse = jQuery.parseJSON(r.d);
if (captchaResponse.success) {
$("[id*=txtCaptcha]").val(captchaResponse.success);
$("[id*=rfvCaptcha]").hide();
} else {
$("[id*=txtCaptcha]").val("");
$("[id*=rfvCaptcha]").show();
var error = captchaResponse["error-codes"][0];
$("[id*=rfvCaptcha]").html("RECaptcha error. " + error);
}
}
});
}
});
};
</script>

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!');
}
});

still not call with ajax in separate javascript file

I am new in jquery and ajax but my requirement is calling servlet/jsp through ajax using jquery so that my ajax code dosen't work in separate javascript file
Here is my javascript file that I called ajax through jquery :
function insertData(idvalue)
{
var forsplit = idvalue.id.split("_");
var qtsrl = forsplit[2];
var qtno = forsplit[3];
alert(qtsrl);
alert(qtno);
var queryid=idvalue.id;
var qtsrl_id = document.getElementById("qstn_srl_"+qtsrl+"_"+qtno).value;
var qstn_no_id = document.getElementById("qstn_no_"+qtsrl+"_"+qtno).value;
alert(qtsrl_id);
alert(qstn_no_id);
$.ajax(
{
url: "aftermarksave.jsp",
type: "get",
data:{setvalues : queryid},
dataType: "JSON",
success: function(data)
{
alert('Successful :'+data);
},
error: function(data)
{
alert('Not Successful: '+data);
}
});
}
Still not call to jsp page and I tried for Servlet page also that servlet is not called through ajax.
Try Like
$.ajax({
url: "URL",
type: "GET",
contentType: "application/json;charset=utf-8",
data: {setvalues : queryid},
dataType: "json",
success: function (response) {
alert(response);
},
error: function (x, e) {
alert('Failed');
alert(x.responseText);
alert(x.status);
}
});
OR
$.get("URL",function(data,status){
alert("Data: " + data + "\nStatus: " + status);
});

Webmethod did not work with jquery

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!

Categories

Resources