send ajax form to web service, only after successful validation - asp.net

my target is to create form that validated in the client side, and only when it is valid, send ajax call to asmx web service. i manage to do that two separately: client-side validation and ajax send to web service, and i want to combine this two. how?..
i have this form (i simplify everything for simple example):
<form id="ContactForm" runat="server">
<label for="name">Full Name</label>
<input type="text" name="name" id="name"/>
<input id="submit" type="button" />
</form>
the client validation looks like:
$(document).ready(function() {
$("#submit").click(function() {
var validator = $("#ContactForm").validate({
rules: { name: { required: true } },
messages: { name: errName }
}).form();
});
});
and the ajax send looks like this:
$(document).ready(function() {
$("#submit").click(function() {
var myMailerRequest = {name: $('#name').val()};
var data = JSON.stringify({req: myMailerRequest});
$.ajax
({
type: "POST",
url: "ContactFormMailer.asmx/SendContactForm",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
AjaxSucceeded(msg);
}, error: AjaxFailed
});
});
});
Thanks!

You can use the submitHandler option of .valdiate() for this, it only executes when a valid form is submitted (it has an invalidHandler for the opposite), like this:
$(function() {
$("#submit").click(function() {
var validator = $("#ContactForm").validate({
rules: { name: { required: true } },
messages: { name: errName },
submitHandler: function() {
var myMailerRequest = {name: $('#name').val()};
var data = JSON.stringify({req: myMailerRequest});
$.ajax({
type: "POST",
url: "ContactFormMailer.asmx/SendContactForm",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: AjaxSucceeded,
error: AjaxFailed
});
}
}).form();
});
});
Since you're not using this though, it might be much more readable in 2 functions, like this:
$(function() {
$("#submit").click(function() {
var validator = $("#ContactForm").validate({
rules: { name: { required: true } },
messages: { name: errName },
submitHandler: ajaxSubmit
}).form();
});
function ajaxSubmit() {
var myMailerRequest = {name: $('#name').val()};
var data = JSON.stringify({req: myMailerRequest});
$.ajax({
type: "POST",
url: "ContactFormMailer.asmx/SendContactForm",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: AjaxSucceeded,
error: AjaxFailed
});
}
});
The only other change was shortening your call to AjaxSuceeded (maybe this can't be done, only because of your simplified example), but other than that...just submit the form from the submitHandler callback and you're all set.

Related

Subscribe to specific event in ASP.NET WebHooks

I'm trying to learn ASP.NET WebHooks, but the docs are pretty sparse right now.
What I'm trying to do is subscribe to a specific events. All the samples I can find demonstrate subscribing to all the events, which is not very useful for me.
EDIT:
This is the code for subscribing I found in the docs:
function subscribe() {
$.ajax({
type: "POST",
url: "/api/webhooks/registrations",
data: JSON.stringify({
WebHookUri: "http://localhost:59927/api/webhooks/incoming/custom",
Secret: "12345678901234567890123456789012",
Description: "My first WebHook!"
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data, status) { alert(status); },
failure: function(errMsg) { alert(errMsg); }
});
return false;
}
What should be the code for subscribing to a "BookAdded" event?
Thanks!
So, for anyone else looking for the answer, this is how it should be done:
function subscribe() {
$.ajax({
type: "POST",
url: "/api/webhooks/registrations",
data: JSON.stringify({
WebHookUri: "http://localhost:59927/api/webhooks/incoming/custom",
Secret: "12345678901234567890123456789012",
Description: "My first WebHook!",
Filters: ["BookAdded"]
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data, status) { alert(status); },
failure: function(errMsg) { alert(errMsg); }
});
return false;
}
Note the Filters field added to the ajax statement.

Can't send data with ajax to a asp.net mvc controller

Hello i'm having problems sending data through ajax to my asp.net controller. When i try to view the problem in opera inspector i get server 500 error on jquery line 8720.
xhr.send( ( s.hasContent && s.data ) || null );
Here are my code samples:
Html:
<div class="top-row">
<div class="field-wrap">
<label>
<span class="req"></span>
</label>
<input class="text-center" type="text" required autocomplete="off" name="url" id="url" />
</div>
</div>
<button type="submit" class="button button-block" name="sendIT" id="sendIT">Save</button>
</div>
Javascript:
var button1 = document.getElementById("sendIT");
function LoginButton1OnClick() {
var text = $('#url').val();
alert(text);
$.ajax({
type: 'POST',
url: '/Book/TestBook',
crossDomain: true,
data: text,
success: function () {
alert('success');
}, error: function (data) {
alert("Error");
}
});
}
button1.addEventListener("click", LoginButton1OnClick);
C#:
[HttpPost]enter code here
public ActionResult TestBook(string test)
{
var s1 = test;
return View();
}
you need to post data as object
$.ajax({
type: 'POST',
url: '/Book/TestBook',
crossDomain: true,
data: {test: text},
success: function () {
alert('success');
}, error: function (data) {
alert("Error");
}
});
The error 500 you're getting is because of the malformed 'data' in your ajax POST request. You need to send the data as an object:
Javascript
$.ajax({
type: 'POST',
url: '/Home/TestBook',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({test: text }),
success: function (data) {
alert('success');
}, error: function (data) {
alert("Error");
}
});
Note that the "test" parameter in javascript needs to mach the exact same name in your controller.

How to fill dropdown when its master Dropwnlist change event works on table row

ddlInjuryType and ddlInjurySubType are two dropdown placed in same row that row will dynamically clone to next row on add button click. following code not filling "ddlInjurySubType"
$("#tblSurgery").on('change', 'select.ddlInjuryType', function (event) {
$.ajax({
type: "POST",
url: "Surgery.aspx/FetchInjurySubType",
data: JSON.stringify({ typeId: $(this).val(), locale: 'en-US' }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data.d.length > 0) {
$(this).find(".ddlInjurySubType").empty().append("<option value='0'>--Select Injury Type--</option>").append(data.d);
}
}
});
});
Replace your code with following
$("#tblSurgery").on('change', 'select.ddlInjuryType', function (event) {
event.stopPropagation();
event.stopImmediatePropagation();
var ddlInjuryType = $(this);
$.ajax({
type: "POST",
url: "Surgery.aspx/FetchInjurySubType",
data: JSON.stringify({ typeId: $(ddlInjuryType).val(), locale: 'en-US' }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data.d.length > 0) {
$(ddlInjuryType ).parent().parent().find(".ddlInjurySubType").empty().append("<option value='0'>--Select Injury Type--</option>").append(data.d);
}
}
});
});
I got the answer
$("#tblSurgery").on('change', 'select.ddlInjuryType', function (event) {
var trIndex= $(this).closest('tr').index();
$.ajax({
type: "POST",
url: "Surgery.aspx/FetchInjurySubType",
data: JSON.stringify({ typeId: $(ddlInjuryType).val(), locale: 'en-US' }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data.d.length > 0) {
$("#tblSurgery tr:eq(" + trIndex+1 + ")").closest("tr").find(".ddlInjurySubType").empty().append("<option value='0'>--Select Injury Sub Type--</option>").append(data.d);
}
}
});
});
There is a scope issue in your code, this doesn't refer to the changed element. You should cache the this object outside the success handler:
var _this = this;
Then you can use the cached object in your success handler, or the set the context property to this:
$.ajax({
context: this,
// ...
})

