JQuery AJAX method executes both "success" and "failure" - c#

I have an AJAX method to tell the user whether or not an email is available when registering.
$('#mainArea_txtEmail').keyup(function (e) {
var inputemail = $(this).val();
if (inputemail.length > 5)
{
$.ajax({
type: "POST",
url: "Default.aspx/isEmailAvailable",
data: '{email: "' + inputemail + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: alert("available"),
failure: alert("unavailable")
});
}
});
When a user types in an email, whether it is available or not, the browser displays the success alert and then the failure alert every time.
Here is the C# method:
[System.Web.Services.WebMethod]
public static string isEmailAvailable(string email)
{
BasePage page = new BasePage();
string returnvalue;
if (page.db.UserGet(email) == null)
{
returnvalue = "true";
}
else
{
returnvalue = "false";
}
return returnvalue;
}
The db.UserGet method will try and find a database record of a user with the email address matching the email parameter. If there is one, then a User class instance is populated and page.db.UserGet is not null, meaning the email is taken. If it is still null, then no user with that email was found and the email is available.
What am I doing wrong here?
I was following this tutorial (http://www.c-sharpcorner.com/UploadFile/20abe2/how-to-check-user-name-or-email-availability-using-Asp-Net)

Your syntax won't work, you can't use alert as the callback function. alert needs to be wrapped in a proper function or it will fire immediately
$.ajax({
type: "POST",
url: "Default.aspx/isEmailAvailable",
data: '{email: "' + inputemail + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(serverResponse) {
alert("available");
/* do something with serverResponse */
},
failure: function() { alert("available"); }
});
$.ajax API Reference

Related

webmethod isn't catching ajax POST

I'm trying to call a server side method with ajax. This is what I've got:
Client side:
function accept(thisButton) {
$.ajax({
type: "POST",
url: "Default.aspx/editMaxUsers",
data: '{param: "' + $(thisButton).prev().val() + '" }',
contentType: "application/json: charset=utf-8",
dataType: "json",
success: function (result) { alert("successful" + result.d); }
});
}
Server side:
[System.Web.Services.WebMethod]
public static string editMaxUsers(string maxUsers)
{
return maxUsers; //I also have a breakpoint here that isn't stopping the execute
}
When I check the calls with firebug I can see that the POST is being sent and looks fine. But Nothing seems to be happening on server side. What am I doing wrong?
EDIT: Don't know if it's relevant, but the url already contains some parameters. I've tried the following url: "Default.aspx/" + window.location.search + "editMaxUsers" but no success.
The parameters of your WebMethod need to match the parameter name you are passing in.
Change
data: '{param: "' + $(thisButton).prev().val() + '" }',
to
data: '{maxUsers: "' + $(thisButton).prev().val() + '" }',
1.Go to App_Start/RouteConfig and change
settings.AutoRedirectMode = RedirectMode.Permanent;
to
settings.AutoRedirectMode = RedirectMode.Off;
2.As #F11 said the paramter in the WebMethod and the key in the json object should be with the same name and what I strongly recommend is not to build json object manually. It is better to do:
function accept(thisButton) {
var data = {};
data.maxUsers = $(thisButton).prev().val();
$.ajax({
type: "POST",
url: "Default.aspx/editMaxUsers",
data: JSON.stringify(data),
contentType: "application/json: charset=utf-8",
dataType: "json",
success: function (result) { alert("successful" + result.d); }
});
}

How to call webmethod in Asp.net C#

I want to call a web method in asp.net c# application using the following code
Jquery:
jQuery.ajax({
url: 'AddToCart.aspx/AddTo_Cart',
type: "POST",
data: "{'quantity' : " + total_qty + ",'itemId':" + itemId + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function () {
alert("Start!!! ");
},
success: function (data) {
alert("a");
},
failure: function (msg) { alert("Sorry!!! "); }
});
C# Code:
[System.Web.Services.WebMethod]
public static string AddTo_Cart(int quantity, int itemId)
{
SpiritsShared.ShoppingCart.AddItem(itemId, quantity);
return "Add";
}
But it always call page_load. How can i fix it?
There are quite a few elements of the $.Ajax() that can cause issues if they are not defined correctly. I would suggest rewritting your javascript in its most basic form, you will most likely find that it works fine.
Script example:
$.ajax({
type: "POST",
url: '/Default.aspx/TestMethod',
data: '{message: "HAI" }',
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log(data);
},
failure: function (response) {
alert(response.d);
}
});
WebMethod example:
[WebMethod]
public static string TestMethod(string message)
{
return "The message" + message;
}
This is a bit late, but I just stumbled on this problem, trying to resolve my own problem of this kind. I then realized that I had this line in the ajax post wrong:
data: "{'quantity' : " + total_qty + ",'itemId':" + itemId + "}",
It should be:
data: "{quantity : '" + total_qty + "',itemId: '" + itemId + "'}",
As well as the WebMethod to:
public static string AddTo_Cart(string quantity, string itemId)
And this resolved my problem.
Hope it may be of help to someone else as well.
Necro'ing this Question ;)
You need to change the data being sent as Stringified JSON, that way you can modularize the Ajax call into a single supportable function.
First Step: Extract data construction
/***
* This helper is used to call WebMethods from the page WebMethods.aspx
*
* #method - String value; the name of the Web Method to execute
* #data - JSON Object; the JSON structure data to pass, it will be Stringified
* before sending
* #beforeSend - Function(xhr, sett)
* #success - Function(data, status, xhr)
* #error - Function(xhr, status, err)
*/
function AddToCartAjax(method, data, beforeSend, success, error) {
$.ajax({
url: 'AddToCart.aspx/', + method,
data: JSON.stringify(data),
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
beforeSend: beforeSend,
success: success,
error: error
})
}
Second Step: Generalize WebMethod
[WebMethod]
public static string AddTo_Cart ( object items ) {
var js = new JavaScriptSerializer();
var json = js.ConvertToType<Dictionary<string , int>>( items );
SpiritsShared.ShoppingCart.AddItem(json["itemId"], json["quantity"]);
return "Add";
}
Third Step: Call it where you need it
This can be called just about anywhere, JS-file, HTML-file, or Server-side construction.
var items = { "quantity": total_qty, "itemId": itemId };
AddToCartAjax("AddTo_Cart", items,
function (xhr, sett) { // #beforeSend
alert("Start!!!");
}, function (data, status, xhr) { // #success
alert("a");
}, function(xhr, status, err){ // #error
alert("Sorry!!!");
});
One problem here is that your method expects int values while you are passing string from ajax call. Try to change it to string and parse inside the webmethod if necessary :
[System.Web.Services.WebMethod]
public static string AddTo_Cart(string quantity, string itemId)
{
//parse parameters here
SpiritsShared.ShoppingCart.AddItem(itemId, quantity);
return "Add";
}
Edit : or Pass int parameters from ajax call.
I'm not sure why that isn't working, It works fine on my test. But here is an alternative technique that might help.
Instead of calling the method in the AJAX url, just use the page .aspx url, and add the method as a parameter in the data object. Then when it calls page_load, your data will be in the Request.Form variable.
jQuery
jQuery.ajax({
url: 'AddToCart.aspx',
type: "POST",
data: {
method: 'AddTo_Cart', quantity: total_qty, itemId: itemId
},
dataType: "json",
beforeSend: function () {
alert("Start!!! ");
},
success: function (data) {
alert("a");
},
failure: function (msg) { alert("Sorry!!! "); }
});
C# Page Load:
if (!Page.IsPostBack)
{
if (Request.Form["method"] == "AddTo_Cart")
{
int q, id;
int.TryParse(Request.Form["quantity"], out q);
int.TryParse(Request.Form["itemId"], out id);
AddTo_Cart(q,id);
}
}
The problem is at [System.Web.Services.WebMethod], add [WebMethod(EnableSession = false)] and you could get rid of page life cycle, by default EnableSession is true in Page and making page to come in life though life cycle events..
Please refer below page for more details
http://msdn.microsoft.com/en-us/library/system.web.configuration.pagessection.enablesessionstate.aspx
you need to JSON.stringify the data parameter before sending it.
Here is your answer.
use
jquery.json-2.2.min.js
and
jquery-1.8.3.min.js
Javascript :
function CallAddToCart(eitemId, equantity) {
var itemId = Number(eitemId);
var quantity = equantity;
var dataValue = "{itemId:'" + itemId+ "', quantity :'"+ quantity "'}" ;
$.ajax({
url: "AddToCart.aspx/AddTo_Cart",
type: "POST",
dataType: "json",
data: dataValue,
contentType: "application/json; charset=utf-8",
success: function (msg) {
alert("Success");
},
error: function () { alert(arguments[2]); }
});
}
and your C# web method should be
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string AddTo_Cart(int itemId, string quantity)
{
SpiritsShared.ShoppingCart.AddItem(itemId, quantity);
return "Item Added Successfully";
}
From any of the button click or any other html control event you can call to the javascript method with the parameter which in turn calls to the webmethod to get the value in json format.

