Jquery AJAX doesn't call a code behind method - asp.net

I am trying to invoke method from code behind via jquery.ajax... but nothing happens, no error's just methood is not invoked.
Maybe important to note I use DotNetNuke.
jQuery(document).ready(function () {
jQuery(window).scroll(function () {
if (jQuery(window).scrollTop() == jQuery(document).height() - jQuery(window).height()) {
InfiniteScroll();
}
});
function InfiniteScroll() {
jQuery.ajax({
type: "POST",
url: "LoadItemsHandler.aspx/GetData",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data != "") {
alert('comething happened! :)');
}
}
})
};
I have tried to add handler method to .ascx and .aspx but none works:
[WebMethod]
public static string GetData()
{
return "<div><h2>I am comming in peace from code behind.</h2><p>Lorem ipsum dolor sit amet ... :)</p></div>";
...
I have tried to put alert() in InfiniteScroll() and it's invoked on scrolling, but background method... nothing :(
UPDATE 1
public string Test(string input)
{
var serializer = new JavaScriptSerializer();
return serializer.Serialize(new { Name = input });
}
public static string GetData()
{
string json = Test("Mike");
return json;
}
And I get:
Error:SyntaxError: JSON.parse: unexpected character
UPDATE 2
Ok I got it.
From code behind I return:
var serializer = new JavaScriptSerializer();
return serializer.Serialize(new { NewTotal = "777", OfType = "love" });
On the ajax call success I have:
success: function (data) {
if (data != "") {
alert(data.d);
...
Now this present following data:
{"NewTotal":"777", "OfType":"love"}
And now the only issue I have is how to get NewTotal or OfType value because when I use data.NewTotal I get undefined?

You don't need to convert result to JSON, it is auto. serialized to JSON
[WebMethod()]
public static object GetData()
{
return (new { NewTotal = "777", OfType = "love" });
}
On JS, refer to newTotal like this
data.d.NewTotal

Well, first of all, calling Page methods inside UserControl will not work, so they should be defined in the aspx page.
Secondly, check for errors in firebug.
Also, make sure that you are calling from the same page.
Thirdly, use a webservice (*.asmx)

can use library using Newtonsoft.Json;
JsonConvert.SerializeObject(Request["paramater"])

Related

MVC 5 JsonResult returns html?

I have been following this tutorial https://www.youtube.com/watch?v=c_MELPfxJug regarding ajax and JsonResult in HomeController
I did the tutorial, however for some reason the controller is returning Html and not json
I did not change one line of code, but it's failing with parseError on the javascript side.
when i look at the response i see an html page, not a json object.
Controller code:
public JsonResult DoubleValue(int? Value)
{
if (!Request.IsAjaxRequest() || !Value.HasValue)
{ return null; }
else
{
int DoubleValue = Value.Value * 2;
var ret = new JsonResult
{
Data =
new { DoubleValue = DoubleValue }
};
return ret;
}
}
cshtml:
#using (Html.BeginForm())
{
#Html.TextBox("txtAmount",0)
<button id="btnDoubleValue">DoubleIT</button>
<div id="lblMessage"></div>
}
#section Scripts{
<script type="text/javascript">
$(function () {
$('#btnDoubleValue').on('click', function() {
$.ajax({
type: 'POST',
url: '#Html.Action("DoubleValue")',
data: { 'Value': $('#txtAmount').val() },
datatype: 'json',
cache: 'false'
}).success(function (data) {
var t = data;
$('#txtAmount').val(data.DoubleValue);
}).error(function (x, o, e) {
$('#lblMessage').html('error was found: ' );
});
return false;
})
});
</script>
}
found the error
I was using Html.Action and not Url.Action -> just human error I suppose
from the reference:
Html.Action - returns the result as an HTML string.
It works now
$.ajax({
type: 'POST',
url: '#Url.Action("DoubleValue")', //<--- Url.Action
data: { 'Value': $('#txtAmount').val() },
datatype: 'json',
cache: 'false'
I guess this must be the default error page, you are probably getting a 500 response and you must use the Network tab of your browser to see the real problem.
In your browser open developer tools using F12 key and navigate to Network tab.
Make the appropriate actions to do the ajax request (click on that button)
Click on the request row
Navigate to Response tab.
From there you can watch the real request your ajax does and the response from the server.

Calling asp.net server function using jquery ajax

Am basically new to jquery. I have a function in aspx code bihind. I need to call it in a button click from aspx page using jquery. The server side function takes no arguement and returns no data.
The function the code behind is :
[WebMethod]
public void BindTreeview()
{
TreeView1.Nodes.Clear();
System.IO.DirectoryInfo RootDir = new System.IO.DirectoryInfo(#"C:\ClientDocuments\Ford Retail Ltd\");
// output the directory into a node
TreeNode RootNode = OutputDirectory(RootDir, null);
// add the output to the tree
TreeView1.Nodes.Add(RootNode);
//TreeView1.SelectedValue = hdnSelectedNode.Value;
if (hdnSelectedNode.Value != string.Empty)
{
TreeView1.CollapseAll();
TreeNode searchNode = TreeView1.FindNode("Electricity");
if (searchNode != null)
searchNode.Expand();
}
}
aspx jquery is
$(document).ready(function () {
$('#btnNewFolder').click(function () {
// alert('Clicked');
$.ajax({
url: 'Default.aspx/BindTreeview',
type: "POST",
contentType: "application/json; charset=utf-8",
success: function () {
alert(1);
},
error: function (result) {
alert("The call to the server side failed. " + result.responseText);
}
});
});
});
When i run appln am getting alert on result.responseText. Where am i getting wrong? Quick response will be highly appreciable.
mark your method as static
public static void BindTreeview()

Ajax success when a view is returned

I'm struggling to return a view or partial view with Ajax. Whenever I change the return type to something that isn't JSon the ajax command never succeeds. I need to return a partial view because I want to return a lot of data back.
This is my current code:
(Controller)
[HttpPost]
public ActionResult AjaxTestController(string Input)
{
string Results = Input + " -- TestTestTest";
return PartialView("Test", Results);
//return new JsonResult() { };
}
(View)
function AjaxTest() {
alert("test");
$.ajax({
type: "POST",
url: "Home/AjaxTestController",
data: "Input=Test11111",
success: function () {
alert("Success!");
}
});
Thanks!
You can use the $.post command for that:
function AjaxTest() {
alert("test");
$.post({
url: "Home/AjaxTestController",
data: "Input=Test11111",
success: function (response) {
alert(response);
}
});
try the following:
$(function () {
$('#submit').live('click', function () {
AjaxTest();
});
});
function AjaxTest() {
$.ajax({
type: "POST",
url: '#Url.Action("AjaxTestController", "Home")',
data: { Input: "Test - " + new Date() },
success: function (data) {
$('#partialResult').html(data);
},
error: function (xhr, err) {
alert(xhr.responseText);
}
});
};
inside your view and ensure that you have your target div set up for the partial to be populated into:
<div id="partialResult"></div>
also, for the example above, I added a button to the view to initiate the ajax (purely for testing):
<input type="button" value="Submit" id="submit" />
your 'partialview' should look something like this:
#model string
<h2>
Partial Test</h2>
<p>
#Model
</p>
no other changes are required to the existing action for this to now function as required.
[UPDATE] - I changed the AjaxTest() method to include the error event (the result of which is captured in an alert). hopefully, this may help further.
partial View is different than view you have to specify the whole path to the partial view or have it in share folder. otherwise is going to return not found and never success. any way this always work for me, try
partialView("~/Views/ControllerView/Test.cshtml")

aspx and jquery.ajax is always returning an error

This code worked fine in mvc2, but moving back to traditional ASPX (because of Sharepoint 2010). I am encountering errors. Can anyone tell me what I am doing wrong for this framework?
This ajax call is in the $.ready
$.ajax({
type: "POST",
dataType: "json",
data: 'siteName=a&siteUrl=b',
url: 'Wizard.aspx/DoesNameUrlExist',
beforeSend: function () { alert("before send"); },
complete: function () { alert("complete"); },
success: function (data) { alert("success"); },
error: function (data) {
if ($("meta[name=debug]").attr("content") == "true") {
//Full Error when debugging
var errDoc = window.open();
errDoc.document.write(data.responseText);
errDoc.document.close();
}
else {
// generic error message for production use
alert("An unexpected error occurred.");
} return false;
}
});
code behind
[WebMethod]
public static string DoesNameUrlExist(string siteName, string siteUrl)
{
//do something
return someString;
}
I get an error everytime.
You need to send JSON to the service and indicate that you're doing so via the contentType header:
$.ajax({
type: "POST",
contentType: 'application/json',
data: '{"siteName":"a","siteUrl":"b"}',
url: 'Wizard.aspx/DoesNameUrlExist',
beforeSend: function () { alert("before send"); },
complete: function () { alert("complete"); },
success: function (data) { alert("success"); },
error: function (data) {
if ($("meta[name=debug]").attr("content") == "true") {
//Full Error when debugging
var errDoc = window.open();
errDoc.document.write(data.responseText);
errDoc.document.close();
}
else {
// generic error message for production use
alert("An unexpected error occurred.");
} return false;
}
});
More info here: http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
Also, if you're using jQuery 1.4, you can drop the dataType. jQuery will infer JSON automatically based on the response's Content-Type header.
Ajax calls in jQuery will always give you an error if you declare your contentType as json and the response content type is anything but json. If the response from your WebMethod has something different (such as html or text), you'll always get that error. You can set that response type on your method like this:
[WebMethod]
[ScriptMethod (UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public static string DoesNameUrlExist(string siteName, string siteUrl)
Outside of WebMethods this can also be achieved like this:
Response.ContentType = "application/json";

Getting ContentType in ASP.NET MVC 3

i have the following code in c#. I'm using ASP.NET MVC 3.
public override void ExecuteResult(ControllerContext context)
{
// If ContentType is not expected to be application/json, then return XML
if ((context.HttpContext.Request.ContentType ?? String.Empty).Contains("application/json"))
{
new JsonResult { Data = this.Data }
.ExecuteResult(context);
}
else
{
using (MemoryStream stream = new MemoryStream(500))
{
using (var xmlWriter = XmlTextWriter.Create(
stream,
new XmlWriterSettings()
{
OmitXmlDeclaration = true,
Encoding = UTF8,
Indent = true
}))
{
new XmlSerializer(typeof(T), IncludedTypes)
.Serialize(xmlWriter, this.Data);
}
// NOTE: We need to cache XmlSerializer for specific type. Probably use the
// GenerateSerializer to generate compiled custom made serializer for specific
// types and then cache the reference
new ContentResult
{
ContentType = "text/xml",
Content = UTF8.GetString(stream.ToArray()),
ContentEncoding = UTF8
}
.ExecuteResult(context);
}
}
}
I'm trying to return a json or a xml result depending the request. The problem is that i get context.HttpContext.Request.ContentType = "" when i run it.
Is there a way to make the application know that the request is "application/json"?
I'm returning this result object in a controller method called GetGoogleMapsMarkers:
$(document).ready(function () {
$.ajax({
type: "POST",
url: "http://localhost:1939/API/Google/GetGoogleMapsMarkers",
datatype: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data);
}
}
});
Help me please.
Thanks.
Unable to reproduce. Here's what I tried:
Result:
public class TestResult : ActionResult
{
public override void ExecuteResult(ControllerContext context)
{
var ct = context.HttpContext.Request.ContentType;
context.HttpContext.Response.Write(ct);
}
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Foo()
{
return new TestResult();
}
}
View:
<script type="text/javascript">
$.ajax({
url: '#Url.Action("foo")',
type: 'POST',
contentType: 'application/json; charset=utf-8',
success: function (result) {
alert(result);
}
});
</script>
The AJAX call resulted in the correct request content type to be fetched.
i added
data: { },
to the ajax call and it worked.... it's weird but it made it work...

Resources