Ajax method always goes to error function - c#

I have this simple ajax method:
$.ajax({
type: 'POST',
url: 'http://localhost:1195/widget/postdata',
datatype: "jsondata",
async: false,
success: function (data) {
alert("ok")
},
error: function (data) {
alert(data.status + ' ' + data.statusText);
}
});
And this simple method in c#:
[HttpPost]
public JsonResult PostData()
{
return Json("1");
}
When I check the inspector console I have "1" in response but my ajax method always goes to error function.
Why is it so?

In your AJAX call it should be dataType: "json" and not datatype: "jsondata". You can refer to the docs
Also use #Url.Action tag in your url call: url: '#Url.Action("postdata", "widget")'
For a small test, I have used the following AJAX call to the same controller method that you have posted and I am getting the correct result:
$(document).ready(function () {
$("#button_1").click(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url:'#Url.Action("PostData", "Home", null, Request.Url.Scheme)',
datatype: "json",
async: false,
success: function (result) {
alert(result);
},
error: function (error) {
alert(error);
}
});
});
});
</script>
<button id="button_1" value="val_1" name="but1">Check response</button>
Output:

Change the Ajax request to the following :
$.ajax({
type: 'POST',
url: '/widget/postdata',
datatype: "json",
async: false,
success: function (data) {
console.log(data);// to test the response
},
error: function (data) {
alert(data.status + ' ' + data.statusText);
}
});
Always use relative URL instead of full URL that contains the domain name, this will make the deployment easier so you don't have to change the URls when going live

Related

MVC Ajax: How to send string from view to controller

I've found a small problem in sending just plain text(string) via ajax compared to sending an json object.
I have currently this setup working
(cs)html
<label for="search">
<i class="fa fa-search" onclick="sendtoC()"></i>
<input type="search" id="search" placeholder="Sök här..." autofocus; />
<input type="button" id="SÖK" value="SÖK" onclick="sendtoC()" />
Script
<script>
var invalue;
var input = document.getElementById("search");
input.addEventListener("keyup", function go (event) {
if (event.keyCode === 13) {
invalue = document.getElementById("search").value;
sendtoC(invalue);
}
});
function sendtoC() {
$.ajax({
url: "/Home/SearchResults",
dataType: "json",
type: "GET",
contentType: 'application/json; charset=utf-8', //define a contentType of your request
cache: false,
data: { input: invalue },
success: function (data) {
if (data.success) {
alert(data.message);
}
},
error: function (xhr) {
alert('error');
}
});
}
and current controller
public ActionResult SearchResults(string input)
{
Data.gsPersonLista = db.GetPerson(input);
return Json(new { success = true, message = input }, JsonRequestBehavior.AllowGet);
}
I would like to just send a straight string to the controller and i tried this Script
function sendtoC() {
$.ajax({
url: "/Home/SearchResults",
dataType: "text",
type: "GET",
contentType: 'application/json; charset=utf-8', //define a contentType of your request
cache: false,
data: invalue ,
success: function (data) {
if (data.success) {
alert(data.message);
}
},
error: function (xhr) {
alert('error');
}});}
with this Controller
public ActionResult SearchResults(string input)
{
Data.gsPersonLista = db.GetPerson(input);
return View(input);
}
however this didn't work, the input string was shown to get value of null and ajax gave error. I currently have no idea of how to fix this nor what gives the error. If someone could Point me in the right direction I would appreciate it
You can simply use the $.get function here and secondly you should use the Ùrl.Action helper for getting the url against the controller action method, as the magic strings would cause issues in deployments where the application might be deployed in sub-directories and in those case the url becomes wrong :
$.get('#Url.Action("SearchResults","Home")?input='+invalue , function (data) {
if (data.success) {
alert(data.message);
}
});
You can easily pass it as a request parameter, since you've also set the type to "GET".
url: "/Home/SearchResults?input="+invalue
You also have to remove the data attribute. Let me know if it helps.
UPDATED ANSWER
datatype is what you are expecting to return from the server. Content type is what you are sending. so to return a view change datatype to htmL.
dataType: 'html',
the problem is that when you call the function sendtoC you are not receiving any parameters in the function. Change the function to accept a parameter.
var invalue;
var input = document.getElementById("search");
input.addEventListener("keyup", function go (event) {
if (event.keyCode === 13) {
invalue = document.getElementById("search").value;
sendtoC(invalue);
}
});
function sendtoC(invalue ) {
$.ajax({
url: "/Home/SearchResults",
dataType: "json",
type: "GET",
contentType: 'application/json; charset=utf-8', //define a contentType of your request
cache: false,
data: { input: invalue },
success: function (data) {
if (data.success) {
alert(data.message);
}
},
error: function (xhr) {
alert('error');
}
});
}

Can't get ajax call with parameters to hit my C# function

