Ajax call not running code behind controller - javascript

So basically when i'm trying to make ajax call it doesn't run code behind it, no error code, everything seems fine but isnt, even after adding a breakpoint, it doesnt hit it.
Roulette Controller:
public class RouletteController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Pts(int amount)
{
System.Diagnostics.Debug.WriteLine("1111");
Console.WriteLine("2222");
return Json("test");
}
}
JS Script:
$.ajax({
type: "POST",
url: '#Url.Action("Pts", "Roulette")',
contentType: "application/json",
data: JSON.stringify({ id: "1",}),
success: function(recData) { alert('Success'); },
error: function (xhRequest, ErrorText, thrownError) {
alert("Fail");
console.log('xhRequest: ' + xhRequest + "\n");
console.log('ErrorText: ' + ErrorText + "\n");
console.log('thrownError: ' + thrownError + "\n");
}
})
#Edit
Network Tab:

Fix your ajax:
$.ajax({
type: "POST",
url: '/Roulette/Pts")',
data: { amount: 1},
success: function(recData) { alert('Success'); },
error: function (xhRequest, ErrorText, thrownError) {
alert("Fail");
console.log('xhRequest: ' + xhRequest + "\n");
console.log('ErrorText: ' + ErrorText + "\n");
console.log('thrownError: ' + thrownError + "\n");
}
});
And just for the test modify your action header
[Route("~/Roulette/Pts")]
public ActionResult Pts(int amount)
{
System.Diagnostics.Debug.WriteLine("1111");
Console.WriteLine("2222");
return Json("test");
}

Related

asynchronous web Api call success function not returning the data Set

my asynchronous web API returning the data
[HttpGet]
[Route("PrjID_SelectMob")]
public async Task<List<PrjID_SelectMob>> PrjID_SelectMob(int CKy, int UsrKy, int ObjKy, int TrnTypKy, int PreKy, string EnvironmentName)
{
List<PrjID_SelectMob> objMasList = await accMasService.PrjID_SelectMob(CKy, UsrKy, ObjKy, TrnTypKy, PreKy, EnvironmentName);
return objMasList;
}
ajax success function not getting the return data i will get (dataset = undefined)
$.ajax({
url: "http://localhost:49558/api/ComboLoad/PrjID_SelectMob?CKy=" + Cky + "&UsrKy=" + userky + "&ObjKy=" + ObjKy + "&TrnTypKy=" + FormGlblData.TrnTypKy + "&PreKy=" + 1 + "&EnvironmentName=" + Envermentname,
type:'GET',
crossDomain: true,
dataType: 'jsonp',
async: false,
contentType: 'application/json; charset=utf-8',
success: function (dataSource) {
dataset = dataSource;
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log(textStatus);
alert("Status: " + textStatus);
alert("Error: " + errorThrown);
}
});
I will get this error
Status: parsererror
Error: Error: jQuery112303621583680685383_1530522960313 was not called
How can i bind the dataset into Success Function

cannot send json or text to C# bhind-code using AJAX

