500 error coming when I run my ajax function - javascript

I am new to MVC and trying out the ajax functionality on my website. Whenever, I run my ajax function it returns 500 in alert.
This is my controller code
[HttpPost]
public ActionResult JsonNewsfeed(int id)
{
var db = new dekhosaleEntities1();
sale s = db.sales.First(m => m.sale_id == id);
List<sale> sale1 = db.sales.ToList();
saleviewmodel model = new saleviewmodel
{
currentsale = s,
Sales = sale1
};
return Json(model);
}
This is my Jquery ajax function
$('.b1').click(function () {
$.ajax({
type: "POST",
dataType: 'json',
url: '#Url.Action("JsonNewsfeed", "Home")',
data:"{ id: 5}",
success: function (data) {
alert(data);
},
error: function (response) {
alert(response.status);
}
});
});

public ActionResult JsonNewsfeed(int id)
{
try
{
....logic here....
return Json(data, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
//TODO: log exception
return new HttpStatusCodeResult(401, ex.Message);
}
}
you could also return like this instead:
return Content(jsonObject.ToString(), "application/json");
or
return Content("Your message",...
Then in your ajax call change the success to:
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "/someDir/someAjaxControllerMethod",
data: jStr,
success: function (json) {
...do something...
var s = JSON.stringify(json);
alert(s);
},
error: function (event) {
alert(event.statusText);
}
});

Try to correct you ajax request ...
like URL...(url: 'Url.Action("JsonNewsfeed", "Home")')
data (data: {id:id}) (if needed check that too)
here is the reference..
Documentation: http://api.jquery.com/jquery.ajax/

Related

ajax success response change as #html.raw

