check email id already exists in database when losing focus - javascript

I want to check the entered email id already exists in my database or not. For that I need the Text box lost focus event so that I can call it in update panel trigger asynchronously. whereas in my event I can check whether the entered value exists in database or not.
I tried:
txtEmailId.Attributes.Add("onblur", "javascript:CheckEmailIdIsExist()");
If so, the what should be inside CheckEmailIdIsExist() javascript method? how to check database values asynchronously from javascript function?

look at using jQuery to make an AJAX call to a WebMethod on your site:
function CheckEmailIdIsExist(args) {
var loc = window.location.href;
loc = (loc.substr(loc.length - 1, 1) == "/") ? loc + "default.aspx" : loc;
$.ajax({
type: "POST",
url: loc + "/" + IsUniqueEmailAddress,
data: "{" + args + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: onSuccess,
fail: onFail
});
}
This would be on your server:
[WebMethod]
public static bool IsUniqueEmailAddress(string emailAddress)
{
// do some processing here
return true;
}
I think you will need to modify how you call the JavaScript function because you will need to pass the value of the control onblur="javascript:CheckEmailIdIsExist(this.value);"

Either use a javascript web service proxy, by adding a ServiceReference to your ScriptManager
http://www.semenoff.dk/en/Code-Corner/ASP.Net.AJAX/WebService-From-JavaScript.aspx
Alternatively use JQuery's ajax method:
http://api.jquery.com/jQuery.ajax/
The URL parameter can just be an httphandler, which takes the email address as a querystring parameter, checks the database and returns a result

Well, you should create an XMLRequest to some script which should reside on the server-side. The script itself should return some value and based on it you can make a decision whether the "emailId" exists within your database or not.
Note, that the XMLRequest is the method used for ajax calls. From this point I think you should read about ajax. If you use some library (ex jQuery) it might have it built in, so it will be very easy and straight forward for you to make some working implementation and verify your data :)

Related

JQuery - Send inputs via ajax (which were obtained by ajax)

I have an application that after performing a search, returns me multiple "fieldsets" with some hidden inputs (via AJAX!).
I want to use these inputs to send information to the server (again) via AJAX.
The names of these inputs are automatically listed with a prefix:
"video_url_1", "video_url_2", etc.
When the user clicks the button, the value of "video_url_1" or "video_url_2" will be sent via AJAX depending on the button to which it has clicked. To solve this I got the name of the button that was clicked and then I cut the name so that I only have one number, this number I put in a variable and then use it in the "data" section of AJAX.
I did the test by sending a locally stored input and it worked but when trying to send the inputs that were previously obtained by an ajax, it does not work.
What can be wrong? This is my code:
$(document).ajaxComplete(function(){
$('a.report_video').click(function() {
var idbutton = $(this).attr('id');
var idreport = idbutton.replace('report_video_', '');
//I'm still not using these variables, can they be used to pass the input data to ajax?
var videourl = $("#video_url_" + idreport).val();
var videoid = $("#video_id_" + idreport).val();
var videoserver = $("#server").val();
///////////
$.ajax({
type : 'POST',
url : 'https://example.com/script/script.php',
data : $($("#video_url_" + idreport)).serialize(), //It doesn't work
//For example, data: $("#server").serialize()
//Work fine, this input is stored locally.
beforeSend: function(){
$('#video_report_' + idreport).html('<img src="'+pluginUrl+'./assets/img/loading.svg" />');
}
}).done(function(data) {
$('#video_report_' + idreport).html(data);
});
return false;
});
});
Edit:
I just did some tests as suggested by Kevin B and I see that the problem I have is in the syntax when trying to send two dynamic ID's by Ajax.
The problem is that I do not know how to write them correctly, I know that is the problem because when I tried to send them separately they did work...
data : $($("#video_id_" + idreport), $("#video_url_" + idreport)).serialize(),
I'm not sure I completely understand your problem, but this might help.
You call your second AJAX call in the .success() method of the first AJAX call. Essentially chaining the responses.
$('#btn').click(function() {
$.ajax({
type: "POST",
url: 'someURL',
data: someData
}).done(function(firstCallData) {
// This OPTIONAL method fires when the AJAC call succeeded
// You can also put another AJAX call in here with the data returned from the first call
$.ajax({
type: "POST",
url: 'someURL',
data: firstCallData
}).done(function(data) {
// Do something with second AJAX call with data
}).fail(function(data) {
// Second AJAX call failed, handle error
});
}).fail(function(data) {
// This OPTIONAL method fires when the first response failed
}).always(function(data) {
// This OPTIONAL method fires regardless if the first call succeeded or failed.
});
});

AJAX call to server side function in javascript?