I have an AJAX code where I am trying to send some data to a method within C# code-behind
I've tried to send them either using text data type and json data type, but neither of them are working with me.
when I use json type, it returns me the following error:
Internal Server Error
and when using text me
thod, there is no error appear and the code comes through the success function, but the actually the data is never sent to the method of the code-behind class
this is the ajax code using json type:
function searchClicked(sCriterion) {
$.ajax({
type: "POST",
url: "TokenRegistration.aspx/GetSearchCritetrion",
data: "{creiterion : " + sCriterion + " }",
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
success: function (result) {
alert("We returned: " + result);
}
And this is the ajax code using the text format:
function searchClicked(sCriterion) {
$.ajax({
type: "POST",
url: "TokenRegistration.aspx/GetSearchCritetrion",
data: sCriterion,
contentType: "application/text; charset=utf-8",
dataType: "text",
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
success: function (result) {
alert("We returned: " + result);
}
Also here is the my code-behind method that the data should be sent to:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void GetSearchCritetrion(object selectedItem)
{
var json = new JavaScriptSerializer();
var data = json.Deserialize<Dictionary<string, Dictionary<string, string>>[]>(selectedItem.ToString());
}
I've used the exact same ajax code in another project and it works perfectly, but here i'm not getting where the error is, so any suggestions please?
see if this works
instead of sending object try to pass as string
data: JSON.stringify({selectedItem : sCriterion }),
code behind
public void GetSearchCritetrion(string selectedItem)
Here is a really simple example that posts JSON to a controller method, which converts this into an object and then returns a response.
HTML:
<button id="go" class="btn">Go</button>
JS:
var obj = { foo: 123, bar: "abc " };
$('#go').click(function () {
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/Test/TestJson',
data: JSON.stringify(obj),
success: function (response) {
alert(response.result)
},
failure: function (response) {
alert('fail');
}
});
});
Controller:
public class TestController : Controller
{
[OutputCache(Location = OutputCacheLocation.None)]
public JsonResult TestJson(TestClass tc)
{
return Json(new { result = "foo=" + tc.foo + " bar=" + tc.bar }, JsonRequestBehavior.AllowGet);
}
public class TestClass
{
public int foo { get; set; }
public string bar { get; set; }
}
}
I think this help you.
class Item
{
public int id { get; set; }
}
[WebMethod]
public static void GetSearchCritetrion(Item selectedItem)
{
//ToDo: selectedItem.id
}

JavaScript Display Loader while Controller Response

Hi I have a JQuery Function that is calling a controller when
Controller Response (success()) it is loading an iFrame;
Basically; converter is returning success function after 30 seconds, for that reason I am trying to display a loading image using
beforeSend: function()
{
},
Function I tried a lots but its not working; Could you please give me advice how can I achieve it. My code are given bellow:
var callController = function (FirstName, documentId, fileName, packet) {
$.ajax({
type: "POST",
url: "http://localhost:63902/Home/Preview?DocumentId=" + documentId + "&FileName=" + fileName + "&packet=" + packet,
cache: false,
async: false,
//controller happens...
success: function (returnedValue) {
rememberDocumentId(documentId);
location.reload("#mainIframe");
setTimeout(function () {
}, 3000);
document.getElementById("mainIframe").style.display = "none";
document.getElementById("documentIframe").style.display = "block";
document.getElementById("documentIframe").src = "http://localhost:63902/FileProcessing/PDFProcessing/TempPDF/" + returnedValue;
event.preventDefault();
},
error: function (jqXHR, textStatus, errorThrown) {
alert(jqXHR + " " + textStatus + " " + errorThrown);
}
});
};
you can show your loader right after or before $.ajax({...}) but you should never use async:false, this is the root of evil, it will freeze the browser while the request has not succeeded.
like this:
var callController = function (FirstName, documentId, fileName, SL) {
//here
showLoader();
$.ajax({
type: "POST",
url: "http://localhost:63902/Home/Preview?DocumentId=" + documentId + "&FileName=" + fileName + "&SL=" + SL,
cache: false,
//controller happens...
success: function (returnedValue) {
rememberDocumentId(documentId);
location.reload("#mainIframe");
setTimeout(function () {
}, 3000);
document.getElementById("mainIframe").style.display = "none";
document.getElementById("documentIframe").style.display = "block";
document.getElementById("documentIframe").src = "http://localhost:63902/FileProcessing/PDFProcessing/TempPDF/" + returnedValue;
//hide Here
hideLoader();
},
error: function (jqXHR, textStatus, errorThrown) {
alert(jqXHR + " " + textStatus + " " + errorThrown);
//hide Here
hideLoader();
}
});
}

How to get a list from mvc controller to view using jquery ajax

I need to get a list from mvc controller to view using jquery ajax. how can i do that. this is my code. Its alerting error message.
In Controller
public class FoodController : Controller
{
[System.Web.Mvc.HttpPost]
public IList<Food> getFoodDetails(int userId)
{
IList<Food> FoodList = new List<Food>();
FoodList = FoodService.getFoodDetails(userId);
return (FoodList);
}
}
In view
function GetFoodDetails() {
debugger;
$.ajax({
type: "POST",
url: "Food/getFoodDetails",
data: '{userId:"' + Id + '"}',
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
debugger;
alert(result)
},
error: function (response) {
debugger;
alert('eror');
}
});
}
Why you use HttpPost for GET-method? And need return JsonResult.
public class FoodController : Controller
{
public JsonResult getFoodDetails(int userId)
{
IList<Food> FoodList = new List<Food>();
FoodList = FoodService.getFoodDetails(userId);
return Json (new{ FoodList = FoodList }, JsonRequestBehavior.AllowGet);
}
}
function GetFoodDetails() {
debugger;
$.ajax({
type: "GET",
url: "Food/getFoodDetails",
data: { userId: Id },
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
debugger;
alert(result)
},
error: function (response) {
debugger;
alert('eror');
}
});
}
you can do like this , return json data and print it
Read full tutorial : http://www.c-sharpcorner.com/UploadFile/3d39b4/rendering-a-partial-view-and-json-data-using-ajax-in-Asp-Net/
public JsonResult BooksByPublisherId(int id)
{
IEnumerable<BookModel> modelList = new List<BookModel>();
using (DAL.DevelopmentEntities context = new DAL.DevelopmentEntities())
{
var books = context.BOOKs.Where(x => x.PublisherId == id).ToList();
modelList = books.Select(x =>
new BookModel()
{
Title = x.Title,
Author = x.Auther,
Year = x.Year,
Price = x.Price
});
}
return Json(modelList,JsonRequestBehavior.AllowGet);
}
javascript
$.ajax({
cache: false,
type: "GET",
url: "#(Url.RouteUrl("BooksByPublisherId"))",
data: { "id": id },
success: function (data) {
var result = "";
booksDiv.html('');
$.each(data, function (id, book) {
result += '<b>Title : </b>' + book.Title + '<br/>' +
'<b> Author :</b>' + book.Author + '<br/>' +
'<b> Year :</b>' + book.Year + '<br/>' +
'<b> Price :</b>' + book.Price + '<hr/>';
});
booksDiv.html(result);
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Failed to retrieve books.');
}
});
The reason why i am not getting the result was.. I forgot to add json2.js in the library
public class FoodController : Controller
{
[System.Web.Mvc.HttpGet]
public JsonResult getFoodDetails(int userId)
{
IList<Food> FoodList = new List<Food>();
FoodList = FoodService.getFoodDetails(userId);
return Json (FoodList, JsonRequestBehavior.AllowGet);
}
}
function GetFoodDetails() {
debugger;
$.ajax({
type: "GET",
url: "Food/getFoodDetails",
data: { userId: Id },
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
debugger;
alert(result)
},
error: function (response) {
debugger;
alert('eror');
}
});
}
Try This :
View :
[System.Web.Mvc.HttpGet]
public JsonResult getFoodDetails(int? userId)
{
IList<Food> FoodList = new List<Food>();
FoodList = FoodService.getFoodDetails(userId);
return Json (new { Flist = FoodList } , JsonRequestBehavior.AllowGet);
}
Controller :
function GetFoodDetails() {
debugger;
$.ajax({
type: "GET", // make it get request instead //
url: "Food/getFoodDetails",
data: { userId: Id },
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
debugger;
alert(result)
},
error: function (response) {
debugger;
alert('error');
}
});
}
Or if ajax request is creating problems then you can use $.getJSON as :
$.getJSON("Food/getFoodDetails", { userId: Id } , function( data ) {....});
$(document).ready(function () {
var data = new Array();
$.ajax({
url: "list",
type: "Get",
data: JSON.stringify(data),
dataType: 'json',
success: function (data) {
$.each(data, function (index) {
// alert("id= "+data[index].id+" name="+data[index].name);
$('#myTable tbody').append("<tr class='child'><td>" + data[index].id + "</td><td>" + data[index].name + "</td></tr>");
});
},
error: function (msg) { alert(msg); }
});
});
#Controller
public class StudentController
{
#Autowired
StudentService studentService;
#RequestMapping(value= "/list", method= RequestMethod.GET)
#ResponseBody
public List<Student> dispalyPage()
{
return studentService.getAllStudentList();
}
}

