Ajax success event doesn't fire - javascript

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

Related

AJAX: parameters is always null XML format

I have created a [WebMethod] in my server side as shown below:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Xml)]
public string ReadComments(string pagenum)
{
return pagenum;
}
and the ajax code:
function GetCommentItems() {
var pageTrack = $("input[id$='pageTrack']").val();
$.ajax({
url: "/_layouts/15/Load5MoreComments/CommentFetchSvc.asmx",
type: "POST",
dataType: "xml",
beforeSend: function (xhr) { xhr.setRequestHeader('SOAPAction', 'http://tempuri.org/ReadComments'); },
data: '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><ReadComments xmlns="http://tempuri.org"><pagenum>testStr</pagenum></ReadComments></soap:Body></soap:Envelope>',
contentType: 'text/xml; charset=utf-8',
success: function (msg) {
console.log(msg);
var newPageTrack = $("input[id$='pageTrack']").val();
$("input[id$='pageTrack']").val(parseInt(newPageTrack) + 1);
},
error: function (xhr, msg) {
console.log(msg + '\n' + xhr.responseText);
}
});
}
I am passing a testStr as a parameter but it goes always null.
I tried this processData: false, but did not work
Please help me!

JavaScript POST falls when connect to MVC controller

I'm new in MVC and trying to create a site for training.
I need to call a POST method in my controller through JavaScript.
This is my JavaScript method:
function ActivateAddStarAndRoleWithCategories(sender, args) {
var discID = $('#DiscID').val();
var starID = $('#StarID').val();
var desc = $("#Description").val();
var strID = "";
$(':checkbox').each(function () {
strID += this.checked ? this.id + "," : "";
});
strID = strID.substr(0, strID.length - 1);
$.ajax({
type: "POST",
url: 'CreateCategoriesID',
contentType: "application/json; charset=utf-8",
data: {
discID: discID,
starID: starID,
description: desc,
catID: strID
},
dataType: "json",
success: function () { alert("success!"); },
error: function () { alert("Fail!"); }
});
}
And this is my method in the controller:
[HttpPost]
public ActionResult CreateCategoriesID(string discID, string starID, string description, string catID)
{
entities.AddStarAndRoleAndCategories(int.Parse(starID), description, int.Parse(discID), catID);
return Json("OK", JsonRequestBehavior.AllowGet);
}
The view that activates the JavaScript function is already connected to the controller.
I always get error 500 - the server responded with a status of 500.
What am I doing wrong?
Thank you in advance!
I would go with the examples from the jQuery docs.
Did you try something like...?
$.ajax({
method: "POST",
url: "CreateCategoriesID", // Insert your full URL here, that COULD be the problem too
// This contentType is the default, so we can just ignore it
//contentType: "application/x-www-form-urlencoded; charset=UTF-8",
// I would also ignore the dataType unless your backend explicitly sends a JSON response header
//dataType: "json",
data: {
discID: discID,
starID: starID,
description: desc,
catID: strID
}
}).done(function(msg) {
alert('Success with message: ' + msg);
}).fail(function(jqXHR, textStatus) {
alert('Failed with status: ' + textStatus);
});

cannot get request from JQuery

I have auto complete input field, so I have done a function to retrieve data based on user request. I have tested the function with webform and it works fine, but when I tried to use api and send request to controller, the controller does not receive any request from JQuery?
JQuery:
$(document).ready(function () {
$("#auto").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "api/Employee/GetRe",
data: "{'term':'" + $("#auto").val() + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
});
controller:
[HttpGet]
public string GetRe(string term) {
var re = repository.GetCategory(term);
return re.First();
}
function:
[WebMethod]
public string[] GetCategory(string term)
{
List<string> retCategory = new List<string>();
connection();
string query = string.Format("select FirstName from Employee where FirstName Like '%{0}%'", term);
using (SqlCommand cmd = new SqlCommand(query, con))
{
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
retCategory.Add(reader.GetString(0));
}
}
con.Close();
return retCategory.ToArray();
}
}
and it shows this error
"No action was found on the controller 'Employee' that matches the
request ."}
You are formatting your JSON object as a string.
$(document).ready(function () {
$("#auto").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "api/Employee/GetRe",
data: {'term': $("#auto").val()},
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
});

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

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