Server side method not getting called - javascript

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.
}

Related

Ajax success event doesn't fire

Doing Okta Authentication on WebForms
The login works but the redirect part doesnt
I tried with void and to return json object/string but doenst work
if i delete contentType and dataType from ajax method the success event works but then i can't debbug the method and it wasn't doing what was suppose to do
My objective is at the end of the webmethod to redirect to SignedIn.aspx tried with this code but couldn't make it work either that's why im doing client side through ajax success method
HttpContext.Current.Response.Redirect("SignedIn.aspx");
Ajax:
function FormSubmit() {
$.ajax({
type: "POST",
url: "Example.aspx/Login",
data: "{hiddenSessionTokenField:'" + $('#hiddenSessionTokenField').val() + "'}",
dataType: "json",
async:false,
contentType: "application/json; charset=utf-8",
success: function (response) {
alert("Method Called Sucessfully" + response);
window.location.href = "http://localhost:8080/SignedIn.aspx";
},
error: function (response) {
alert("error " + response);
}
});
}
WebMethod
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static void Login(string hiddenSessionTokenField)
{
//var result = new { url = "http://localhost:8080/SignedIn.aspx" };
if (!HttpContext.Current.User.Identity.IsAuthenticated)
{
var properties = new AuthenticationProperties();
properties.Dictionary.Add("sessionToken", hiddenSessionTokenField);
properties.RedirectUri = "~/SignedIn.aspx";
//Okta Authentication
HttpContext.Current.GetOwinContext().Authentication.Challenge(properties,
OpenIdConnectAuthenticationDefaults.AuthenticationType);
//System.Web.Script.Serialization.JavaScriptSerializer s = new System.Web.Script.Serialization.JavaScriptSerializer();
//return s.Serialize(result));
}
//return s.Serialize(result));
}
$('#test').on('click', function () {
$.ajax({
type: "POST",
url: "TEST.aspx/Login",
data: "{hiddenSessionTokenField:'" + $('#hiddenSessionTokenField').val() + "'}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
// alert("Method Called Sucessfully");
window.location.href = "http://localhost:8080/index.aspx";
},
error: function (response) {
alert("error " + response);
}
});
})
public static void Login(string hiddenSessionTokenField) {
int x = 0;
}

ajax send 2d array to action method error - asp.net mvc

i want to send 2d array from javascript file to action method.
My javascript function
function _tbdata() {
var dataarr = [];
for(var i = 0; i<svarr.length; i++)
{
var trangthai = $("input[name='" + svarr[i] + "']:checked").val();
var lydo = $("#" + svarr[i]).val();
dataarr[i] = new Array(2);
dataarr[i][0] = trangthai;
dataarr[i][1] = lydo;
}
$.ajax({
url: '/DiemDanh/testMethod',
data: { info: JSON.stringify(dataarr ) },
type: "POST",
traditional:true,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert('running');
},
error: function (data, textStatus) { alert(textStatus); }
});
}
And my controller
[HttpPost]
public ActionResult testMethod(List<List<string>> info)
{
return RedirectToAction("Index");
}
And when i debug in chrome, i got error
POST http://localhost:56602/DiemDanh/testMethod 500 (Internal Server
Error)
Sorry about my Enligsh is bad, Hope suggest from everybody!!!
I think you should change your javascript. Two dimensional array sholud be [[]]
I've write an example for your code. It works fine.
function Test() {
var dataarr = [[]];
for (var i = 0; i < 1; i++) {
dataarr[i][0] = "A" + i.toString();
dataarr[i][1] = "B" + i.toString();
}
var model = JSON.stringify(dataarr);
$.ajax({
url: '/Home/testMethod',
data: model,
type: "POST",
traditional: true,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert('running');
},
error: function (data, textStatus) { alert(textStatus); }
});
}
Change your ajax like this.
$.ajax({
url: '/DiemDanh/testMethod',
data: { info: JSON.stringify(ngay) },
type: "POST",
traditional:true,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert('running');
},
error: function (data, textStatus) { alert(textStatus); }
});
}
change your method parameter with string multi dimensional array it will work because list of list strings parameter won't work it'll not accepting 2d array
[HttpPost]
public ActionResult testMethod(string [][] info)
{
return RedirectToAction("Index");
}

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

500 error coming when I run my ajax function

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/

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

Categories

Resources