I have an ajax call that seems to be working fine on another page, however when i call it on this page it doesnt work.
CSHTML page
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<script src="~/Script/jquery-1.12.2.min.js"></script>
<script src="~/Script/moment.js"></script>
<script type="text/javascript">
function qs(key) {
key = key.replace(/[*+?^$.\[\]{}()|\\\/]/g, "\\$&"); // escape RegEx meta chars
var match = location.search.match(new RegExp("[?&]" + key + "=([^&]+)(&|$)"));
return match && decodeURIComponent(match[1].replace(/\+/g, " "));
}
function initialiseForms() {
$.ajax({
type: 'POST',
url:'#Url.Action("Index", "Home")',
contentType: 'application/json; charset=utf-8',
error: function (response) { alert(JSON.stringify(response)); }
}).success(function (response) {
alert(JSON.stringify(response));
});
}
</script>
</head>
<body onload="initialiseForms()">
<h1 id="titleText"></h1>
<form id="evolveFormsForm" method="post" target="_self" action="Test">
<input type="hidden" id="formPackEventData" name="formPackEventData" value="" />
<input type="hidden" id="selectedTemplateCodes" name="selectedTemplateCodes" value="" />
<input type="hidden" name="logonMethod" value="automatic" />
</form>
</body>
</html>
Controller
public ActionResult Index()
{
return Json(new { success = true, rtn = "TEST" }, JsonRequestBehavior.AllowGet);
}
This alert(JSON.stringify(response)); works in the response but the breakpoint is not hit and the alert just displays an empty string.
Cheers
Shouldn't your ajax be like this?
$.ajax({
type: 'POST',
url:'#Url.Action("Index", "Home")',
contentType: 'application/json; charset=utf-8',
error: function (response)
{
alert(JSON.stringify(response));
},
success(function (response)
{
alert(JSON.stringify(response));
}
})
instead of
$.ajax({
type: 'POST',
url:'#Url.Action("Index", "Home")',
contentType: 'application/json; charset=utf-8',
error: function (response) { alert(JSON.stringify(response)); }
}).success(function (response) {
alert(JSON.stringify(response));
});
I feel like you have the success outside of the actual ajax as well as having an extra )
EDIT: An easy way for us to help you would be if you add a debugger; into the function itself and tell us if it throws an error in Google DevTools
Related
I am sending ajax request in asp.net i get this error
POST http://localhost:1549/AdminArea/Roles.aspx/Create 500 (Internal
Server Error)
it is with Master Page Also shown code is in individual page Roles.aspx
my HTML Code
<form id="FormSave">
<input type="text" name="txtName" id="txtName" required="required"
class="form-control"/>
<input type="radio" name="Status" value="1" checked="checked"/> Active
<input type="radio" name="Status" value="0"/> In-active
</form>
Javascript Code For Sending Request
<script type="text/javascript">
$(document).ready(function () {
$("#BtnSave").click(function () {
var jsonText = JSON.stringify({ Name: $("txtName").val(), Status: $("Status").val() });
$.ajax({
type: "POST",
url: "Roles.aspx/Create",
contentType: "application/json; charset=utf-8",
data: jsonText,
dataType: "json",
success: function (response) {
alert(response);
}
});
});
});
</script>
SERVER SIDE C# SCRIPT /// IN Roles.aspx.cs file
[WebMethod]
public static string Create(string Name, string Status)
{
return "Hello " + Name + "With " + Status;
}
I want to alert this Hello Name With Status
I have seen answers to this question many times, but most of them are related to MVC controllers.
The issue I am having while trying to send a form using Ajax is that while in debug mode, the execution flow won't reach the break point I have in my code behind. Also, I notice that when I click in the submit button, the page refreshes very quickly; I though that the whole idea of ajax was to not refresh the page.
This is my index.aspx
<head runat="server">
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script src="ajaxform.js" type="text/javascript"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<fieldset class="fs1">
<input id="inputData" tabindex="1" name="theinputData" class="field" placeholder="Paste URL, docId or docSetId" runat="server"/>
<input id="form1Send" type="submit" class="button" onclick="submit()"/>
</fieldset>
</div>
</form>
</body>
Here is the code of my ajaxform.js
$(document).ready(function () {
$('#form1').submit(function (e) {
var formData = new FormData(this);
$.ajax({
url: 'index.aspx/OnSubmit',
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: formData,
contentType: false,
processData: false,
success: function (result) {
alert("We returned: " + result);
},
error: function (result) {
alert("Error");
}
});
e.preventDefault();
});
});
Finally, here is my code behind
namespace mySpace
{
public partial class index : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string OnSubmit()
{
return "I was in code behind";
}
}
}
My break point is on the return line. Why the program never reach the WebMethod?
There are a couple of issues with your code:
You're double declaring something to handle the form. Your form1send button has onclick="submit()" in it as well as the form submit handler you're wiring up via jQuery
The content of your JavaScript handler is slightly off, for example you set contentType twice.
Here's a simplified version of the JavaScript that works on my machine:
$(document).ready(function () {
$('#form1').submit(function (e) {
$.ajax({
type: "POST",
url: "index.aspx/OnSubmit",
contentType: "application/json; charset=utf-8",
data: '{}',
dataType: "json",
success: function (response) {
alert(response.d);
},
failure: function (response) {
}
});
e.preventDefault();
});
});
NOTE: I based this (the content of the $.ajax call) on a code sample I found elsewhere, which is why the parameters and order of the parameters are different to yours.
If your app has a RouteConfig.cs file present, you may also need to change settings.AutoRedirectMode = RedirectMode.Permanent; to settings.AutoRedirectMode = RedirectMode.Off; if you see an HTTP 401 error in your browsers developer tools console for the request to your WebMethod decorated method in index.aspx.
By executing event.preventDefault() before FormData(this) a premature refresh is prevented.
See below:
$(document).ready(function () {
$('#form1').submit(function (event) {
event.preventDefault();
var formData = new FormData(this);
$.ajax({
url: 'index.aspx/OnSubmit',
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: formData,
contentType: false,
processData: false,
success: function (result) {
alert("We returned: " + result);
},
error: function (result) {
alert("Error");
}
});
});
});
Here at below code, the action method which is specified in the URL is not being called at all. can any one help me..?
<link href="~/Content/themes/base/jquery.ui.all.css" rel="stylesheet" />
<link href="~/Content/jquery.jqGrid/ui.jqgrid.css" rel="stylesheet" />
<script src="~/Scripts/jquery.jqGrid.min.js"></script>
<script src="~/Scripts/i18n/grid.locale-en.js"></script>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
function getData() {
$('#list').jqGrid({
url: '/Home/gridData/', // here it is not calling
datatype: 'json',
contentType: "application/json; charset-utf-8",
// ...
});
}
Below one is action method:
public JsonResult gridData()
{
practiceEntities pt = new practiceEntities();
var jsonData = pt.tbl_dept.ToList();
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
Make a call like this. Remove the back slash (/) from the front and back of URL and there is no need of charset-utf-8
$('#list').jqGrid({
url: 'Home/gridData', // here it is not calling
datatype: 'json',
contentType: "application/json",
...........
..........
});
I'm using Tagify, which is basically using jQuery Autocomplete,
references :
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/jquery-ui.min.js"></script>
<script src="../../../Scripts/jquery.tagify.js" type="text/javascript"></script>
<link href="../../../Styles/jqueryTagify.css" rel="stylesheet" type="text/css" />
Script :
<script>
var myTextArea = $("#txtbox").tagify();
myTextArea.tagify('inputField').autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
url: "Demo.aspx/GetKeyword",
data: "{'match': '" + request.term + "'}",
dataType: "json",
contentType: "application/json",
success: function(data) {
response($.map(data, function(item) {
return {
label: item,
value: item,
}
}));
}
});
},
position: { of: myTextArea.tagify('containerDiv') },
close: function(event, ui) { myTextArea.tagify('add'); },
});
$('form').submit( function() {
var tagStr = $("#txtbox").tagify('serialize');
alert( "Got tags: " + tagStr );
return false;
});
</script>
HTML is :
<input type="text" id="txtbox" />
<input class="submit" type="submit" value="Get Values" />
So when we clicked on submit button, we get tags value from here
var tagStr = $("#txtbox").tagify('serialize');
and when I clicked on getvalues the result like this
How could I get those values in the Code Behind in C#?
add a hidden field in html:
<input id="hiddenTags" name="tags" type="hidden"/>
and update submit js:
$('form').submit( function() {
var tagStr = $("#txtbox").tagify('serialize');
alert( "Got tags: " + tagStr );
$('#hiddenTags').val(tagStr);
return false;
});
now you can get tags in c#:
string tags = Request.Form["tags"];
I am trying to call a simple method in my code behind using Jquery with Ajax. But I get a 404 not found exception everytime. Unfortunately this is a web forms solution. So I dont have all the perks of MVC :(
It does get into the javascript method and gives the alert but won't go into my c# method. My previous experience of using this Jquery method is in an MVC website. Is it compatible with webforms sites?
My Javascript is:
$(document).ready(function() {
$('#btn_<%=UserStuff.tag %>').click(function() {
var value = $('#<%#Eval("tag") %>twink').val();
something(value);
});
});
function something(theval) {
alert(theval);
$.ajax({
type: "POST",
url: "/Default.aspx/MyMethod?something=" + theval,
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg);
}
});
}
}
And my C# code is:
public JsonResult MyMethod(string something)
{
JsonResult ret = new JsonResult();
return ret;
}
Thanks in advance.
Your method returns JsonResult. This is MVC specific and you cannot use it in a webforms application.
If you want to call methods in the code behind in a classic WebForms application you could use PageMethods:
[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToString();
}
And then to call the method:
$.ajax({
type: 'POST',
url: 'PageName.aspx/GetDate',
data: '{ }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(msg) {
// Do something interesting here.
}
});
And here's a full working example I wrote for you:
<%# Page Language="C#" %>
<%# Import Namespace="System.Web.Services" %>
<script type="text/C#" runat="server">
[WebMethod]
public static string SayHello(string name)
{
return "Hello " + name;
}
</script>
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="/scripts/jquery-1.4.1.js"></script>
<script type="text/javascript">
$(function () {
$.ajax({
type: 'POST',
url: 'default.aspx/sayhello',
data: JSON.stringify({ name: 'John' }),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
// Notice that msg.d is used to retrieve the result object
alert(msg.d);
}
});
});
</script>
</head>
<body>
<form id="Form1" runat="server">
</form>
</body>
</html>
PageMethods are not limited to simple argument types. You could use any type as input and output, it will be automatically JSON serialized.