Ajax call not working

I am making an ajax call to C# function but it is not being call.
This is ajax call:
$('#button1 button').click(function () {
var username = "username_declared";
var firstname = "firstname_declared";
$.ajax({
type: "GET",
url: "practiced_final.aspx/ServerSideMethod",
data:{username1:username,firstname1:firstname},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$('#myDiv').text(msg.d);
},
error: function (a, b, c) {
alert(a + b + c);
}
});
return false;
});
This is C# code:
[WebMethod]
public static string ServerSideMethod(string username1, string firstname1)
{
return "Message from server with parameter." + username1 + "hello" + firstname1;
}
This method is not getting hit and shows a error message like this:
object XMLHttpRequest]parsererrorundefined
Any help will be highly appreciated.
$('#button1 button').live('click', function () {
var username = "username_declared";
var firstname = "firstname_declared";
$.ajax({
url: "/practiced_final.aspx/ServerSideMethod", type: "GET", dataType: "json",
data: JSON.stringify({ username1: username, firstname1: firstname }),
contentType: "application/json; charset=utf-8",
success: function (msg) {
$('#myDiv').text(msg.d);
},
error: function (a, b, c) {
alert(a + b + c);
}
});
});
$('button#button1') or $('#button1') or $('#button1 button')
check u selector also. put one alert message inside click event and see
Finally it is working.This is the final code.
Thanks everyone for your wise replies.
$.ajax({
type: "POST",
url: "practiced_final.aspx/hello_print",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (msg) {
$('#myDiv').text(msg.d);
}
})
return false;
Enjoy.
In your code I can see : dataType: "json",
But you're not sending a Json through your C# function... When you're telling ajax that the dataType is a json, it will JSON.parse() the response. Maybe that's where the failure is.
Try changing the dataType, or removing it (jQuery will try to guess it).
Please Change below line in Jquery function.
data:{username1:username,firstname1:firstname},
to
data:"{'username1':'" + username + "','firstname1':'" + firstname + "'}",
Hope this will help you.
$('button#button1') //Or check selector put one alert inside onclick
$('#button1').live('click', function () {
var username = "username_declared";
var firstname = "firstname_declared";
$.ajax({
type: "GET",
url: "practiced_final.aspx/ServerSideMethod",
data: JSON.stringify({ username1: username, firstname1: firstname }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$('#myDiv').text(msg.d);
},
error: function (a, b, c) {
alert(a + b + c);
}
})
return false;
it may help
Try changing this line:
data:{username1:username,firstname1:firstname},
to
data:JSON.stringify({username1:username,firstname1:firstname}),
Edit:
I'm not sure if this is the cause of the problem, but this is one thing I noticed different between our jQuery ajax calls. Also, changed result string to reflect #dana's criticism in the comments of my answer.

Redirect after an ajax request in a click event

I'm using JScript + ASP.NET. I got a form with 2 inputs (user and password) and a button. What I'm trying to do is to:
1- Fire a click event
2- Look inside a database if the user exist
3- Give back the answer
4- If the answer is true, POST some data to an other page AND redirect to it.
I first tried to do this with ASP.NET. To POST data with ASP.NET I need to use PostBackUrl property, but the problem is that PostBackUrl ignore my click event.
I then tried to do this with jscript. On my click event (jquery), I use $.ajax to POST data to access my database, give the answer back in json...and I'm stuck there. In both method, I'm stuck at point 4.
ASP.NET
protected void SignIn_OnClick(object sender, EventArgs e)
{
Clients client = (Clients)clientDAO.getUsername(text1.Text, password2.Text);
if (client != null)
{
Session.Add("SessionNoClient", "1272");
Session.Add("CurrentQuote", "-1");
Session.Add("UnitSystem", "0");
Session.Add("SessionAdministrator", "0");
//How to redirect with POST here
}
}
JScript:
$("#m_bLogin").click(function () {
var username = $("#text1").val();
var password = $("#password2").val();
var form = $("#formClient");
$.ajax({
url: '../../Class/LoginAjax.asmx/GetLoginInformation',
data: "{ 'Name':'" + username + "','Password':'" + $("#password2").val() + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
//My Json returns {"'Name':'Bob','Password':'1234'} and I'm not able to access Name or Password property. I tried data.d, data.d.Name, eval(data.d.Name) etc...
form.submit();
},
error: function (XMLHttpRequest, textStatus, error) {
alert(error);
}
});
});
You could do something like that:
$.ajax({
url: '../../Class/LoginAjax.asmx/GetLoginInformation',
data: "{ 'Name':'" + username + "','Password':'" + $("#password2").val() + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
//My Json returns {"'Name':'Bob','Password':'1234'} and I'm not able to access Name or Password property. I tried data.d, data.d.Name, eval(data.d.Name) etc...
form.submit();
},
error: function (XMLHttpRequest, textStatus, error) {
alert(error);
}
}).done(function() {
window.location.href = "YourNewPage.aspx";
});

