unable to call a c# method from javascript using ajax - javascript

I have a c# method which I would like to call on client side.
I used ajax calling to achieve this
function ValidateIfDuplicate()
{
debugger
var billtext = $("#ctl00_ContentPlaceHolder2_textBoxBillNumber").val();
var retailer= $("#ctl00_ContentPlaceHolder2_dropDownListRetailers").val();
var billdate = $("#ctl00_ContentPlaceHolder2_textBoxBillDate").val();
if (billtext == "")
{
alert("Bill Number cannot be left empty");
return false;
}
else if (retailer == 0) {
alert("Please select a Retailer");
return false;
}
else if (billdate == '') {
alert("Date cannot be left empty");
return false;
}
else if (billtext != '' && retailer != '' && billdate != '')
{
$.ajax({
Type: "POST",
url: "CAInvoiceEntry.aspx/ValidateDuplicateEntry",
contentType: "application/json; charset=utf-8",
data: { billtext1: billtext, billdate1: billdate, retailer1: retailer },
dataType: "json",
success: function (result) {
debugger
alert(result.d);
}
});
return true;
}
}
and this is my c# method
[System.Web.Script.Services.ScriptService]
public partial class CAInvoiceEntry: BaseClass
{
[WebMethod, ScriptMethod()]
public static int ValidateDuplicateEntry(string billtext1, string billdate1, string retailer1)
{
string validatebill = objCAInvoiceEntry.validatebilldate(textBoxBillNumber.Text, billdate1.ToString(), ViewState[AppConstants.UploadedBy].ToString(), dropDownListRetailers.SelectedValue);
if (validatebill == "1")
{
return 1;
}
else
return 0;
}
}
but the web method is not fired.
I have also tried using pagemethods.methodname() as an alternative(by registring the script with enablepagemethods=true) but with no effect.
If someone can guide me on where i am doing it wrong?
Just to be clear..
in the below image you can see the breakpoint execution, where the ajax call gets skipped.

I was facing similar issue today. In my case i had RouteConfig in App_start folder, So i solved my problem by commenting this line
//settings.AutoRedirectMode = RedirectMode.Permanent;
which was the cause of the problem.
also Your web method needs to be public and static.
something like
public static int MethodName()
{
// your method
}

There seems to be as issue with the way you are passing parameters through ajax.
Try this.
if (billtext != '' && retailer != '' && billdate != '')
{
debugger
$.ajax({
type: "POST",
url: "CAInvoiceEntry.aspx/ValidateDuplicateEntry",
data: "{ billtext1:" + "'" + billtext + "'" + ", billdate1:" + "'" + billdate + "'" + ", retailer1:" + "'" + retailer + "'" + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (msg) {
if (msg == "1")
alert("Already exists");
else
alert("valid");
},
error: function (msg) {
debugger;
alert(msg);
}
})
return false;
}

You have a tiny typo in your javascript. Remember that javascript is case-sensitive. You are passing in:
Type: "POST"
But in fact you should be passing in:
type: "POST"
If you use F12 on the Network tab, you will noticed that your current AJAX call is making a GET request, not a POST request.

Related

Page not loading after Postback event completes - ASP.Net

I have a Javascript function on a button click with a POST to a WebMethod. After getting the response back; which is a redirect URL, the code goes to the IsPostBack event of the redirected page but that page never loads. I have written redirects all over the place but somehow this one just stays on the page it is called from.
jQuery.ajax({
type: "POST",
url: "MyProfile.aspx/UpdateProfile_Clicked",
async: false,
data: parms,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (response.d != '') {
alert("Your profile has been updated.");
// response.d = "SubmitRequest.aspx"
var data = response.d;
if (data.indexOf("aspx", 0) > -1) {
redirect(data);
}
}
return false;
},
error: function (httpRequest, textStatus, errorThrown) {
LogAjaxErrorToServer(httpRequest, textStatus, errorThrown, parms, "UpdateProfile_Clicked");
}
});
function redirect(url) {
if (url == "") { return false; }
var indx = window.location.pathname.lastIndexOf('/', 0);
if (indx < 0) { indx = 0; }
var local = window.location.pathname.substr(0, indx);
local += "/" + url;
location.href = local;
return false;
}
So the code does go to the (!IsPostBack) for SubmitRequest.aspx but stays on the Profile.aspx. What am I missing? Thank you in advance for helping me
May

ajax post error: internal error 500 on post method

