Get response from c# code behind to javascript - c#

I am making jquery ajax call to post data on server and return response from whether completed successfully or not. But I am not able to see response in js.
js:
$.ajax({
url: 'ajaxExecute.aspx/CAO2',
data: strRequest,
dataType: "json",
contentType: "application/json",
cache: false,
context: document.body,
type: 'POST',
success: function (response) {
alert(response);
window.parent.$('#divDialog').dialog('close');
window.parent.$('#divDialog').dialog('destroy');
window.parent.$('#divDialog').html(response);
window.parent.$('#divDialog').attr('title', 'Error');
window.parent.$('#divDialog').dialog({ show: "blind", modal: true, dialogClass: 'alert', zIndex: 99999, resizable: false, draggable: false });
}
});
here i am not getting any alert but able to see response in Chrome -> Inspect Element -> Network -> Response
cs
[WebMethod]
public static void CAO2(string Guardian, string CIFID, string EmploymentType)
{
try
{
if (Guardian != "" && CIFID != "" && EmploymentType != "" )
{
if (Generix.putCustomerDetailsPart2(Guardian,CIFID,EmploymentType)) // Will Create SQL Query And Execute on Database
{
HttpContext.Current.Response.Write("Information Submitted Successfuly..!!<br/><br/>Please Visit Your Nearest Branch...");
}
else
{
HttpContext.Current.Response.Write("Error Occurred While Processing Information..!!<br/><br/>Please Try Again...");
}
}
else
{
HttpContext.Current.Response.Write("Missing Information..!!");
}
}
catch (Exception xObj)
{
HttpContext.Current.Response.Write("ERROR: " + xObj.Message);
}
}
where I am missing?

Use the reponseType as "json" and try response.d. Also add error function to find where exactly the problem occurs
$.ajax({
url: 'ajaxExecute.aspx/CAO2',
data: strRequest,
dataType: "json",
contentType: "application/json",
responseType:"json",
cache: false,
context: document.body,
type: 'POST',
success: function (response) {
alert(response.d);
},
error: function(xhr) {
alert(xhr.responseText);
}
});

Related

Web API is not working when calling through C# or jQuery ajax

