I am trying to call a method with jQuery on a button click.This is waht I have so far:
$("a.AddToCart").click(function () {
var link = document.URL;
$.ajax({
type:"POST",
url: "/Account/AddToCartHack",
data: {url : link},
contentType: "application/json; charset=utf-8",
dataType: "json"
});
});
[WebMethod]
public void AddToCartHack(string url)
{
GeneralHelperClass.URL = url;
}
What I am trying to do here is when I click the link with class add to cart I want to call the method AddToCartHack and pass it the curent URL as a parameter.
I must be doing something wrong because it seems that AddToCartHack is not being called.
What am I doing wrong?
There are quite a lot of issues with your code, I don't know where to start. So let's conduct an interactive refactoring session with you (if you don't care about my comments but just want to see the final and recommended solution, just scroll down at the end of answer).
First: you don't seem to be canceling the default action of the anchor by returning false from the .click() event handler. By not doing this you are actually leaving the browser perform the default action of the anchor (which as you know for an anchor is to redirect to the url that it's href attribute is pointing to. As a consequence to this your AJAX call never has the time to execute because the browser has already left the page and no more scripts are ever running). So return false from the handler to give your AJAX script the possibility to execute and stay on the same page:
$("a.AddToCart").click(function () {
var link = document.URL;
$.ajax({
type:"POST",
url: "/Account/AddToCartHack",
data: {url : link},
contentType: "application/json; charset=utf-8",
dataType: "json"
});
return false;
});
Second: You have specified contentType: 'application/json' request header but you are not sending any JSON at all. You are sending a application/x-www-form-urlencoded request which is the default for jQuery. So get rid of this meaningless parameter in your case:
$("a.AddToCart").click(function () {
var link = document.URL;
$.ajax({
type:"POST",
url: "/Account/AddToCartHack",
data: {url : link},
dataType: "json"
});
return false;
});
Third: You have specified that your server side code will return JSON (dataType: 'json') but your server side code doesn't return anything at all. It's a void method. In ASP.NET MVC what you call C# method has a name. It's called a controller action. And in ASP.NET MVC controller actions return ActionResults, not void. So fix your contoller action. Also get rid of the [WebMethod] attribute - that's no longer to be used in ASP.NET MVC
public class AccountController: Controller
{
public ActionResult AddToCartHack(string url)
{
GeneralHelperClass.URL = url;
return Json(new { success = true });
}
}
Fourth: you have hardcoded the url to the controller action in your javascript instead of using server side helpers to generate this url. The problem with this is that your code will break if you deploy your application in IIS in a virtual directory. And not only that - if you decide to modify the pattern of your routes in Global.asax you will have to modify all your scripts because the url will no longer be {controller}/{action}. The approach I would recommend you to solve this problem is to use unobtrusive AJAX. So you would simply generate the anchor using an HTML helper:
#Html.ActionLink(
"Add to cart",
"AddToCartHack",
"Account",
null,
new { #class = "AddToCart" }
)
and then unobtrusively AJAXify this anchor:
$('a.AddToCart').click(function () {
var link = document.URL;
$.ajax({
type: 'POST',
url: this.href,
data: { url : link }
});
return false;
});
Fifth: You seem to be employing some document.URL variable inside your .click() handler. It looks like some global javascript variable that must have been defined elsewhere. Unfortunately you haven't shown the part of the code where this variable is defined, nor why is it used, so I cannot really propose a better way to do this, but I really feel that there's something wrong with it. Or oh wait, is this supposed to be the current browser url??? Is so you should use the window.location.href property. Just like that:
$('a.AddToCart').click(function () {
$.ajax({
type: 'POST',
url: this.href,
data: { url : window.location.href }
});
return false;
});
or even better, make it part of the original anchor (Final and recommended solution):
#Html.ActionLink(
"Add to cart",
"AddToCartHack",
"Account",
new { url = Request.RawUrl },
new { #class = "AddToCart" }
)
and then simply:
$('a.AddToCart').click(function () {
$.ajax({
type: 'POST',
url: this.href
});
return false;
});
Now that's much better compared to what we had initially. Your application will now work even with javascript disabled on the page.
place script method this way as shown below
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
Add Success and error function to check your ajax functionality
...
$.ajax({
type:"POST",
url: "/Account/AddToCartHack",
data: {url : link},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(){
alert('success');
},
error:function(){
alert('error');
}
});
....
If this is Asp.Net webforms you will need to make the webmethod static or the method cannot be accessed through JavaScript.
$(document).ready(function () {
$.ajax({
url: "Testajax.aspx/GetDate",
data: "f=GetDate",
cache: false,
success: function (content) {
$('#tableData').append('My Dear Friend');
alert(content);
},
failure: function (response) {
alert("no data found");
}
});
});
Related
I originally wrote the call as a GET but found a limitation with the length of the URI. Ideally, the call will take an object and turns it into a JSON format string, then sends it to a controller which will encrypt that string. The controller will send back a true/false if it succeeded.
My problem with POST, once it reaches the controller, the data parameter set from the ajax is null.
Here is the ajax/js:
var encActionURL = '#Url.Action("Encrypt", "Home")';
$.ajax({
url: encActionURL,
type: "POST",
contentType: "application/json; charset=utf-8;",
dataType: "json",
async: true,
traditional: true,
data: { jsonDoc: JSON.stringify(jsonDataFile) },
success: /*OnSuccess*/ function (result) {
// DO STUFF;
}
});
Here is the controller:
[HttpPost]
public bool Encrypt(string jsonDoc)
{
return serverConnection.Encrypt();
}
Note that, when I simply change the type to 'GET', it works great but when the form gets too long, it throws a 414 status error.
Most of the fixes found that I seem to have is the 'application/json'. I've also set ajax to traditional.
After going through a rabbit-hole of security tokens and validating forms, it wasn't any of that... this might be a solution for anyone using ASP.NET Core 2.1 MVC (5?) or just in general. Could have been a syntax mistake, return type mistake, or a combination.
New Ajax
$.ajax({
url: encActionURL,
type: "POST",
data: { 'jsonDoc': JSON.stringify(jsonDataFile) }, // NOTICE the single quotes on jsonDoc
cache: false,
success: /*OnSuccess*/ function (result) {
// DO STUFF;
}
});
New Controller
[HttpPost]
public ActionResult EncryptJSON(string jsonDoc) // Switch to ActionResult, formerly JsonResult
{
return Json(serverConnection.Encrypt());
}
I am using C# ASP.NET MVC and wish to know is there any way to redirect to other page from controller in success condition. For failure condition, it should return JSon result redirect to AJAX method. For this, ActionResult return type is okay for me.
C# Controller:
[HttpPost]
public ActionResult DoMyAction(string var1, string var2)
{
// Do some action
if(success)
Redirect to a page.
else
return Json(new { Message = "Action cannot be process..", Status = false});
}
AJAX method:
$.ajax({
url: '/Home/DoMyAction',
type: 'POST',
data: { "var1": "Hello", "var2":"World!"},
datatype: "json",
contenttype: "application/json; charset=utf-8",
success: function (result) {
if (!result.Status)
// Display error message.
},
error: function () {
}
});
Note: Please do not consider syntax here, I wish to know only the way to redirect from C# controller class.
Thanks in advance!
If you want to redirect to a page using js you can use
window.location.href = 'your url here'
Hope that help.
You Need to add this in your success callback or else a normal form submit can be used
I've looked at several solutions for making an ajax call and by not this issue mentioned anywhere i feel it might be something specific to the environment i'm working with.
My controller:
[HttpPost]
public ActionResult ChangeDefualtCC(string a)
{
return Json("ok");
}
[HttpGet]
public ActionResult ChangeDefualtCC()
{
return Json("ok");
}
JS:
$("nevermind").change(function () {
$.ajax({
type: "POST",
url: "/Account/ChangeDefualtCC",
dataType: "json",
data: {
a: "A"
},
success: function (data) { console.log(data)},
error: function (data) { console.log("error");}
});
});
The Controller code is never hit, and this is what i'm seeing in chrome after the ajax call:
EDIT 2: The page hits the [HttpGet] method.
EDIT:
I tagged Ektron as well because it is used in the project, and it is possible that it is affecting the call.
My Routes:
Update: I have tried using Get, as well as Post, and also returning back to the View I was in, I get the 302 everytime.
any ideas?
It looks like it finds the "get" because you don't have a parameter in that call. I think you might be missing the content type from your ajax call, so the model binder cannot parse the content of your post as a parameter.
$.ajax({
type: "POST",
url: "/Account/ChangeDefualtCC",
contentType: 'application/json; charset=utf-8',
dataType: "json",
data: {
a: "A"
},
success: function (data) { console.log(data)},
error: function (data) { console.log("error");}
});
Your code seems to be absolutely correct.
This not be exact solution but try this may it work.
$("nevermind").change(function () {
$.post("/../Home/ChangeDefualtCC", { a: "A" }, function (data) {
console.log(data)
});
});
Our project is integrated with the CMS Ektron. We later discovered that Ektron is hit before the C# code, and has some affect to any url without a trailing url.
Thanks for all the help
I've never used ajax and I'm just try to see if this will call the method from my controller and give me the desired result. The javascript debugger in VS doesn't seem to be working at the moment. Does this look right?
$("form").submit(function() {
var hasCurrentJob = $.ajax({
url: 'Application/HasJobInProgess/#Model.ClientId'
});
});
controller method
public Boolean HasJobInProgress(int clientId)
{
return _proxy.GetJobInProgress(clientId).Equals(0);
}
Update
$("#saveButton").click(function() {
var hasCurrentJob = false;
$.ajax({
url: '#Url.Action("HasJobInProgress","ClientChoices")/',
data: { id: #Model.ClientId },
success: function(data){
hasCurrentJob = data;
}
});
if (hasCurrentJob) {
alert("The current clients has a job in progress. No changes can be saved until current job completes");
}
});
Try to use the Url.Action HTML Helper method when calling an action method. This will get you the correct url to the action method. You dont need to worry about how many ../ to add/
$(function(){
$("form").submit(function() {
$.ajax({
url: '#Url.Action("HasJobInProgess","Application")',
data: {clientId: '#Model.ClientId'},
success: function(data) {
//you have your result from action method here in data variable. do whatever you want with that.
alert(data);
}
});
});
});
I have a user control that I'm creating that is using some AJAX in jQuery.
I need to call a function in the code-behind of my control, but every example I find online looks like this:
$("input").click(function() {
$.ajax({
type: "POST",
url: "Default.aspx/GetResult",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result) {
//do something
}
});
});
This works fine if I have the method in the Default.aspx page. But I don't want to have the function there, I need the function in the code-behind of my control. How can I modify the url property to call the correct function?
I tried:
url: "GetResult"
but that didn't work.
The way to handle this is to have the webmethod in your page, then just pass the values directly to a control method with the same signature in your control - there is no other way to do this.
In other words, ALL the page method does is call the usercontrol method so it is really small. IF you have the same signature for multiple child controls, you could pass a parameter to tell the page method which one to call/use.
EDIT: Per request (very very simple example). You can find other examples with more complex types being passed to the server side method. for instance see my answer here: Jquery .ajax async postback on C# UserControl
Example:
Page method: note the "static" part.
[WebMethod]
public static string GetServerTimeString()
{
return MyNamespace.UserControls.Menu.ucHelloWorld();
}
User Control Method:
public static string ucHelloWorld()
{
return "howdy from myUserControl.cs at: " + DateTime.Now.ToString();
}
Client ajax via jquery:
$(document).ready(function()
{
/***************************************/
function testLoadTime(jdata)
{
$("#timeResult").text(jdata);
};
$("#testTimeServerButton").click(function()
{
//alert("beep");
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{}",
dataFilter: function(data)
{
var msg;
if (typeof (JSON) !== 'undefined' &&
typeof (JSON.parse) === 'function')
msg = JSON.parse(data);
else
msg = eval('(' + data + ')');
if (msg.hasOwnProperty('d'))
return msg.d;
else
return msg;
},
url: "MyPage.aspx/GetServerTimeString",
success: function(msg)
{
testLoadTime(msg);
}
});
});
});
Note: the dataFilter: function(data)... part of the ajax is so that it works with 2.0 and 3.5 asp.net ajax without changing the client code.
You can't...WebMethods have to be in WebServices or Pages, they cannot be inside UserControls.
Think about it a different way to see the issue a bit clearer...what's the URL to a UserControl? Since there's no way to access them you can't get at the method directly. You could try another way perhaps, maybe a proxy method in your page?