I am running the script below whe a timer has run out of time, the post was working fine when i started passing the data through that is need for the final information is saved. that when got an internal error.
JavaScript ajax call
var selectedval;
if (document.getElementById('RadioButtonList1_0').checked == true) {
selectedval = document.getElementById('RadioButtonList1_0').value
}
else if (document.getElementById('RadioButtonList1_1').checked == true) {
selectedval = document.getElementById('RadioButtonList1_1').value
}
else if (document.getElementById('RadioButtonList1_1').checked == true) {
selectedval = document.getElementById('RadioButtonList1_1').value
}
else if (document.getElementById('RadioButtonList1_2').checked == true) {
selectedval = document.getElementById('RadioButtonList1_2').value
}
else if (document.getElementById('RadioButtonList1_3').checked == true) {
selectedval = document.getElementById('RadioButtonList1_3').value
}
else {
selectedval = '';
}
var qustNo = document.getElementById('ltlQuestNos').innerHTML;
`enter code here` $.ajax({
type: "GET",
data: '{questNo:'+ qustNo.trim().toString()+',selectedoption:'+ selectedval.toString()+'}',
contentType: "application/json; charset=utf-8",
url: "prTest.aspx/timeFinished",
dataType: "json",
success: function (result) {
// this displays the information so that the page can be re-directed to the results page.
window.location = result.d;
}
Vb.net code.
<WebMethod()>
Public Shared Function timeFinished(questNo As String, selectedoption As String) As String
Dim objExam As New examClass()
If selectedoption = "-1" Then
'lblWarning.Visible = True
'lblWarning.Text = "Please answer Question!"
Else
' lblMessage.Text = "Navigation = " & Request.Form("textNav")
objExam.answerQuestion(HttpContext.Current.Session("examid"), questNo, selectedoption, "00:00:00")
' lblWarning.Visible = False
'close connection
objExam.Dispose()
End If
objExam.finishTest(Convert.ToInt32(HttpContext.Current.Session("examid").ToString()))
objExam.Dispose()
' HttpContext.Current.Response.Redirect("ChapterTestSummary.aspx", true);
Dim url As String = "testsummary.aspx"
Return url
End Function
I think the problem is with data part in ajax. Because, if you are building the data as string by yourself, key and value should enclosed in double quotes. Otherwise make it as an object and use JSON.stringify() method to make it as string.
$.ajax({
type: "GET",
data: JSON.stringify({
questNo: qustNo.trim(),
selectedoption: selectedval
}),
contentType: "application/json; charset=utf-8",
url: "prTest.aspx/timeFinished",
dataType: "json",
success: function(result) {
// this displays the information so that the page can be re-directed to the results page.
window.location = result.d;
}
});

Returning Response in jquery ajax function

Getting problems in Response.d , based on the result which is returning by the checkusers() function I am saving the values. If the entered name is in already in database it should say "User already exists", if it is not in database it should create a new record.
But I am not getting the correct value from (response), I observed that Console.log(response.d) giving me correct values like 'true' or 'false'. I tried everything I know like-
changing async:"false"
var jqXHR = $.ajax({ and returning jqXHR.responseText
But none of they worked for me . Please help me with this.
submitHandler: function (form) {
var txtName = $("#txtName").val();
var txtEmail = $("#txtEmail").val();
var txtSurName = $("#txtSurName").val();
var txtMobile = $("#txtMobile").val();
var txtAddress = $("#txtAddress").val();
var obj = CheckUser();
if (obj == false) {
$.ajax({
type: "POST",
url: location.pathname + "/saveData",
data: "{Name:'" + txtName + "',SurName:'" + txtSurName + "',Email:'" + txtEmail + "',Mobile:'" + txtMobile + "',Address:'" + txtAddress + "'}",
contentType: "application/json; charset=utf-8",
datatype: "jsondata",
async: "true",
success: function (response) {
$(".errMsg ul").remove();
var myObject = eval('(' + response.d + ')');
if (myObject > 0) {
bindData();
$(".errMsg").append("<ul><li>Data saved successfully</li></ul>");
}
else {
$(".errMsg").append("<ul><li>Opppps something went wrong.</li></ul>");
}
$(".errMsg").show("slow");
clear();
},
error: function (response) {
alert(response.status + ' ' + response.statusText);
}
});
}
else {
$(".errMsg").append("<ul><li>User Already Exists </li></ul>");
$(".errMsg").show("slow");
}
}
});
$("#btnSave").click(function () {
$("#form1").submit()
});
});
checkusers function is:
function CheckUser() {
var EmpName = $("#txtName").val();
$.ajax({
type: "POST",
url: location.pathname + "/UserExist",
data: "{Name:'" + EmpName + "'}",
contentType: "application/json; charset=utf-8",
datatype: "jsondata",
async: "true",
success: function (response) {
console.log(response.d);
},
error: function (response) {
alert(response.status + ' ' + response.statusText);
}
});
}
Just because your database returns true or false doesn't mean this also gets returned by your CheckUser().
There are several options here:
Either you make a local variable in your CheckUser, Make your Ajax call synchronous, set the local variable to response.d in the success function and then return that local variable.
Another option is to work with Deferred objects and make your submithandler Ajax call wait for the Checkuser Ajax call to return;
A third option is to call your create ajax call from your success callback in your CheckUser Ajax call if the user isn't created yet.
I would recommend either option 2 or 3, because option 1 is not userfriendly.

asp.net button client side confirmation before submit

