Ajax request with web method - asp.net

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

Related

Ajax with asp.net aspx returns Undefined

I'm facing the following issue: Whenever I click on the button, the alert shows undefined.
Web method:
[WebMethod]
public static string getTest()
{
return "testing success";
}
Ajax script
<script type="text/javascript">
function getTest() {
$.ajax({
type: "POST",
url: "main.aspx/getTest",
data: "{}",
datatype: "json",
contenttype: "/application/json; charset=utf-8",
success: function (msg) {
alert(msg.d);
},
error: function (data) {
}
});
}
</script>
datatype should be dataType and contenttype should be contentType. Also remove / from start of "/application/json; charset=utf-8"
$.ajax({
type: "POST",
url: "main.aspx/getTest",
data: "{}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (msg) {
alert(msg.d);
},
error: function (data) {
}
});
Remove these from your ajax call
datatype: "json",
contenttype: "/application/json; charset=utf-8",
More about these
Differences between contentType and dataType in jQuery ajax function
What is content-type and datatype in an AJAX request?
You can find more details in the jQuery Ajax documentation

Ajax call doesn't work

I try to use ajax call in my aspx page. Here is my script:
<head runat="server">
<title></title>
<script type="text/javascript" src="jquery/ui/jquery-ui-1.8.23.custom.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
url: "WebForm1.aspx/List",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
alert('asd');
}
});
});
</script>
</head>
Here is my server side code:
[WebMethod]
public static string[] List()
{
...
}
I put a break point List's first row but nothing happen. Do you have any suggestion, where I make a mistake?
The parameter you're specifying is json; but where's the json data?? data: '{}', is an object. Also, I'd check the url parameter. Presumably, you'd need to write your call like this:
var AjaxData = '{"ParameterName":""}';
$.ajax({
type: "POST",
url: "../WebForm1.aspx/GetList",
data: AjaxData ,
contentType: "application/json; charset=utf-8",
dataType: "json",....
And then on the server side, you should therefore specify that you're receiving a string, since that's the format of json data. I would also recommend changing the name of the WebMethod because List can be confusing. And finally, you're returning json, therefore you're returning a string and not an array. Server method like this:
[WebMethod]
public string GetList(string ParameterName)
{
...
}

Jquery ajax postback not hitting server method?

This is some of the code on the aspx page with the ajax post:
<div>
Make Comment: <br />
<textarea rows="7" cols="20" id="comment_content"></textarea><br />
<input type="button" id="Make_Comment" value="Make Comment" />
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#Make_Comment").click(function () {
$.ajax({
type: "POST",
url: "Conversation.aspx/AddComment",
data: '{ comment: This is a test comment via ajax postback }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
alert("Got Back to code");
}
});
});
});
</script>
And here is the method I am trying to hit on the server side:
[WebMethod]
public static void AddComment(string data)
{
}
I have placed a breakpoint by the server side method but its not hitting it, what could be the issue?
Couple of things :
your data ina ajax call
data: '{ comment: This is a test comment via ajax postback }'
should be
data: "{'comment':'This is a test comment via ajax postback'}",
And your WebMethod :
AddComment(string data)
Should be
AddComment(string comment)
Try this:
<script type="text/javascript">
$(document).ready(function () {
$("#Make_Comment").click(function () {
var comment = $("#comment_content").val();
var Params = { comment : comment };
$.ajax({
type: "POST",
url: "Conversation.aspx/AddComment",
data: Params,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
alert("Got Back to code");
}
});
});
});
</script>
In your controller set the httppost.
[WebMethod]
[HttpPost]
public static void AddComment(string comment)
{
}

send ajax form to web service, only after successful validation

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.

Why does this JQuery call to asp.net pagemethod load the whole page?

Here is a snippet of my html:
<input id="btnGetDate" type="submit" value="Get Date" />
<div id="Result"></div>
<script type="text/javascript">
$(document).ready(function() {
$("#btnGetDate").click(function() {
$.ajax({
type: "POST",
url: "Date.aspx/GetDate",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#Result").text(msg.d);
}
});
});
});
</script>
My Page Method id defined as follows:
[System.Web.Services.WebMethod]
public static string GetDate()
{
return DateTime.Now.ToString();
}
When I click the Get Date button, I saw the date flash on the screen for a second, but since the whole page is loading, it disappears and when I view it in firebug, I see it is doing the POST, but quickly disappearing. Any ideas on how to resolve this?
Try returning false from your $("#btnGetDate").click() event handler:
$("#btnGetDate").click(function() {
$.ajax({
type: "POST",
url: "Date.aspx/GetDate",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#Result").text(msg.d);
}
});
return false;
});
karim79's solution will do the job in Internet Explorer - but to make sure that it works in Firefox and other browsers as well, you probably want to add an input argument to the click handler that will take the click event, and stop the event.
$("#btnGetDate").click(function(ev) {
ev.stopPropagation();
$.ajax({
type: "POST",
url: "Date.aspx/GetDate",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#Result").text(msg.d);
}
});
return false;
});

Resources