Ajax request with web method

Can someone explain me why this gives me an error?
My ajax call something like this.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(document).ready(function () {
$('#btn1').click(function () {
var values = JSON.stringify({ data: $('#form1').serializeArray() });
alert($('#form1').serializeArray());
$.ajax({
type: "POST",
url: "Default.aspx/Test",
contentType: "application/json; charset=utf-8",
scripts: true,
dataType: "json",
data: values,
success: function (data) { $('#results').append(data.d); },
error: function () { $('#results').append('hata'); }
});
}); });
</script>
</head>
<body>
<form runat="server" id="form1">
First name: <input type="text" name="firstname"><br>
Last name: <input type="text" name="lastname">
<button id="btn1" type="button">bummm</button>
<div id="results"></div>
</form>
</body>
</html>
[WebMethod]
public static string Test (string data)
{
return "İşlem başarılı"+data;
}
It says me {"Message":"Type \u0027System.String\u0027 is not supported for deserialization of an array.","StackTrace":"
I think this happens because you wrong call your webmethod with ajax.
Your webmethod have one parameter named data with type string, but you try send without name, so try change your code like this:
var KaydetDataWithAjax = function (e)
{
var values =JSON.stringify({data: $(e).serializeArray()});
alert(values);
$.ajax({
type: "POST",
dataType: 'json',
contentType: "application/json; charset=utf-8",
url: "Harita.aspx/HaritaKaydet",
scripts: true,
data:values,
success: function (dt) { alert(dt);},
complete:function(){},
error: function () { alert('error'); }
});
};
UPDATE
this method work on new project
$.ajax({
type: "POST",
dataType: 'json',
contentType: "application/json; charset=utf-8",
url: "Harita.aspx/HaritaKaydet",
scripts: true,
data:JSON.stringify({data: 'text'}),
success: function (dt) { alert(dt);},
complete:function(){},
error: function () { alert('error'); }
});
if in your case it not work then possibly helps if you provide little more code
UPDATE 2
turns out it's all simple than i thought!
serializeArray() returns Array! So it find on server method with parameters something like List<object>, so to solve you must stringify array too
so try this code
var KaydetDataWithAjax = function (e)
{
var values =JSON.stringify({data: JSON.stringify($(e).serializeArray())});
alert(values);
$.ajax({
type: "POST",
dataType: 'json',
contentType: "application/json; charset=utf-8",
url: "Harita.aspx/HaritaKaydet",
scripts: true,
data:values,
success: function (dt) { alert(dt);},
complete:function(){},
error: function () { alert('error'); }
});
};

how to send a value to asp textbox from AJAX success function....?

$.ajax({
type: "POST",
url: "ClaretExamSchedule.aspx/LoadFatherInfo",
data: JSON.stringify({ appId: appId }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
**I want to pass the return values here to ASP Textboxes**
}
});
Given the code above, I passed a parameter for codebehind the method LoadFatherInfo, now
I returned an ArrayList and I want every datum to be displayed using textbox.. Sorry for my English but I hope you get my point, any help will be much appreciated. Thanks!
Assuming your text boxes and web method will something similar to the code below:
<input type="text" id="Father1" value="" class="father" />
<input type="text" id="Father2" value="" class="father" />
<input type="text" id="Father3" value="" class="father" />
[WebMethod]
public string[] LoadFatherInfo(appId appId)
{
// Do Stuff
var fatherInfo = new List();
fatherInfo.Add("John");
fatherInfo.Add("Jim");
fatherInfo.Add("Joe");
return fatherInfo.ToArray();
}
you could change your ajax call to something similar to the javascript below:
$.ajax({
type: "POST",
url: "ClaretExamSchedule.aspx/LoadFatherInfo",
data: JSON.stringify({ appId: appId }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: PopulateFatherBoxes,
error: OnError
});
function PopulateFatherBoxes(data, status) {
var i = 0;
$(".father").each(function() {
$(this).val(data.d[i]);
i++;
});
}

Resources