I have this problem: I need to validate that files have not been uploaded already, for which I use a webservice with Jquery called by isAlreadyUploaded() which returns true or false. Should the files exists, a confirmation to proceed is asked. THEN, once that is finished, I want to call the Button1_Click function to finish the operation. My problem is tha both of them are being called at the same time, thus avoiding the confirmation.
Maybe I am approaching the problem the wrong way. If so, feel free to correct me.
<asp:Button ID="Button1" runat="server" Text="Upload" onclick="Button1_Click" OnClientClick="return isAlreadyUploaded()" />
<script>
function isAlreadyUploaded() {
var mystring = "";
$.ajax({
type: "POST",
url: "Main.aspx/alreadyUploaded",
data: "{'swfFile':'" + $("#<%=FileUpload2.ClientID%>").val() + "','flvFile':'" + $("#<%=FileUpload3.ClientID%>").val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
mystring = msg.d;
alert(mystring);
if (mystring != "") {
if (confirm(mystring)) {
return true;
} else {
return false;
}
} else {
return true;
}
}
});
}
</script>
It should work if you add the following option:
$.ajax({
/* ... code ...*/
async : false,
/* ... code ...*/
});
You're making an asynchronous request to the server when you need to make a synchronous request.
http://api.jquery.com/jQuery.ajax/
Because ajax is async by nature isAlreadyUploaded will not wait for the server to respond and since you are not returning anything from isAlreadyUploaded it will be treated as true and the button will submit the form.
You can set async property of ajax config to false so that it will wait for the server to respond before leaving from the function.
function isAlreadyUploaded() {
var mystring = "", retVal = false;
$.ajax({
async: false
type: "POST",
url: "Main.aspx/alreadyUploaded",
data: "{'swfFile':'" + $("#<%=FileUpload2.ClientID%>").val() + "','flvFile':'" + $("#<%=FileUpload3.ClientID%>").val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
mystring = msg.d;
alert(mystring);
if (mystring != "") {
if (confirm(mystring)) {
retVal = true;
} else {
retVal= false;
}
} else {
retVal = true;
}
}
});
return retVal;
}
There is an ConfirmButtonExtender in the ajax toolkit which might be what you're looking for.
Here is an example i found:http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/ConfirmButton/ConfirmButton.aspx

Updating jQuery Item during Ajax call

I am making an ajax call to send out a couple of emails when the user clicks a button. I am trying to update a "Please wait..." div before and after the call with the status, as well as report any errors. The problem... is that the div doesn't actually update until the ajax call is complete.
If I comment out the ajax call the status update works fine, but fails if the ajax call takes place. My Windows programming experience tells me the div needs to be refreshed, but I'm not sure how this is done, or if this is the right method.
For example:
$("#msgEmail").show();
$("#msgEmail").html("Preparing to send");
$.ajax({ blah blah blah...
Any pointers in the right direction will be much appreciated!
On nnnnnn's suggestion I started testing on other browsers. The problem occurs on Chrome and Safari, but works as expected on Firefox and SeaMonkey. It sure looks like he's right about this. Now I just need to figure out to implement setTimeout() in this scenario.
Update: Code:
.click(function() {
$('#myTable :checkbox:checked').each(function() {
sId = $(this).attr('cid');
sName = $(this).attr('cname');
ret = true;
$("#msgImage").slideDown();
sUpdate = 'Sending alerts to class: '+ sName;
$("#msgEmail").slideDown();
$("#msgEmail").html(sUpdate);
sSubject = "Notificatiom";
sMessage = $('#message').val();
sData= "cid="+sId+'&sname='+sName+'&subject='+sSubject+'&message='+encodeURIComponent(sMessage);
$.ajax({
url: 'dostuff.php',
data: sData,
dataType: 'text',
type: 'POST',
async: false,
success: function (msg)
{
if(msg >= '1')
{
ret = true;
}
}
});
if(ret)
$("#msgEmail").html('Finished sending alerts');
$("#msgImage").slideUp();
ret = false;
return false;
})
Place your ajax call in the callback for 'slideDown'. Set the message before calling 'slideDown'. This will ensure your message is updated before the ajax call is sent.'
sUpdate = 'Sending alerts to class: ' + sName;
$("#msgEmail").html(sUpdate);
$("#msgEmail").slideDown(function() {
sSubject = "Notificatiom";
sMessage = $('#message').val();
sData = "cid=" + sId + '&sname=' + sName + '&subject=' + sSubject + '&message=' + encodeURIComponent(sMessage);
$.ajax({
url: 'dostuff.php',
data: sData,
dataType: 'text',
type: 'POST',
async: false,
success: function(msg) {
if (msg >= '1') {
ret = true;
}
}
});
});
I ll get you an on hw this stuff is going to be
$(document).ready(function(){
$.ajax({
url :'YOur url',
.....
.....
ajaxSend :function(){
$('#yourdiv').html('please wait...');
}
success:function(msg){
if (msg >= '1') {
$('#yourdiv').html('validated');
}
}
});
}):

Categories

Resources