I have following jquery code in my Razor viewpage
$(document).ready(function () {
var grouplistvalues = #Html.Raw(Json.Encode(Session["grouplist"]));
$("#nsline").click(function () {
alert(grouplistvalues)
$.ajax({
type: "POST",
url: "SetupGroups",
data: { grouplist : grouplistvalues },
dataType: "html",
success: function (response)
{
grouplistvalues = null;
grouplistvalues = response;
alert(response)
},
error: function ()
{
}
});
});
$("#ewline").click(function () {
$.ajax({
type: "POST",
url: "SetupGroups",
data: { grouplist : grouplistvalues },
dataType: "html",
success: function (response)
{
grouplistvalues = null;
grouplistvalues = response;
},
error: function ()
{
}
});
});
in above grouplistvalues its taking session as html raw
when I alert it on #nsline click function I can see it,
in above function I'm calling to ajax function and above grouplistvalues value updating
once I alert it on #nsline click function success response I can see a alert like folllowing
since this(grouplistvalues value) 1,2,.. changing as [1,2..] I cannot call to other ajax function in #ewline click function since parameter difference,
this is the above common ajax call
[HttpPost]
public JsonResult SetupGroups(long[] grouplist)
{
Session["grouplist"] = null;
List<long> groupList = new List<long>();
foreach (var groupitem in grouplist)
{
groupList.Add(groupitem);
}
long[] grouparray = groupList.ToArray();
Session["grouplist"] = grouparray;
return Json(grouparray);
}
}
Though I have two click functions its work with only the first click(ewline or nsline only the first time)
How to solve this
It was the dataType in your ajax request. It should be json:
dataType: "json"

Web service receiving null with jQuery post JSON

The web service on http://localhost:57501/api/addDatabase has the following code.
[System.Web.Mvc.HttpPost]
public ActionResult Post(addDatabase pNuevaConeccion)
{
pNuevaConeccion.insertarMetaData();
return null;
}
The Ajax function is on a javascript that creates the JSON from the give values on http://localhost:1161/CreateServer.
$(document).ready(function ()
{
$("#createServer").click(function (e) {
e.preventDefault(); //Prevent the normal submission action
var frm = $("#CreateServerID");
var dataa = JSON.stringify(frm.serializeJSON());
console.log(dataa);
$.ajax({
type: 'POST',
url: 'http://localhost:57501/api/addDatabase/',
contentType: 'application/json; charset=utf-8',
crossDomain: true,
//ContentLength: dataa.length,
data: dataa,
datatype: 'json',
error: function (response)
{
alert(response.responseText);
},
success: function (response)
{
alert(response);
if (response == "Database successfully connected") {
var pagina = "/CreateServer"
location.href = pagina
}
}
});
});
});
When I run this code an alert pops up saying "undefined" but if I delete the contentType the alert doesn't show up. The problem is that the variables that the function Post (from the web service) receives are NULL even though I know that the JSON named dataa is not NULL since I did a console.log.
I have seen various examples and pretty much all of them say that I should use a relative URL but the problem is that since there are 2 different domains and when I tried it, it couldn't find the URL since it's not in the same localhost.
Web service should return a JSON format instead of null. like below example.
public JsonResult Post()
{
string output = pNuevaConeccion.insertarMetaData();
return Json(output, JsonRequestBehavior.AllowGet);
}
try to use this code for calling the web method
$.ajax({
method: "POST",
contentType: "application/json; charset=utf-8",
data: dataa,
url: 'http://localhost:57501/api/addDatabase/',
success: function (data) {
console.log(data);
},
error: function (error) {
console.log(error);
}
});
its my old code.(ensure action parameter variable name and post variable name are same)
$('#ConnectionAddres_ZonesId').change(function () {
var optionSelected = $(this).find("option:selected");
var id = { id: optionSelected.val() };
$.ajax({
type: "POST",
url: '#Url.Action("GetParetArea", "Customers")',
contentType: "application/json;charset=utf-8",
data: JSON.stringify(id),
dataType: "json",
success: function (data) {
$('#ConnectionAddres_ParentAreaId').empty().append('<option value="">Select parent area</option>');
$.each(data, function (index, value) {
$('#ConnectionAddres_ParentAreaId').append($('<option />', {
value: value.Id,
text: value.Area
}));
});
},
});
});
public ActionResult GetParetArea(int id)
{
var parents="";
return Json(parents, JsonRequestBehavior.AllowGet);
}

How to get data from Ajax

I have a variable called sid which handle number of seat. I want to throw sid to TryJSON.aspx method test. then I wanna do manipulate data on method test then throw back the result to this ajax. but I have an error when I just try to throw sid
var sid = jQuery(this).attr('id');
console.log(sid);
$.ajax({
url: "TryJSON.aspx/test",
type: "POST",
data: JSON.stringify({ 'noSeat': sid }),
contentType: "application/json; charset=utf-8",
success: function (response) {
var arr = JSON.parse(response.d);
console.log(arr);
},
error: function () {
alert("sorry, there was a problem!");
console.log("error");
},
complete: function () {
console.log("completed");
}
});
this is my C# code to receive noSeat
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static string test(string noSeat)
{
// return noSeat;
//JavaScriptSerializer serializer = new JavaScriptSerializer();
// return new JavaScriptSerializer().Serialize(new { noSeat = noSeat });
}
I have try return only noSeat and also with Javascript serializer. but it has an error. it says
An attempt was made to call the method 'test' using a POST request, which is not allowed.
I have been tried
return "Success !!"
but it doesn't appear on console and still same error.
what's the matter ?
var sid = jQuery(this).attr('id');
console.log(sid);
$.ajax({
url: "TryJSON.aspx/test",
type: "POST",
data: JSON.stringify({ 'noSeat': sid }),
contentType: "application/json; charset=utf-8",
dataType:'json',
success: function (response) {
var arr = JSON.parse(response.d);
console.log(arr);
},
error: function () {
alert("sorry, there was a problem!");
console.log("error");
},
complete: function () {
console.log("completed");
}
});

Ajax Get Method Error

I have this javascript code, it must get a list of my viewmodel, but success function is not called, error function is called.
What is my error?
var id = 5;
var request = $.ajax({
url: "/ArizaTalep/Get_List?tid=" + id,
type: "POST",
dataType: "json",
data: "{}",
contentType: 'application/json; charset=utf-8',
success: function (data) { },
error: function (data) { alert("error!!") }
});
Controller:
public List<DURUM_HAREKET_ViewModel> Get_List(int tid)
{
DH_DataModel dmodel = new DH_DataModel();
var ll = dmodel.GetAll().Where(i => i.T_ID == tid).ToList();
return ll;
}
public ActionResult Get_List(int tid)
{
DH_DataModel dmodel = new DH_DataModel();
var ll = dmodel.GetAll().Where(i => i.T_ID == tid).ToList();
return Json(ll, JsonRequestBehavior.AllowGet);
}
Try modifying your action to:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Get_List(int tid)
{
DH_DataModel dmodel = new DH_DataModel();
var ll = dmodel.GetAll().Where(i => i.T_ID == tid).ToList();
return Json(ll);
}
and
var request = $.ajax({
url: "/ArizaTalep/Get_List",
type: "POST",
dataType: "json",
data: {tid: id},
contentType: 'application/json; charset=utf-8',
success: function (data) { },
error: function (data) { alert("error!!") }
});
Change Controller to:
public ActionResult Get_List(int tid)
{
DH_DataModel dmodel = new DH_DataModel();
var ll = dmodel.GetAll().Where(i => i.T_ID == tid).ToList();
return Json(ll, JsonRequestBehavior.AllowGet);
}
Explanation:
You need to return Json type to get it into your View Success function.

Server side method not getting called

From the below javascript code i am trying to call a serverside method, but serververside method is not getting called. I am using jquery, ajax
<script type="text/javascript" src="JquryLib.js"></script>
<script type="text/javascript" language="javascript">
function fnPopulateCities() {
debugger;
var State = $("#ddlState").val();
GetCities(State);
return false;
}
function GetCities(StateId) {
debugger;
var v1 = 'StateId: ' + StateId;
$.ajax(
{
type: "POST",
url: 'DropDownList_Cascade.aspx/PopulateCities',
data: '{' + v1 + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
if (result.status === "OK") {
alert('Success!!');
}
else {
fnDisplayCities(result);
}
},
error: function (req, status, error) {
alert("Sorry! Not able to retrieve cities");
}
});
}
</script>
This is my serverside method which i need to call.
private static ArrayList PopulateCities(int StateId)
{
//this code returns Cities ArrayList from database.
}
It is giving me the following error: 500 (Internal Server Error)
I cannot figure out what is wrong. please help!
Stack Trace:
[ArgumentException: Unknown web method PopulateCities.Parameter name: methodName]
use this script:
function fnPopulateCities() {
debugger;
var State = $("#ddlState").val();
GetCities(State);
return false;
}
function GetCities(StateId) {
debugger;
var data = {
'StateId': StateId
};
$.ajax({
type: "POST",
url: 'DropDownList_Cascade.aspx/PopulateCities',
data: JSON.stringify(data), // using from JSON.stringify is much better than to try stringify data manually
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
if (result.status === "OK") {
alert('Success!!');
}
else {
fnDisplayCities(result);
}
},
error: function (req, status, error) {
alert("Sorry! Not able to retrieve cities");
}
});
}
and this code for your code behind:
[System.Web.Services.WebMethod]
public static ArrayList PopulateCities(int StateId)
{
//this code returns Cities ArrayList from database.
}
Use this script
function GetCities(StateId) {
debugger;
var v1 = "{'StateId': '" + StateId+"'}";
$.ajax({
type: "POST",
url: 'DropDownList_Cascade.aspx/PopulateCities',
data: v1,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
if (result.status === "OK") {
alert('Success!!');
}
else {
fnDisplayCities(result);
}
},
error: function (req, status, error) {
alert("Sorry! Not able to retrieve cities");
}
});
}
and modify Code Behind
[System.Web.Services.WebMethod]
public static ArrayList PopulateCities(int StateId)
{
//this code returns Cities ArrayList from database.
}

Categories

Resources