Im getting the following error on my Ajax post back {"readyState":0,"status":0,"statusText":"error"}
on my first ajax call but the second one returns data I want.
My C# method (UserSelect) JsonResults shows the data when I put break point
My C# code :
public IActionResult OnPostAreaSelect(string Id)
{
//Generating list for Areas
Guid ModelId = new Guid(Id);
List<ModelArea> modelAreas = _context.ModelArea.Distinct()
.Where(w => w.ModelId == ModelId).OrderBy(o => o.AreaColumn.Name).Include(i => i.AreaColumn).ToList();
return new JsonResult(modelAreas);
}
public IActionResult OnPostUserSelect(string Id)
{
//Generating list for Users
Guid ModelId = new Guid(Id);
List<UserModel> userModels = _context.UserModel
.Where(w => w.ModelId == ModelId).OrderBy(o => o.User.FullName)
.Include(i => i.User)
.ToList();
return new JsonResult(userModels);
}
My JavaScript :
<script type="text/javascript">
$(document).ready(function () {
$("#RepfocusModelDropdown").change(function () {
var Id = $(this).val();
if (Id != null) {
$.ajax({
async: true,
type: "POST",
url: "./Create?handler=UserSelect",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: {
Id: Id
},
crossDomain: true,
dataType: "json",
success: function (response) {
alert(JSON.stringify(response));
},
error: function (response) {
alert(JSON.stringify(response));
}
});
$.ajax({
type: "POST",
url: "./Create?handler=AreaSelect",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: {
Id: Id
},
dataType: "json",
success: function (response) {
alert(JSON.stringify(response));
},
error: function (response) {
alert(JSON.stringify(response));
}
});
}
})
})
The second ajax call on my script works fine only the first one returns the error
How can I solve the error
When you work with EntityFramework (or other ORM) there may be problems with serialization because an entity could have some circular references. To avoid this problem a solution is to set serialization settings:
services.AddMvc().AddJsonOptions(opt => {
opt.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});
or:
Newtonsoft.Json.JsonConvert.DefaultSettings = () => new Newtonsoft.Json.JsonSerializerSettings {
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
};
Related
I have a question is it possible to send two parameters from controller to Ajax for view?
I have two variables that store data
I need an optimal solution
I tried:
Controller:
[HttpGet]
public async Task<ActionResult> GetDepartmentAndManager(string userId)
{
var danePracownika = _uzytkownicyContext.Uzytkownicy
.Where(x => x.Id == IntIdCzlowieka)
.Select(s => new
{
UserDepartament = s.Departament,
UserManager = s.ManagerLogin
});
var userDetailsAU = _ecpContext.AC_Merge_V
.Where(x => x.Id == IntIdCzlowieka)
.Select(s => new
{
WymiarEtatu = s.WymiarEtatu,
NormaDzienna = s.NormaDzienna
});
return Json(danePracownika, userDetailsAU);
}
Ajax | javascript / View:
$.ajax({
url: "#Url.Action("GetDepartmentAndManager", "Uzytkownicy")",
type: "GET",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: {"userId": JSON.stringify(userId)},
cache: false,
success: function (data, user) {
$("#Id_department")
.dxTextBox("instance")
.option("value", data[0].UserDepartament);
$("#Id_manager")
.dxTextBox("instance")
.option("value", data[0].UserManager);
}
});
Return those values as properties on an object:
return Json(new { data = danePracownika, user = userDetailsAU });
Then in the response they will be properties on the result:
success: function (result) {
$("#Id_department")
.dxTextBox("instance")
.option("value", result.data[0].UserDepartament);
$("#Id_manager")
.dxTextBox("instance")
.option("value", result.data[0].UserManager);
// I assume you also want to use result.user somewhere...
}
enter code hereI have read several answers about this question, but no one works.
I have the following code but my HttpPostedFileBase[] array is always null.
The Other parameters has the right value, but the HttpPostedFileBase[] is always null.
What am i missing??
$('#myFile').on('change', function (e) {
var fileName = e.target.files[0].name;
archivosProcesar = new FormData();
for (var i = 0; i <= e.target.files.length -1; i++) {
archivosProcesar.append(i, e.target.files[i]);
}
});
function aplicarFragmentacion() {
var ids = obtenerAfiliadosSeleccionados();
var data = {
fragmento1: parseInt($('#fragmento1').val()),
fragmento2: parseInt($('#fragmento2').val()),
segmentos: ids,
archivos: archivosProcesar
}
if (!validarProcentajes() & !validarSeleccionados(ids)) {
$.ajax({
data: data,
url: urlAplicarFrag,
type: 'POST',
processData: false,
beforeSend: function () {
//$("#resultado").html("Procesando, espere por favor...");
},
success: function (data) {
onSuccessAplicarFragmentacion(data);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR.responseText);
onError(jqXHR.responseText);
}
});
}
}
Controller.cs
public async Task<ActionResult> AplicarFragmentacion(decimal fragmento1, decimal fragmento2, string[] segment\
os, HttpPostedFileBase[] archivos)
{
List<Credito> lstSegmentos = new List<Credito>();
try
{
ProgressHub.SendMessage("Iniciando proceso de fragmentación...", 10);
lstSegmentos = await FragmentacionNegocio.AplicarFragmentacion(fragmento1, fragmento2, segmentos)\
;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return Json(lstSegmentos, JsonRequestBehavior.AllowGet);
}
Try submitting a FormData object, not an anonymous object with a FormData field. Also it is my understanding that the contentType should be set to false.
var formData = new FormData();
formData.append('fragmento1', parseInt($('#fragmento1').val());
formData.append('fragmento2', parseInt($('#fragmento2').val());
formData.append('segmentos', obtenerAfiliadosSeleccionados());
formData.append('archivos', $('#fileupload')[0].files[0]);
$.ajax({
type: 'POST',
data: formData,
url: urlAplicarFrag,
type: 'POST',
processData: false,
contentType: false,
[...]
});
The fix was to use this plug in
https://jquery-form.github.io/form/
In this way
$(this).ajaxSubmit({
url: urlAplicarFrag,
data: {
fragmento1: parseInt($('#fragmento1').val()),
fragmento2: parseInt($('#fragmento2').val()),
segmentos: ids,
fechaReenvio: $('#fecha-reenvio').val()
},
success: function (data) {
onSuccessAplicarFragmentacion(data);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR.responseText);
onError(jqXHR.responseText);
}
});
check the plugin website
I use only kendo template in my website and use this js:
kendo.cdn.telerik.com/2015.2.805/js/kendo.all.min.js
but this file very very large size (2.102 KB). I want Appropriate kendo js file for this sulotion but I dont know:
my codes is:
<script>
function FillSpecificationAttr(attrId) {
var template = kendo.template($("#template").html());
var ID = attrId;
var dataSource = new kendo.data.DataSource({
type: "json",
transport: {
read: {
url: "../AjaxFunctionPages.asmx/ProductSpecAttrList",
type: "POST",
contentType: "application/json; charset=utf-8",
data: {
ID: ID
}
},
destroy: {
url: "../../AjaxFunctionsAdminPages.asmx/TierPriceDelete",
type: "POST",
contentType: "application/json; charset=utf-8",
data: {
ID: ID
}
},
parameterMap: function (data, operation) {
if (operation != "read") {
// web service method parameters need to be send as JSON. The Create, Update and Destroy methods have a "products" parameter.
return JSON.stringify({ ID: data.Id })
}
else if (operation == "destroy") {
}
else {
// web services need default values for every parameter
data = $.extend({ sort: null, filter: null }, data);
return JSON.stringify(data);
}
}
},
schema: {
data: "d.Data"
},
requestStart: function () {
kendo.ui.progress($("#tblConfigProduct"), true);
},
requestEnd: function () {
kendo.ui.progress($("#tblConfigProduct"), false);
},
change: function () {
$("#tblConfigProduct").html(kendo.render(template, this.view()));
}
});
dataSource.read();
};
</script>
I think the template is defined in kendo.core.min.js file which in version 2017.2.504 is only 54KB of size. You will still need jQuery library as a required dependency added in your document.
Demo
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'm sorry similar post is already there in the community, But i'm finding it strange. Its working fine but it affected my other views and not allowing other view pages to populate any dialogue boxes..
I tried to fix it by wrapping it in function() like this
$('#_auto').autocomplete(function(){
But, with this i'm not getting jason values in the _auto textfield and getting unexpected token error with following line.
can anyone help me to solve this please.
source: function(request,response){
this is my code:
$(function () {
$('#_auto').autocomplete({
selectFist: true,
minLength: 2,
source: function (request, response) {
var sval = $('#_auto').val();
//alert(sval);
$.ajax({
url: BASE_URL + '/controller/search/',
type: 'POST',
data: {
'term': sval,
},
dataType: 'json',
success: function (data) {
console.log(data);
var dta = [];
orgdetails = [];
//response(data.d);
for (var i in data) {
dta.push(data[i].name);
orgdetails[data[i].name] = data[i].id;
}
response(dta); //response(dta);
},
error: function (result) {}
}); //ajax
}
}).focus(function () {
$(this).trigger('keydown.autocomplete');
});
});
Many Thanks
I think the for loop should be
var dta = $.map(data, function(v, i){
orgdetails[v.name] = v.id;
return {
label: v.name,
id: v.name
};
});
Fiddle.
Another observation, You can get the current searched term using request.term rather than $('#_auto').val()
Complete code:
$('#_auto').autocomplete({
selectFist: true,
minLength: 2,
source: function (request, response) {
$.ajax({
url: BASE_URL + '/controller/search/',
type: 'POST',
data: {
'term': request.term,
},
dataType: 'json',
success: function (data) {
console.log(data);
orgdetails = {};
var dta = $.map(data, function(v, i){
orgdetails[v.name] = v.id;
return {
label: v.name,
id: v.name
};
});
response(dta); //response(dta);
},
error: function (result) {}
}); //ajax
}
}).focus(function () {
$(this).trigger('keydown.autocomplete');
});