I'm new to AJAX and I'm not too clear about how to use the format of the AJAX call
ex
$.ajax({
type: "POST",
url: "Default.aspx/function",
data: '{ searchBy: id }',
contentType: "application/json; charset=utf-8"
}).success(function (result) {
alert(result);
})
I have a function in the .cs file that should take in a string ID and return a list of all the objects that contain that ID.
I want to call this function in the javascript to check that the returned list is null (therefore the ID does not already exist) before inserting new objects into the database.
How could I go about doing this?
All the examples I see return a string from the server side function.
If you have control of the server-side endpoint, then return whatever you want to indicate no matches - an empty list, null, empty string, etc. Then in the success function check for that.
Note the dataType ajax parameter. That tells the ajax function how to format the response for you to consume. If you are expecting JSON to be returned, use dataType: json and in the success function check for an empty json array result.length === 0. In the case of null or empty string, use a dataType: text and check for result == "null" or result == "". Etc.
If you don't have control of server side then you will need to conform to whatever data it sends back to you. The dataType is still the key though.
[WebMethod]
public static int function(int Id)
{
return Id;
}
If you need use only ajax, the best option is XMLHttpRequest, is Vanilla JS and more fast.
If you decide use ajax with jquery the function is:
$.ajax({
type: "POST",
url: "Default.aspx/function",
data: { searchBy: id },
dataType: 'json',
success: function(result) {
// Do something
}
});
I've never done C#, but your url parameter must be a path to a file (e.g. url: Default.aspx). In your file, you should have the logic to handle the request and call the right function. This function will check the DB, and will print the result.
// inside Default.aspx
// 1- is there a POST parameter? If so, call foo()
public static string foo(string postParam) {
// check DB, process
Print(result)
}
Inside your success callback, check if null:
.then(function(result) {
if (result === null) // do stuff
})

Web Service method name is not valid

I get the following error "Web Service method name is not valid" when i try to call webmethod from javascript
System.InvalidOperationException: SaveBOAT Web Service method name is not valid.
at System.Web.Services.Protocols.HttpServerProtocol.Initialize()
at System.Web.Services.Protocols.ServerProtocol.SetContext(Type type, HttpContext context, HttpRequest request, HttpResponse response)
at System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type, HttpContext context, HttpRequest request, HttpResponse response, Boolean& abortProcessing)
HTML Code :
<asp:LinkButton runat="server" ID="lnkAddBoat" OnClientClick="javascript:AddMyBoat(); return false;"></asp:LinkButton>
JS Code :
function AddMyBoat() {
var b = document.getElementById('HdnControlId').value;
jQuery.ajax({
type: "GET",
url: "/AllService.asmx/SaveBOAT",
data: { Pid: b },
contentType: "application/text",
dataType: "text",
success: function(dd) {
alert('Success' + dd);
},
error: function(dd) {
alert('There is error' + dd.responseText);
}
});
}
C# Code (Web method in AllService.asmx file)
[WebMethod]
public static string SaveBOAT(int Pid)
{
// My Code is here
//I can put anythng here
SessionManager.MemberID = Pid;
return "";
}
I tried all solutions found on Stack Overflow and ASP.NET site.but none of them worked for me.
It was a silly mistake.
remove Static keyword from method declaration.
[WebMethod]
public string SaveBOAT(string Pid)
{
SessionManager.MemberID = Pid;
return "";
}
In my case I had copied another asmx file, but not changed the class property to the name of the new class in the asmx file itself (Right click on asmx file -> View Markup)
In my case the error was that the Web Service method was declared "private" instead of "public"
Try using this, I think datatype should be JSON
jQuery.ajax({
type: "POST", // or GET
url: "/AllService.asmx/SaveBOAT",
data: { Pid: b },
contentType: "application/json; charset=utf-8",
dataType: "json"
success: function(dd) {
alert('Success' + dd);
},
error: function(dd) {
alert('There is error' + dd.responseText);
}
});
And in C# Code change Pid to string
[WebMethod]
public static string SaveBOAT(string Pid)
{
SessionManager.MemberID = Pid;
return "";
}
I too faced the similar issue. The solution includes checking everything related to ensuring all name, parameters are passed correctly as many have responded. Make sure that the web method name that we are calling in UI page is spelled correctly, the data, data types are correct and etc. In my case, I misspelled the web method name in my ajax call. It works fine once I found and corrected the name correctly.
For Ex: In .asmx class file, this is the method name "IsLeaseMentorExistWithTheSameName" but when I called from UI this is how I called:
var varURL = <%=Page.ResolveUrl("~/Main/BuildCriteria.asmx") %> + '/IsLeaseMentorExistWithSameName';
Notice that the word "The" is missing. That was a mistake and I corrected and so it worked fine.
As Sundar Rajan states, check the parameters are also correct. My instance of this error was because I had failed to pass any parameters (as a body in a POST request) and the asmx web method was expecting a named parameter, because of this the binding logic failed to match up the request to the method name, even though the name itself is actually correct.
[WebMethod]
public object MyWebMethod(object parameter)
If there is no parameter in the body of the request then you will get this error.
Did U add ServiceReference Class. Check this once. Based on your comment I can tell what to do
I had this issue because my soap method had a List<string> parameter. Couldn't figure out a way to make it work with the array parameter; so just converted the parameter to a &-delimited string (e.g. val1&val2&val3) and converted the parameter to an array in the service method.
In my case, one of the WebService receiving parameters was called aId. When I called it from javascript, I was sending the correct Id value, but the name of the sent variable was incorrectly called bId. So I just had to rename the WebService call, keep the correct value like before, and just change the variable name.