Calling handler from jQuery doesn't work

I need to call a handler (ashx) file from jQuery to fetch some data at runtime.
My jQuery function looks like:
var pID = 3;
var tID = 6;
$("#Button1").click(function() {
var urlToHandler = "Controller/TestHandler.ashx";
$.ajax({
type: "POST",
url: urlToHandler,
data: "{'pID':'" + pID + "', 'tID':'" + tID + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg);
}
});
});
My handler code:
<%# WebHandler Language="C#" Class="TestHandler" %>
using System;
using System.Web;
public class TestHandler : IHttpHandler
{
public void ProcessRequest (HttpContext context)
{
String pID = context.Request.Params["pID"];
String tID = context.Request.Params["tID"];
context.Response.ContentType = "text/plain";
context.Response.Write(pID + " " + tID);
}
public bool IsReusable
{
get {
return false;
}
}
}
The problem is the code execution doesn't reach to the handler code.
I can call other web forms (aspx) files from the same jQuery function from the same directory, where the handler file is residing. So it isn't any path issue.
I am new to this handler file concept. I googled a lot but couldn't find anything wrong in my code.
It worked after changing the way I was passing the json data (as suggested by #DRAKO) and removing the contentType from the ajax post back call. Also corrected the path.
$("#Button1").click(function() {
var urlToHandler = "TestHandler.ashx";
$.ajax({
type: "POST",
url: urlToHandler,
data: { pID: pID, tID: tID },
dataType: "json",
success: function(msg) {
//do something with the msg here...
}
});
});
I think the way you are passing the json data to the handler is incorrect.
Also make sure the path to the handler is correct and write a line to the console in the handler to check if it is getting called. Try this code out
$("#Button1").click(function(){
$.ajax({
type: "POST",
url: "/Controller/TestHandler.ashx",
data: {pID:pID, tID:tID},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg);
},
error: function(){
alert("Error");
}
});
});

Categories

Resources