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?
Related
Hi ihave this input with type file with multiple select enabled.
i need to get the files from the file input and pass it to my webmethod but i'm getting none in my webmethod, i've read that prop return a list, i have this code in jquery
function post_RepAttach(){
var params = {
Ocap_no:$('#txtOcapNo').val(),
file_Name:$('#FileUpload1').prop("files")[0]
}
var files = $('#FileUpload1').prop("files")[0];
alert(files);
$.ajax({
type: 'POST',
contentType: 'application/json',
url: baseUrl + 'Create-OCAP.aspx/post_attachment_rep',
data: JSON.stringify(params),
dataType: 'json',
success: function (data) {
var response = data;
if (typeof callback != 'undefined') {
//hideLoadingGif();
//callback(response);
}
},
error: function (xhr, status, error) {
//hideLoadingGif();
console.log(xhr, status, error);
}
});
}
i have try this $('#FileUpload1').prop("files") remove the [0] but still no luck
and here's my webMethod
[WebMethod]
public static string post_attachment_rep(string Ocap_no, List<string> file_Name)
{
OcapDataAccess ODA = new OcapDataAccess();
bool result;
result = ODA.insert_reports(HttpContext.Current.Request.MapPath("~/OCAP/files/Reports/" + file_Name.ToString()), Ocap_no);
if (result == true)
{
return "1";
}
else
{
return "0";
}
}
but the file_Name count is zero even if i selected files
how can i achive it.
Hope you understand what i mean
var fileNames = $.map( $('#FileUpload1').prop("files"), function(val) { return val.name; });
and params is :
var params = {
Ocap_no:$('#txtOcapNo').val(),
file_Name:fileNames }
}
I am learning C# and jQuery AJAX. I'm currently having a problem where I cannot get Ajax to run correctly and I am not sure why.
Here is the error log:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
Here is my code:
HTML
<button class="btn btn-primary btn-edit" id="{{SubjectId}}" id1="
{{StudentId}}" >Edit</button>
JavaScript AJAX code:
$('.btn-edit').off('click').on('click', function () {
$('#editModal').modal('show');
var id = parseInt($(this).attr('id'));
var id1 = parseInt($(this).attr('id1'));
ExamsController.LoadDetail(id, id1);
});
LoadDetail: function (id, id1) {
$.ajax({
url: '/Exams/LoadDetail',
type: 'GET',
data: {
id : id,
id1 : id1
},
dataType: 'json',
success: function (response) {
console.log(response.status);
if (response.status == true) {
var data = response.data;
$('#txtSubjectName').val(data.Subject.SubjectName);
$('#txtStudentName').val(data.Student.StudentName);
$('#numScore').val(data.Score);
} else {
alert("Error!")
}
},
Error: function (err) {
console.log(err);
}
});
},
And ExamsController
[HttpGet]
public JsonResult LoadDetail(int id, int id1)
{
bool status = false;
Exam exam = new Exam();
exam = db.Exams.Find(id, id1);
status = true;
return Json(new
{
data = exam,
status = status
}, JsonRequestBehavior.AllowGet);
}
Internal server error means you have error in C# script, please double check error logs.
And also your code isnt cleanest, missing semi-colons.
Try add semi-colons, add name to function , and check error log, it can be useful, we can make better answer.
Maybe try this code with semi colon :) :
$('.btn-edit').off('click').on('click', function () {
$('#editModal').modal('show');
var id = parseInt($(this).attr('id'));
var id1 = parseInt($(this).attr('id1'));
ExamsController.LoadDetail(id, id1);
});
LoadDetail: function (id, id1) {
$.ajax({
url: '/Exams/LoadDetail',
type: 'GET',
data: {
id : id,
id1 : id1
},
dataType: 'json',
success: function (response) {
console.log(response.status);
if (response.status == true) {
var data = response.data;
$('#txtSubjectName').val(data.Subject.SubjectName);
$('#txtStudentName').val(data.Student.StudentName);
$('#numScore').val(data.Score);
} else {
alert("Error!");
}
},
Error: function (err) {
console.log(err);
}
});
},
Thanks!
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);
}
}
});
}
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
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;