How to pass page or master page object to AJAX page method

I wrote a page Page method in my aspx page. in web service method I need to call FindControl method return textbox and get text box value. But my findControl will take MasterPage object to iterate.
Please see my code
<script type = "text/javascript">
function ShowCurrentDateTime() {
$.ajax({
type: "POST",
url: "HRDefault.aspx/GetDate",
data: '',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function(response) {
alert(response.d);
}
});
}
function OnSuccess(response) { }
</script>
<System.Web.Services.WebMethod()> _
Public Shared Function GetDate() As String
Dim txt22_2 As TextBox = CType(RenderControls.FindControlRecursive
(Page.Master, "txt22_2"), TextBox)
Dim str As String
str = txt22_2.Text
Return String.Empty
End Function
But I am getting compiler error when use Page.Master:
Reference to non-shared member requires an object reference
How to pass Master Page object or Page to Page method?. So I can use in Sared method.
Is there any way I can access Textbox value directly in Page method? I need access couple of controls in Page Method.
don't know about $.ajax, but this works fine for me:
<asp:ScriptManager runat="server" EnablePageMethods="true" />
<!-- ...................... -->
<script type="text/javascript">
function ShowCurrentDateTime() {
x = document.getElementById('<%= TextBox1.ClientID %>').value;
PageMethods.GetDate(x, OnSuccess, OnFailure);
}
function OnSuccess(response) {
alert(response);
}
function OnFailure(response) {
alert(response._message);
}
</script>
and in code behind:
<System.Web.Services.WebMethod()> _
Public Shared Function GetDate(x as String) As String
' do something with x
' u can add more params if you need
Return String.Empty
End Function
hope the syntax is ok, i don't remember much of vb :P
HttpContext.Current.Handler may get you the reference to page object but it will not be useful because page life cycle is not executed in PageMethods (so no view-state or request data). You have couple of alternatives:
Pick control values from java-script. If needed, pass them to PageMethod using data parameter while making service call.
Use Session (HttpContext.Current.Session) or cache to store data on page and then retrieve it in PageMethod. I will prefer using cache with new guid as a key and then pass guid to PageMethod.
Since you're already posting data, you should be able to get reference to Request.Form collection which you can use to read posted textbox values

jQuery - can I "append" an additional parameter to every get/post request made

I would like to extend jQuery such that every post/get request made on the client side will have an additional parameter sent (always the same key : value). I need this to detect on the client side if the request was made through jQuery, since I have several js libs at work. The additional param is simply jquery : true. A typical request will normally look like this:
jQuery.post('/users/save', { name : 'john', age : 24 }, ....)
Is there a way to append this addition parameter by extending jQuery or some other way such that it'll look like so when it reaches the server:
{ name : 'john', age : 24, jquery : true }
Basically I want to intercept the request and edit it's parameters before they reach the server side. thanks.
Look at beforeSend(XMLHttpRequest)
A pre-callback to modify the
XMLHttpRequest object before it is
sent. Use this to set custom headers
etc. The XMLHttpRequest is passed as
the only argument. This is an Ajax
Event. You may return false in
function to cancel the request
You should be able to use it with ajaxSetup
Try putting the following somewhere in your code before any AJAX request would be executed:
$.ajaxSetup({
beforeSend: function(xhr) {
var newUrl = this.url;
if (newUrl.indexOf("?") != -1) {
newUrl = newUrl + '&jquery=true';
} else {
newUrl = newUrl + '?jquery=true';
}
xhr.open(this.type, newUrl, this.async);
}
});
This will trigger a function before the sending of any AJAX request. The function determines what the new URL should be (based on whether or not any query string has already been attached), then reopens the XMLHttpRequest with the 'jquery=true' attached at the end.
Here's a working demo of this: http://jsfiddle.net/uz9zg/

Categories