How to get data from C# Webmethod via AJAX statuscode? - javascript

I am developing a code to check whether a data already exist on the server or not. If there is a conflict, then the program must return status code 409. I can get the data returned by the webmethod via ajax.success. However, I cannot get the data via ajax.statusCode. It always returns error:
TypeError: data is undefined
I have tried this but I got an error
Non-invocable member "Content" cannot be used like a method
How do I get my object via ajax.statusCode?
C#:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static Case CreateNewCase(int id)
{
try
{
Case caseResponse = new Case();
//some process about checking if the ID exists and loading other data
if(idCount > 0)
{
HttpContext.Current.Response.StatusCode = 409;
return caseResponse;
}
else
{
HttpContext.Current.Response.StatusCode = 200;
return caseResponse;
}
}
catch (Exception ex)
{
HttpContext.Current.Response.StatusCode = 500;
return null;
}
}
JS:
function newCase() {
$.ajax({
url: 'Default.aspx/CreateNewCase',
data: JSON.stringify(
{id: ID }
),
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
statusCode: {
409: function (data, response) {
//how do I get the "data" from WebMethod here?
loadCase(ID, data);
//TypeError: data is undefined
}
},
success: function (data, status) {
loadCase(ID, data);
},
error: function (data) {
}
});
}

You can do like this. Use Web API instead of Web method and return HttpResponseMessage instead of case
public HttpResponseMessage CreateNewCase(int id)
{
try
{
Case caseResponse = new Case();
//some process about checking if the ID exists and loading other data
if(idCount > 0)
{
return Request.CreateResponse( HttpStatusCode.Conflict, caseResponse );
}
else
{
return Request.CreateResponse( HttpStatusCode.OK, caseResponse );
}
}
catch (Exception ex)
{
return Request.CreateResponse( HttpStatusCode.InternalServerError, null);
}
}

If you want to use the web method approach then change the ajax and try to parse the error in errro function as given below
function newCase() {
$.ajax({
url: 'Default.aspx/CreateNewCase',
data: JSON.stringify(
{id: ID }
),
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data, status) {
loadCase(ID, data);
},
error: function (jqXHR, textStatus, thrownError) {
if(jqXHR.status =="409" ){
var data= jqXHR.responseJSON;
loadCase(ID, data);
}
else
{
console.log(textStatus);
}
}
});
}

Related

Laravel Submitting form with same input name ajax

