jquery Post does not work in asp.net mvc 3? - asp.net

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>

Related

Ajax data not passing to controller

I have a problem where the data in the ajax isn't passing the sessionStorage item. I have tried using JSON.stringify and added contentType: 'application/json' but still it's not passing. Can this be done using POST method? Also, I have debugged and returned those sessionStorages, hence the problem isn't because the sessionStorge doesn't contain data.
Here my function:
function functionA() {
$.ajax({
url: URLToApi,
method: 'POST',
headers: {
sessionStorage.getItem('token')
},
data: {
access_token: sessionStorage.getItem('pageToken'),
message: $('#comment').val(),
id: sessionStorage.getItem('pageId')
},
success: function () {
$('#success').text('It has been added!"');
},
});
}
Check below things in Controller's action that
there should be a matching action in controller
name of parameter should be same as you are passing in data in ajax
Method type should be same the ajax POST of the action in controller.
function AddPayment(id, amount) {
var type = $("#paymenttype").val();
var note = $("#note").val();
var payingamount = $("#amount").val();
$('#addPayment').preloader();
$.ajax({
type: "POST",
url: "/Fixed/AddPayment",
data: {
id: id,
amount: payingamount,
type: type,
note: note
},
success: function (data) {
}
});
}
Here is the working code from my side.
Check with this, and for the header part you need to get it from the Request in action
The solution to this problem has been found. The issue was the sessionStorage, hence I've passed it directly to the URL and now it working as follows:
function functionA() {
$.ajax({
url: 'http://localhost:#####/api?id=' + sessionStorage.getItem('pageId') + '&access_token=' + sessionStorage.getItem('pageToken') + '&message=' + $('#comment').val(),
method: 'POST',
headers: {
sessionStorage.getItem('token')
},
success: function () {
$('#success').text('It has been added!"');
},
});
}

asp.net mvc core add anchor tag in success function in ajax

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

How to send ember js header request without ember data

I'm trying to make a call to the wp-api.org plugin for Wordpress. I want to show all users, and I want to use cookie authentication. Therefore I need to send a header request as explained on the website like this:
options.beforeSend = function(xhr) {
xhr.setRequestHeader('X-WP-Nonce', WP_API_Settings.nonce);
if (beforeSend) {
return beforeSend.apply(this, arguments);
}
};
The following code I am using in my model:
App.UsersRoute = Ember.Route.extend({
model: function() {
return Ember.$.ajax({
url: "http://myurl.com/wp-json/users/",
type: "GET",
dataType: "json",
data: JSON.stringify({}),
beforeSend: xhr.setRequestHeader('X-WP-Nonce', WP_API_Settings.nonce);
});
}
});
At the moment the site returns this message because the authentication failed, but I am logged in and cookies are set:
[{"code":"json_user_cannot_list","message":"Sorry, you are not allowed to list users."}]
This should work:
App.UsersRoute = Ember.Route.extend({
model: function() {
return Ember.$.ajax({
url: "http://myurl.com/wp-json/users/",
type: "GET",
dataType: "json",
data: JSON.stringify({}),
beforeSend: function(xhr) {
xhr.setRequestHeader('X-WP-Nonce', WP_API_Settings.nonce);
}
});
}
});
the beforeSend property needs to be a function that is passed xhr, like in your first example, in your second code snippet xhr will be undefined.

setTimeout calls function repeatedly and causes page to hang

I have three javascript functions defined that creates ajax calls to my java controller. I set timeouts for two of the functions to update the ping status every 3 seconds and to update performance status every 5 min. The ping update every 3 seconds seems to be working correctly but when the updatePerformance method gets called my controller method gets executed 5 or so times in a row until the app hangs. Any ideas why one is working and the other setTimeout isn't? Here's my javascript functions:
<script type="text/javascript">
function updateReachability() {
$.ajax({
url: 'updatePing.htm',
type: 'GET',
success: function(data) {
$('#site').html(data);
}
});
}
setTimeout(updateReachability, 3000);
function updatePerformance() {
$.ajax({
url: 'updatePerformance.htm',
type: 'GET',
success: function(data) {
$('#site').html(data);
}
});
}
setTimeout(updatePerformance, 300000);
function updateSiteList() {
$.ajax({
url: 'connector.htm',
type: 'GET',
success: function(data) {
$('#site').html(data);
}
});
}
you may want to wrap you function in the setTimeout itself, so that the settimeout is specific to that function and nothing else.
<script type="text/javascript">
function updateReachability() {
setTimeout(function() {
$.ajax({
url: 'updatePing.htm',
type: 'GET',
success: function(data) {
$('#site').html(data);
}
});
},3000);
May be this will work for you.
Don't know why this works but created a separate function that sets the two timeout values then called it on body onload:
<script type="text/javascript">
function updateSiteList() {
$.ajax({
url: 'connector.htm',
type: 'GET',
success: function(data) {
$('#site').html(data);
}
});
}
function updateReachability() {
$.ajax({
url: 'updatePing.htm',
type: 'GET',
success: function(data) {
$('#site').html(data);
}
});
}
function setTimeouts() {
setInterval(updateReachability, 3000);
setInterval(updatePerformance, 300000);
}
function updatePerformance() {
$.ajax({
url: 'updatePerformance.htm',
type: 'GET',
success: function(data) {
$('#site').html(data);
}
});
}

X-editable with .Net and c# web methods

I am using X-Editable Plugin in Asp.net.
I have tried this: Usage with .Net and C# Webmethods
But it gives me error. It is not calling the WebMethod as it should be.
How to solve this problem?
Please help.
Javascript:
$('#username').editable({
url: function (params) {
return $.ajax({
url: 'Default.aspx/TestMethod',
data: JSON.stringify(params),
dataType: 'json',
async: true,
cache: false,
timeout: 10000,
success: function (response) {
alert("Success");
},
error: function () {
alert("Error in Ajax");
}
});
}
});
HTML:
superuser
WebMethod in Default.aspx:
[System.Web.Services.WebMethod]
public static String TestMethod(String params)
{
//access params here
}
If you want to call a page method, first of all you need to make a request of type POST (also having content-type set will not do any harm):
$('#username').editable({
url: function (params) {
return $.ajax({
type: 'POST',
url: 'Default.aspx/TestMethod',
data: JSON.stringify(params),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: true,
cache: false,
timeout: 10000,
success: function (response) {
alert("Success");
},
error: function () {
alert("Error in Ajax");
}
});
}
});
Also the JSON will be auto deserialized on server side, so you should expect the name, pk and value parameters on server side (this is what plugin is sending according to docs)
[System.Web.Services.WebMethod]
public static String TestMethod(string name, string pk, string value)
{
//access params here
}
In your case the pk will be null as you haven't set one.

Resources