Sending my variable information to a url

I am using the following code to prepend information into my list and it is working fine. On top of that, I want to send the 2 variable below (listDescription and payment) to a url too as follows :
http://mywebsite.com/public/user/spent/?amount=listDescription&account=payment
I am trying to use ajax and send the information over with the following code but it is not working and I get no response alerts either way. Can I get some help on this please. Thanks.
$(document).ready( function() {
var listDescription;
var payment;
//prepending - working fine
$('#add_list').click( function() {
listDescription = $('#list_description').val();
payment = $('#payment').val();
$('.expense_list').prepend('<div>' + "\u00A3 " + listDescription + "\t\t\t" + payment + "\t" + '</div>');
//This is not working
$.ajax({
url: "htttp://mywebsite.com/public/user/spent/",
data: {
amount: listDescription,
account: payment
},
type: "GET",
async:true,
cache:false,
success: function (data) {
alert("success");
},
error: function (xhr, status, error) {
alert("error");
}
});
$('#list_form')[0].reset();
return false;
});
});
$(document).ready( function() {
//prepending - working fine
var listDescription = $('#list_description').val();
var payment = $('#payment').val();
$('#add_list').click( function() {
$('.expense_list').prepend('<div>' + "\u00A3 " + listDescription + "\t\t\t" + payment + "\t" + '</div>');
//This is not working
$.ajax({
url: "htttp://mywebsite.com/public/user/spent/",
data: {
amount: listDescription,
account: payment
},
type: "GET",
async:true,
cache:false,
success: function (data) {
alert("success");
},
error: function (xhr, status, error) {
alert("error");
}
});
$('#list_form')[0].reset();
return false;
});
});
This should work :)
May be try to add data type JSON in your AJAX Request?
dataType:'json',

Categories

Resources