I need help with my ajax function. I have a form that submits data with the same input name
When I run my code without javascript, I can insert multiple input data with the same name,
Submitted structure
{"_token":"CepbQkKwKziSRwDJKuqlEa5i4E21Y5jvSbmDNvqu","id":"7","service_name":["asfd","safd"]}
When I implement javascript, a concatenated string is sent to the controller and this makes the service_name inaccessible.
formdata:"_token=CepbQkKwKziSRwDJKuqlEa5i4E21Y5jvSbmDNvqu&id=7&service_name%5B%5D=sdfg&service_name%5B%5D=gfds&_token=CepbQkKwKziSRwDJKuqlEa5i4E21Y5jvSbmDNvqu&id=8&_token=CepbQkKwKziSRwDJKuqlEa5i4E21Y5jvSbmDNvqu&id=9&_token=CepbQkKwKziSRwDJKuqlEa5i4E21Y5jvSbmDNvqu&id=10&_token=CepbQkKwKziSRwDJKuqlEa5i4E21Y5jvSbmDNvqu&id=11&_token=CepbQkKwKziSRwDJKuqlEa5i4E21Y5jvSbmDNvqu&id=18"
My javascript function
jQuery("form.ajax").on("submit", function (e) {
e.preventDefault();
jQuery.ajax({
url: "/admin/adminpanel/insertService/",
type: "post",
data: {
formdata: $(".ajax#servicesForm").serialize()
},
dataType: "JSON",
success: function (response) {
console.log(response);
},
error: function (jqXHR, exception) {
var msg = "";
if (jqXHR.status === 0) {
msg = "Not connect.\n Verify Network.";
} else if (jqXHR.status === 404) {
msg = "Requested page not found. [404]";
} else if (jqXHR.status === 500) {
msg = "Internal Server Error [500].";
} else if (exception === "parsererror") {
msg = "function Requested JSON parse failed.";
} else if (exception === "timeout") {
msg = "Time out error.";
} else if (exception === "abort") {
msg = "Ajax request aborted.";
} else {
msg = "Uncaught Error.\n" + jqXHR.responseText;
}
}
});
});
My PHP Controller Function
public function insert(Request $request)
{
return response()->json($request);
}
use FormData Object, to send fromdata
fd = new FormData();
fd.append("input-name", value1);
fd.append("input-name2", value2 OR arry of value);
jQuery.ajax({
url: "/admin/adminpanel/insertService/",
type: "post",
data: {
formdata: fd
}
I found a workaround:
First, I created an array, and pushed all instances of input[name='service_name[]'] into the array.
Then I passed the data with ajax and was able to insert the data.
var serviceArray = new Array(), id;
jQuery.map($("input[name='service_name[]']"), function(obj, index) {
serviceArray.push($(obj).val());
});
My ajax script then:
jQuery.ajax({
url: "/admin/adminpanel/insertService/",
type: 'post',
data: {
'service_name': serviceArray,
'id': id
},
dataType: 'JSON',
success: function(response) {
console.log(response);
}
});

Ajax POST returns undefined error from a ashx page

I keep receiving the undefined error. Here is the ajax method.
function testing() {
var data = JSON.stringify(
{
"TestID1": "12345",
"TestID2": "12345",
"TestID3": "12345",
});
$.ajax({
type: "POST",
url: "Test.ashx",
data: data,
//async: false,
//cache: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.ID);
},
error: function (jqXHR, textStatus, errorThrown) {
alert(jqXHR.status);
alert(textStatus);
alert(errorThrown);
}
});
}
Here is the controller/handler.
public void ProcessRequest(HttpContext context)
{
string jsonString = String.Empty;
HttpContext.Current.Request.InputStream.Position = 0;
using (StreamReader inputStream = new StreamReader(HttpContext.Current.Request.InputStream))
{
jsonString = inputStream.ReadToEnd();
JavaScriptSerializer jSerialize = new JavaScriptSerializer();
var receipt = jSerialize.Deserialize<Receipt>(jsonString);
if (receipt != null)
{
InsertData(receipt.TestID1, receipt.TestID1, receipt.TestID1);
var wrapper = new { ID = receipt.TestID1};
context.Response.Write(JsonConvert.SerializeObject(wrapper));
//context.Response.Write("{ \"data\": [1,2,3] }");
//context.Response.End();
}
}
}
public bool IsReusable
{
get
{
return false;
}
}
Right now I am getting undefined error, but I was getting the "JSON.parse: unexpected end of data at line 1 column 1 of the JSON data" until recently. The data that is being posted is working since the InsertData() function inserts the correct data. I also tried setting the async function in the ajax method to false, but no luck. Also, tried sending specific responses (like the one commented out) and so far none have succeeded.

Ajax call showing error cant debug

this is how the javascript looks like
<script type="text/javascript">
$(document).ready(function () {
$('#loginButton').click(function () {
//this.disabled = true;
debugger;
var data = {
"userid": $("#username").val(),
"password": $("#password").val()
};
$.ajax({
url: "/Account/LoginPost",
type: "POST",
data: JSON.stringify(data),
dataType: "json",
contentType: "application/json",
success: function (response) {
if (response.Success) {
$.get("#Url.Action("Search", "Home")", function (data) {
$('.container').html(data);
});
}
else
window.location.href = "#Url.Action("Index", "Home")";
},
error: function () {
alert('Login Fail!!!');
}
});
});
});
I am getting the alert('Login fail') also debugger not getting hit.
I am using jquery 1.9.1 and have included unobstrusive
my controller is this as you can i am passing string values not object values
to the controller so stringify is justified here
[HttpPost]
public JsonResult LoginPost(string userid, string password)
{
using (someentities wk = new someentities())
{
var LoginUser = wk.tblUsers.Where(a => a.Username.Equals(userid)&&a.Password.Equals(password)).FirstOrDefault();
if (LoginUser != null)
{
FormsAuthentication.SetAuthCookie(userid,false);
Session["Username"] = LoginUser.Username;
Session["Password"] = LoginUser.Password;
Session["Name"] = LoginUser.Name;
return Json(new { Success = true }, JsonRequestBehavior.AllowGet);
}
else
{
TempData["Login"] = "Please Enter Correct Login Details";
return Json(new { Success = false }, JsonRequestBehavior.AllowGet);
}
}
// If we got this far, something failed, redisplay form
}
when page is loading these error are shown
$(..) live is not a valid function in
(anonymous function) # jquery.unobtrusive-ajax.js:115
(anonymous function) # jquery.unobtrusive-ajax.js:163
take a look to the success function
success: function (response) {
if (response.Success) {
$.get("#Url.Action("Search", "Home")", function (data) {
$('.container').html(data);
});
}
else
window.location.href = "#Url.Action("Index", "Home")";
}
you are using multiple ", combine it with the single one ', this is a syntax error, try to check the code on an editor such as Atom, to avoid this kind of errors
Stringify converts an object to a string. Have you tried passing data an object instead of a string? Try replacing JSON.stringify(data), with data?

Dotnetnuke Call ajax from a module

I am now trying to build a dnn module using ajax calls. But there is a jquery error stating
SyntaxError: Unexpected token <
I have tried to work around with ajax "url: " and tried to create a new ascx at the root folder but still showing error 404.
My ajax call is as below
$.ajax({
url: "NewsManagement.ascx/Add",
contentType: "application/json; charset=utf-8",
dataType: "json",
method: "POST",
beforeSend: function () {
},
cache: false,
data: {
title : $('#txt_Title').val(),
news_content : $('#txt_Content').val(),
image : $('#file_Image').val(),
chapter_id : $('#sel_Chapter').val(),
is_draft : $('#chk_Draft').val(),
posted_date : $('#dp_PostDate').val(),
created_by : "",
lastupdate_by : ""
},
success: function (data) {
console.log(data);
if (data == "success") {
console.log(data);
}
else {
initMdlError("SERVER : " + data);
}
},
error: function (data, textStatus, error) {
// ERROR IS BEING CALLED FROM HERE
console.log("JQUERY JAVASCRIPT : " + error);
initMdlError(error);
},
complete: function () {
console.log('complete');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Is there any way to solve the issues?
The problem you're running into is that DNN isn't handling the requested URL properly that you are calling. If you want to call a service URL in DNN you're going to want to setup routes to handle the calls.
namespace Christoc.Com.Modules.SlidePresentation.services
{
public class SlidePresentationRouteMapper : IServiceRouteMapper
{
public void RegisterRoutes(IMapRoute mapRouteManager)
{
mapRouteManager.MapRoute("SlidePresentation", "{controller}.ashx/{action}",
new[] {"Christoc.Com.Modules.SlidePresentation.services"});
}
}
}
In the Controller you can define the methods available
[DnnAuthorize(AllowAnonymous = true)]
public ActionResult ListOfSlides()
{
try
{
var slides = Slide.GetSlides(ActiveModule.TabID, ActiveModule.ModuleID);
return Json(slides, JsonRequestBehavior.AllowGet);
}
catch (Exception exc)
{
DnnLog.Error(exc);
return Json(null, JsonRequestBehavior.AllowGet);
}
}
https://slidepresentation.codeplex.com/SourceControl/latest#DesktopModules/SlidePresentation/services/SlidePresentationController.cs
sample Javascript
//get slides on initialization
this.init = function(element) {
//var data = {}; //removed because we don't need this
//data.moduleId = moduleId; //removed because we don't need this when calling setModuleHeaders
//data.tabId = tabId; //removed because we don't need this
//serviceFramework.getAntiForgeryProperty(); //removed because we don't need this
$.ajax({
type: "POST",
cache: false,
url: baseServicePath + 'ListOfSlides',
//data: data,
//dataType:"json",
beforeSend: serviceFramework.setModuleHeaders
}).done(function(data) {
viewModel.slides = ko.utils.arrayMap(data, function(s) {
return new slide(s);
});
ko.applyBindings(viewModel);
$(element).jmpress();
}).fail(function () {
Console.Log('Sorry failed to load Slides');
});
};
Here's an example module that does this
https://slidepresentation.codeplex.com/
And a user group video I did years ago on this module.
https://www.youtube.com/watch?v=hBqn5TsLUxA

To show JSON returned error message

I needs to show the Json returned message.
In the controller, an exception is thrown and caught in a catch block. I am returning the fault error message.
In Ajax, the success part always executes. But if it is an error from my webservice, I don't want to execute the normal; instead I want to show an error message.
How I can achieve this?
My code below:
Controller
[HttpPost]
public JsonResult DeleteClientRecord()
{
bool result = true;
try
{
result = ClientCRUDCollection.DeleteClient(deleteClientId);
}
catch (Exception ex)
{
return Json(ex.Message, JsonRequestBehavior.AllowGet);
}
return Json(new { result }, JsonRequestBehavior.AllowGet);
}
AJAX Call
$("#YesDelete").click(function () {
$.ajax({
type: "POST",
async: false,
url: "/Client/DeleteClientRecord",
dataType: "json",
error: function (request) {
alert(request.responseText);
event.preventDefault();
},
success: function (result) {
// if error from webservice I want to differentiate here somehow
$("#Update_" + id).parents("tr").remove();
$('#myClientDeleteContainer').dialog('close');
return false;
}
});
});
Please can anyone help me on this.
[HttpPost]
public JsonResult DeleteClientRecord()
{
bool result = true;
try
{
result = ClientCRUDCollection.DeleteClient(deleteClientId);
}
catch (Exception ex)
{
return Json(new { Success="False", responseText=ex.Message});
}
return Json(new { result }, JsonRequestBehavior.AllowGet);
}
to show error message, you should add error scope after success scope in AJAX call like this:
$("#YesDelete").click(function () {
$.ajax({
type: "POST",
async: false,
url: "/Client/DeleteClientRecord",
dataType: "json",
error: function (request) {
alert(request.responseText);
event.preventDefault();
},
success: function (result) {
// if error from webservice I want to differentiate here somehow
$("#Update_" + id).parents("tr").remove();
$('#myClientDeleteContainer').dialog('close');
return false;
}
error: function (xhr) {alert(JSON.parse(xhr.responseText).Message); }
});
});
add Response.StatusCode to the response
_httpContextAccessor.HttpContext.Response.StatusCode = StatusCodes.Status400BadRequest;

Categories