Going crazy. The first call sets the session and the 2nd call gets the session. First 'Post' call return username and session id correctly but when I try to get the session, it returns blank with status code 200.
The same is the case with HttpClient (C#) code.
Both the call works perfectly if I try to set through browser or PostMan.
$.ajax({
url: "http://localhost:xxxx/xxxx/api/v1/session?username=xxxx&password=xxxx",
type: 'POST',
dataType: 'application/json',
success: function (result) {
$.ajax({
url: "http://localhost:xxxx/xxxx/api/v1/session",
type: 'Get',
dataType: 'application/json',
crossDomain: true,
success: function (result) {
debugger;
},
error: function (result) {
debugger;
}
});
},
error: function (result) {
debugger;
$.ajax({
url: "http://localhost:xxxx/xxxx/api/v1/session",
type: 'Get',
dataType: 'application/json',
crossDomain: true,
success: function (result) {
debugger
},
error: function (result) {
debugger;
}
});
}
});
The Get Request from Post Man
{"sessionId":"088BE3296B8778948F649A6B7B8C064B","userName":"user1"}
Am I missing anything?
Do note that Web-APIs are exposed by third party.
The problem is you have used the post method and trying to pass the data in query string.
function DoLogin() {
if (document.getElementById("Email").value == "" && document.getElementById("Password").value == "") {
document.getElementById("Email").focus();
toastr.error("Please enter email and password.");
}
else if (document.getElementById("Email").value == "") {
document.getElementById("Email").focus();
toastr.error("Please enter valid email address.");
}
else if (document.getElementById("Password").value == "") {
document.getElementById("Password").focus();
toastr.error("Please enter valid password.");
}
else {
document.getElementById("ButtonLogin").value = "Validating your account...";
document.getElementById("ButtonLogin").disabled = true;
var model = {
Email: $('#Email').val(),
Password: $('#Password').val()
}
$.ajax({
type: "POST",
data: JSON.stringify(model),
url: "#Url.Action("Login", "Account", null)",
contentType: "application/json"
}).success(function (res) {
var Type = res.type;
if (Type == "error") {
toastr.error(res.value);
document.getElementById("ButtonLogin").value = "login";
document.getElementById("ButtonLogin").disabled = false;
}
else {
window.location.href = res.returnUrl;
}
});
}
}
Usually, in the response for the POST request, there will be a Set-Cookie header.
You may need to pass the cookie in the GET request.

I have internal server error 500 when I tried to post json in Jquery ajax

When I try to send json JSON.stringify(coords); or above code I get error message but I try when the data is empty like data:{} the code works correctly. How can I solve this problem?
$.ajax({
type: "POST",
data: {"yagiz":"aabb"},
dataType: 'json',
url: url,
crossDomain:true,
async: false,
contentType: "application/json; charset=utf-8",
success: function (response) {
$("#Content").text(response.d);
console.log(response.d);
},
failure: function (response) {
alert(response.d);
console.log(response.d);
}
});
Web Method
[System.Web.Services.WebMethod]
public static string GetLocationPolygon(string location)
{
return location;
}
You can debug on server side as 500 internal error raised at server side only. You can catch and log the exact exception.
try this code
$.ajax({
type: "POST",
data: JSON.stringify({"location":"aabb"}), //Change here
dataType: 'json',
url: url,
crossDomain:true,
async: false,
contentType: "application/json; charset=utf-8",
success: function (response) {
$("#Content").text(response.d);
console.log(response.d);
},
failure: function (response) {
alert(response.d);
console.log(response.d);
}
});

Cannot get response in ajax success

My AJAX code is below. In this i cannot get the response from server side C# code. But there is no issues with my server side code ( I have checked it by debugging ). From server side i am returning string to this ajax.
$.ajax({
type: "POST",
url: '#System.Web.Configuration.WebConfigurationManager.AppSettings["BaseURL"]' +"provider/GetState",
contentType: 'application/json',
data: {CountryId: Country_Id },
success: function (data) {
alert(data);
}
});
Server side code is below
public string GetState(string CountryId)
{
int i= Convert.ToInt32(CountryId);
var Details = objUserAccount.SP_Getstate(i).ToList();
if(Details.Count>0)
{
return "Success";
}
else
{
return "False";
}
}
Add datatype in your ajax request like this, if datatype is not matched with received data from server then the ajax error will call instead of success
$.ajax({
type: "POST",
url: '#System.Web.Configuration.WebConfigurationManager.AppSettings["BaseURL"]'+ NSSCTProvider/GetState",
contentType: 'application/json',
dataType: "json",
data: {CountryId: Country_Id },
success: function (data) {
alert(data);
},
error: function(data){
alert("Error occured");
}
});
$.ajax({
type: "POST",
url: '#System.Web.Configuration.WebConfigurationManager.AppSettings["BaseURL"]'+ NSSCTProvider/GetState",
contentType: 'application/json',
data: {CountryId: Country_Id },
success: function (data) {
alert(data);
},
error: function(data){
alert("Error occured");
}
});
Either one of the success or failure call back will be initiated if the request is made from this snippet. Might be a server issue, most probably. And make sure that this is the code snippet getting executed. Happens to me all the time.

How to get number of hours/minutes JSON is running

I have a page that calls JSON API. It shows a loading image while processing. I need to check if it is more than 5 minutes running, then show an alert message. Can't find on Google. Thank you!
ADDED my code:
function SeeMyCoupon(list, func) {
CallLoadingPopup(true);
$.ajax({
url: "https://www.test.com/api/SeeMyCode.ashx",
global: false,
type: "POST",
data: list,
dataType: "json",
cache: false,
async: false,
success: function (data) {
if (func) {
func(data);
CallLoadingPopup(false);
}
}
});
}
You could try using the timeout property:
function SeeMyCoupon(list, func) {
CallLoadingPopup(true);
$.ajax({
url: "https://www.test.com/api/SeeMyCode.ashx",
global: false,
type: "POST",
data: list,
dataType: "json",
cache: false,
async: false,
timeout: 300000,
success: function (data) {
if (func) {
func(data);
CallLoadingPopup(false);
}
},
error: function(jqXHR, textStatus, errorThrown) {
if(textStatus === "timeout") {
alert('The operation took more than 5 minutes');
}
});
}
Also please note that setting async: false is a very bad design. This is not AJAX. You are blocking the client browser during the entire execution of the request. AJAX is meant to be asynchronous.

RedirectToAction is not working while authentication of mvc3 form with jquery

i have been facing an issue in my loginscreen of my application which is developed with mvc3 and jquery, as i am writing the code for checking login credentials in controller and and that controller event is firing by clciking the buttoon click which is developed using jquery. i would like to navigate someo other page('/Customer/CollaborationPortal') when the login credentials are correct, else i want display message box stating that "credentials are wrong" and this is my code.
JQuery Code
$("#btnGo").click(function (e) {
var RegData = getRegData();
if (RegData === null) {
console.log("Specify Data!");
return;
}
$.ajax(
{
url: '/Registration/IsLoginExsit',
type: 'POST',
dataType: 'json',
data: JSON.stringify(RegData),
contentType: 'application/json; charset=utf-8',
success: function (response) {
//window.location.href('/Customer/CollaborationPortal');
Console.Log("success");
error: function () {
//aler('Login error');
Console.Log("error");
}
}
});
});
function getRegData() {
var UserName = $("#txtUserName").val();
var Password = $("#txtPassword").val();
return { "UserName": UserName, "Password": Password };
}
});
Controller Code
public ActionResult IsLoginExsit(BAMasterCustomerDO loginData)
{
if (!string.IsNullOrEmpty(loginData.UserName) && !string.IsNullOrEmpty (loginData.Password))
{
bool result = Businesss.Factory.BusinessFactory.GetRegistration().IsLoginExist(loginData.UserName, loginData.Password);
if (result)
{
System.Web.HttpContext.Current.Session["UserName"]=loginData.UserName;
return RedirectToAction("/Customer/CollaborationPortal");
}
else
{
ViewData["message"] = "Registration failed";
return View();
}
}
return View();
}
and also it is not entering into "success" and "error" code.
Thanks in advance.
you have specified the error callback inside success callback, move it outside like:
$.ajax(
{
url: '/Registration/IsLoginExsit',
type: 'POST',
dataType: 'json',
data: JSON.stringify(RegData),
contentType: 'application/json; charset=utf-8',
success: function (response) {
//window.location.href('/Customer/CollaborationPortal');
console.log("success");
},
error: function () {
//alert('Login error');
console.log("error");
}
});
You have error function inside of success function....
This it's what you must have:
$.ajax(
{
url: '/Registration/IsLoginExsit',
type: 'POST',
dataType: 'json',
data: JSON.stringify(RegData),
contentType: 'application/json; charset=utf-8',
success: function (response) {
//window.location.href('/Customer/CollaborationPortal');
Console.Log("success");
},
error: function () {
//aler('Login error');
Console.Log("error");
}
});
If I were you, I'd return a JSON object to the client like this:
Success:
{
'error' : false,
'redirect' : '/Customer/CollaborationPortal',
'message' : ''
}
Error:
{
'error' : true,
'redirect' : false,
'message' : 'Please do this or that'
}
My jQuery would be:
$.ajax(
{
url: '/Registration/IsLoginExsit',
type: 'POST',
dataType: 'json',
data: JSON.stringify(RegData),
contentType: 'application/json; charset=utf-8',
success: function (response) {
if (response.error)
{
alert(response.message);
return;
}
window.location.pathname = response.redirect;
}
});

Categories