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)
{
}
Related
It's not a working properly anchor tag in the success function of ajax in jquery. Button clicked but not perform action.
<script>
$(document).ready(function () {
$.ajax({
type: "GET",
url: "#Url.Action("Action", "Controller")",
dataType: "json",
success: function (data) {
$.each(data.models, function (index, value) {
$('#Teacher_table tbody').append("<tr><td> <a asp-action='Action_name' asp-route-id="+value.Id +">Edit</a></td></tr>");
});
}
});
});
I find the solution to this problem.
asp-action is not work in success function in asp.net MVC core. So use this code
<script>
$(document).ready(function () {
$.ajax({
type: "GET",
url: "#Url.Action("Action", "Controller")",
dataType: "json",
success: function (data) {
$.each(data.models, function (index, value) {
$('#Teacher_table tbody').append("<tr><td><a href='/Controller/Action?id=" + Id + "'>Anchor Name</a></td></tr>");
});
}
});
});
I run into a little bit of a problem executing `AJAX request.
When specifying contentType and dataType, success section is not executing.
However, when omitting that, it is executing, but is showing the entire content of generated html page.
Here is my AJAX call:
$.ajax({
type: "POST",
url: "Default.aspx/GeneratePdfs",
data: '{frequency: "' + $('#ddlFrequency option:selected').text() + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$('#rptDisplay').text(data);
alert("1");
},
failure: function () {
// $('#rptDisplay').text("Error");
alert("2");
}
});
This is code behind:
[System.Web.Services.WebMethod]
public static void GeneratePdfs(string frequency)
{
string test = frequency;
HttpResponse response = HttpContext.Current.Response;
response.Write(test);
}
This is the fragment of html page:
<div id="rptDisplay" class="well" runat="server" clientidmode="Static">
</div>
I need to display data returned from Web Method in my div section.
What am I doing wrong?
Hope this will help you:
contentType :When sending data to the server.
dataType: The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response .
Please find the code:
[System.Web.Services.WebMethod]
public static string GeneratePdfs(string frequency)
{
string test = "frequency";//Hard Code value
HttpResponse response = HttpContext.Current.Response;
return test;
}
Design:
<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
<div id="rptDisplay" class="well" runat="server" clientidmode="Static">
</div>
<script src="Scripts/jquery-1.7.1.min.js"></script>
<script src="Scripts/jquery-ui-1.8.20.min.js"></script>
<script type="text/javascript">
$.ajax({
type: "POST",
url: "Default.aspx/GeneratePdfs",
data: '{frequency: "' + $('#ddlFrequency option:selected').text() + '" }',
contentType: "application/json;charset=utf-8",
// dataType: "text/Json",
success: function (data) {
debugger;
if (data.d!="") {
$('#rptDisplay').text(data.d);
}
alert("1");
},
failure: function () {
// $('#rptDisplay').text("Error");
alert("2");
}
});
</script>
I cannot get a simple ajax example to work from an html page inside my visual studio project. It works fine from a webform (aspx):
...
webform1.aspx and form1.html
...
function ShowCurrentTime() {
alert("before json");
$.ajax({
type: "POST",
url: "json.aspx/GetCurrentTime",
data: "{name: bob }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
alert("after json");
}
function OnSuccess(response) {
alert(response.d);
}
...
webform1.aspx and form1.html
...
<input id="btnGetTime" type="button" value="Show Current Time"
onclick="ShowCurrentTime()" />
...
json.aspx
...
[WebMethod]
public static string GetCurrentTime(string name)
{
return "Hello " + name + Environment.NewLine + "The Current Time is: "
+ DateTime.Now.ToString();
}
If I put the code in webform1.aspx, it works fine. If I put it on form1.html, nothing comes back from json.aspx. I am running the project in debug mode from my machine using vs2013. Any help would be appreciated.
Update #1
I checked fiddler and the server is returning the following result (500):
{"Message":"Invalid JSON primitive: bob.","StackTrace":" at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject()\r\n at ...
Your json is malformed. Strings need to be in quotes. Put bob in quotes and you should be good. I'm unsure why it's working on the ASP.NET page though, unless it has the quotes there.
function ShowCurrentTime() {
alert("before json");
$.ajax({
type: "POST",
url: "json.aspx/GetCurrentTime",
data: "{name: \"bob\" }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
alert("after json");
}
function OnSuccess(response) {
alert(response.d);
}
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'); }
});
};
I just copied some code from an asp.net mvc 2 app which works. Now i am trying it in asp.net mvc 3 and it does not call the save method on the controller?
controller:
[HttpPost]
public JsonResult save(string inputdata)
{
return Json(new { Result = string.Format("From the controller - you have clicked the GO-button ! ") }, JsonRequestBehavior.AllowGet);
}
view:
<button id="but">go</button>
<div id=result></div>
<script type="text/javascript">
$(document).ready(
$("#but").click(
function () {
$.ajax({
url: "/Home/save",
dataType: "json",
type: 'POST',
data: "test",
success: function (result) {
$("#result").html(result.Result);
}
});
}
)
);
</script>
You are not passing the data correctly. The action argument is called inputdata. So you should use this same name in the data hash of the AJAX request:
$.ajax({
url: '/Home/save',
dataType: 'json',
type: 'POST',
data: { inputdata: 'test' },
success: function (result) {
$('#result').html(result.Result);
}
});
Also never hardcode urls in your javascript, always use url helpers or your application will simply stop working when you deploy due to the possibility of having a virtual directory name:
$.ajax({
url: '#Url.Action("save", "home")',
dataType: 'json',
type: 'POST',
data: { inputdata: 'test' },
success: function (result) {
$('#result').html(result.Result);
}
});
Another issue that you have with your code is that you are not canceling the default action of the button meaning that if this is an action link or a submit button the AJAX request might never have the time to execute before the browser redirects.
Also you don't need to specify the dataType to JSON as jQuery is intelligent enough to deduce this from the Content-Type response header sent from the server.
So the final version should look something along the lines of:
<script type="text/javascript">
$(function() {
$('#but').click(function () {
$.ajax({
url: '#Url.Action("save", "home")',
type: 'POST',
data: { inputdata: 'test' },
success: function (result) {
$('#result').html(result.Result);
}
});
return false;
});
});
</script>