Ajax:
var test = "test";
$.ajax(
{
type: "POST",
url: "project/function",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: { input: test },
success: function (response) {
$("#lblMsg").text(response.d);
},
failure: function (response) {
alert(response.d);
}
});
C# function:
[WebMethod]
public void function(string input)
{
}
The connection is made successfully when I don't include a parameter. I have tried different single and double quote permutations of the 'data' portion of the ajax call, to no avail.
I have also tried setting the dataType to "text" with similar results.
What am I missing?
I would suggest that you shouldn't send your data as JSON. Just remove the
contentType: "application/json; charset=utf-8"
and jQuery will serialise the data into normal url-encoded form data format, which is what the WebMethod is expecting.
try this one may be resolve your issue
var test = "test";
$(document).ready(function () {
$.ajax({
type: "POST",
url: "project/function",
contentType: "application/json; charset=utf-8",
datatype: "json",
data:JSON.stringify({ 'input': test }),
success: function (response) {
$("#lblMsg").text(response.d);
},
failure: function (response) {
alert(response.d);
}
});
});

Passing arguments in jQuery post to a method in controller

In ASP.NET MVC I was using this script to call a method in controller:
<script>
$.ajax({
url: '#Url.Action("getBookedByUser", "Home")',
data: "2",
dataType: "html",
success: function (data) {
$('#someElement').html(data); // add the returned html to the DOM
console.log(data);
},
});
</script>
and this is the method I call:
public async Task getBookedByUser(string id)
{
BenchesService benchService = new BenchesService();
List<Bench> obj = await benchService.getLastBenchByUser(id);
userBench = obj.ElementAt(0);
}
My problem is that id in my controller method is null. It doesn't assume the value "2" as I intend.
Any idea why?
You're almost there. You need to setup the JSON to include your id property:
$.ajax({
url: '#Url.Action("getBookedByUser", "Home")',
data: { id: '2' },
dataType: "html",
success: function (data) {
$('#someElement').html(data); // add the returned html to the DOM
console.log(data);
},
});

async ajax call error won't show Error.cshtml

I'm calling a function in the controller using ajax. If there is an error in the controller, it goes to the Error.cshtml page, sends an error email from that page, but it won't render the Error.cshtml page on the screen, it stays on the page with the ajax call.
How do I fix that?
Here is the ajax call:
$("#County").change(function () {
$.ajax({
url: '#Url.Action("UpdateCountySessionVariables", "Home")',
type: 'POST',
data: JSON.stringify({ countyId: $("#County").val() }),
datatype: 'json',
contentType: "application/json; charset=utf-8",
success: function (data) {
location.reload();
},
failure: function (data) {
alert('failure');
},
});
});
Here is the customErrors from the main web.config:
<customErrors mode="On" defaultRedirect="~/Error" redirectMode="ResponseRedirect"/>
In your $.ajax definition you should use error property, not failure, check documentation. Like this:
$.ajax({
url: '#Url.Action("UpdateCountySessionVariables", "Home")',
type: 'POST',
data: JSON.stringify({ countyId: $("#County").val() }),
datatype: 'json',
contentType: "application/json; charset=utf-8",
success: function (data) {
location.reload();
},
error: function (data) {
alert('failure');
},
});
You also can get full error page like this:
error: function (httpRequest) {
console.log(httpRequest.responseText);
},

Unknown web method parameter method name

I'm building a Web Application in which I'm trying to call a WebMethod in a WebForm, I've tried every single page in google but I'm still getting nothing. This is an example of the Jquery Ajax Call
$.ajax({
type: "Post",
url: "Default.aspx/Return",
data: {dato:'Hello'},
contentType: "application/json; chartset:utf-8",
dataType: "json",
success:
function (result) {
if (result.d) {
alert(result.d);
}
},
error:
function (XmlHttpError, error, description) {
$("#grdEmpleados").html(XmlHttpError.responseText);
},
async: true
});
And this is the WebMethod in the codebehind
[WebMethod]
[ScriptMethod(ResponseFormat=ResponseFormat.Json)]
public static string Return(string dato)
{
return dato;
}
You can't access a Static method this way. Remove the "Static" reference and it will work. Also, like someone else said - do not use that as your method name "Return".
[WebMethod]
[ScriptMethod(ResponseFormat=ResponseFormat.Json)]
public string Return(string dato)
{
return dato;
}
I think, on your success event the function with result is used, which is a string and u are trying to access property named d assuming result is an object.
use of only alert(result);
User F12 tool to debug and find your error.
Make sure that you have enabled page methods in your ScriptManager element:
<asp:ScriptManager ID="scriptManager" runat="server" EnablePageMethods="true" />
and your method
$.ajax({
type: "Post",
url: '<%= ResolveUrl("~/Default.aspx/Return") %>',
data: {dato:'Hello'},
contentType: "application/json; charset=utf-8",
dataType: "json",
success:
function (result) {
alert(result);
},
error:
function (XmlHttpError, error, description) {
$("#grdEmpleados").html(XmlHttpError.responseText);
},
async: true
});
Try this
var url = window.location.pathname + "/Return";
$.ajax({
type: "Post",
url: url,
data: {dato:'Hello'},
contentType: "application/json; charset=utf-8",
dataType: "json",
success:
function (result) {
alert(result.d);
},
error:
function (XmlHttpError, error, description) {
$("#grdEmpleados").html(XmlHttpError.responseText);
},
async: true
});`

Categories

Resources