Ajax in asp net core 5 Bad request 400 - javascript

I got error like "Failed to load resource: the server responded with a status of 400 ()" when i'm trying to run function ajax in javascript. What to do? Please, help me!
#page
#model IndexModel
#{
ViewData["Title"] = "Home page";
}
<div class="container">
<p id="scanned"></p>
</div>
<script type="text/javascript">
function Q(el) {
if (typeof el === "string") {
var els = document.querySelectorAll(el);
return typeof els === "undefined" ? undefined : els.length > 1 ? els : els[0];
}
return el;
}
var txt = "innerText" in HTMLElement.prototype ? "innerText" : "textContent";
var scannedQR = Q("#scanned");
var args = {
autoBrightnessValue: 100,
resultFunction: function (res) {
[].forEach.call(scannerLaser, function (el) {
fadeOut(el, 0.5);
setTimeout(function () {
fadeIn(el, 0.5);
}, 300);
});
scannedImg.src = res.imgData;
scannedQR[txt] = res.code;
UserCheckId();
}
};
function UserCheckId() {
$.ajax({
contentType: 'application/json; charset=utf-8',
crossDomain: true,
type: "POST",
dataType: "json",
url: '#Url.Action("UserCheckId", "Home")',
data: { qrcode: JSON.stringify(scannedQR[txt]) },
success: function (data) {
alert(data);
}
});
}
</script>
[HttpPost]
[AutoValidateAntiforgeryToken]
public ActionResult UserCheckId(string qrcode)
{
string result = qrcode;
return Json(result, System.Web.Mvc.JsonRequestBehavior.AllowGet);
}
i updated the code and showed where i am calling function "UserCheckId".

i found a solution.
I added below line in Startup.cs in Configure and it worked.
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});

Related

jQuery remove DropZone.js thumbnail after deleting file

We have more option into DropZone.js such as removedFile. In this Javascript script, I try to remove DropZone thumbnail after deleting file from server. Removing file from server works fine, but I can't detach thumbnails
<script type="text/javascript">
var DropzoneUp = function () {
var _componentDropzone = function () {
if (typeof Dropzone == 'undefined') {
console.warn('Warning - dropzone.min.js is not loaded.');
return;
}
// Multiple files
Dropzone.options.dropzoneMultiple = {
paramName: "file",
//...
params: {
prefixFile: '{{csrf_token()}}'
},
removedfile: function (file) {
jQuery.ajax({
//...
dataType: "json",
success: function (data) {
}
});
}
};
};
return {
init: function () {
_componentDropzone();
}
}
}();
DropzoneUp.init();
</script>
How can I do that and how can I remove thumbnails?
My problem solved by this code in success call back function:
removedfile: function (file) {
jQuery.ajax({
//...
type: "POST",
dataType: "json",
success: function (data) {
let _ref;
return (_ref = file.previewElement) != null ? _ref.parentNode.removeChild(file.previewElement) : void 0;
}
});
},

How can I get response ajax correctly?

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!

How to set serialization in Asp .Net Core

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

How To Load json Data To PivotTable.js in Mvc

I am using PivotTable.js
Run-time error and I do not know what is
[HttpGet]
public JsonResult DataResult ()
{
List<jsonList> list = new List<jsonList>();
for (int i = 0; i < 100; i++)
{
jsonList New = new jsonList();
New.Age = i;
if (i % 2 == 0)
{
New.Gender = "Female";
}
else
{
New.Gender= "Male";
}
New.Name= i.ToString();
New.Party = "NDP";
New.Province= "Quebec";
list.Add(New);
}
return Json(list, JsonRequestBehavior.AllowGet);
}
and View
JavaScript code snippet at the bottom
<link href="../../assets/PivotCss/pivot.css" rel="stylesheet" />
<div id="output"></div>
<script src="~/scripts/Pivote/jquery-1.8.3.min.js"></script>
<script src="~/scripts/Pivote/jquery-ui-1.9.2.custom.min.js"></script>
<script src="~/scripts/Pivote/**pivot.js**"></script>
<div id="output"></div>
<script>
$(document).ready(function () {
jQuery.ajax({
type: "Get",
url: "/ReportBuilder/DataResult",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: [],
success: function (data) {
alert(JSON.stringify(data));
$("#output").pivot(
JSON.stringify(data),
{
rows: ["Age"],
cols: ["Province", "Party"]
}
);
}
});
});
</script>
And Alert Result Json
And Firebug Error page
This error is that when run
Thanks for your kindness

How to use Jquery UI in my Custom Function? (Autocomplete)

I want to create a function to simplify configuration of jQuery UI AutoComplete. Here is my function code:
(function($) {
$.fn.myAutocomplete = function() {
var cache = {};
var dataUrl = args.dataUrl;
var dataSend = args.dataItem;
$.autocomplete({
source: function(request, response) {
if (cache.term == request.term && cache.content) {
response(cache.content);
}
if (new RegExp(cache.term).test(request.term) && cache.content && cache.content.length < 13) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
response($.grep(cache.content, function(value) {
return matcher.test(value.value)
}));
}
$.ajax({
url: dataUrl,
dataType: "json",
type: "POST",
data: dataSend,
success: function(data) {
cache.term = request.term;
cache.content = data;
response(data);
}
});
},
minLength: 2,
});
}
}) (jQuery);
but when I'm using this function like:
$("input#tag").myAutocomplete({
dataUrl: "/auto_complete/tag",
dataSend: { term: request.term, category: $("input#category").val() }
});
It's give me an error:
Uncaught ReferenceError: request is not defined
Perhaps the error is referring to request.term in
$("input#tag").myAutocomplete({
dataUrl: "/auto_complete/tag",
dataSend: { term: request.term, category: $("input#category").val() }
});
Sorry for the trouble, I'm not adept at using jquery. Here's the final working code.
(function($) {
$.fn.myAutocomplete = function(opt) {
var cache = {};
this.autocomplete({
source: function(request, response) {
if (cache.term == request.term && cache.content) {
response(cache.content);
}
if (new RegExp(cache.term).test(request.term) && cache.content && cache.content.length < 13) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
response($.grep(cache.content, function(value) {
return matcher.test(value.value)
}));
}
opt.dataSend.term = request.term;
$.ajax({
url: opt.dataUrl,
dataType: "json",
type: "POST",
data: opt.dataSend,
success: function(data) {
cache.term = request.term;
cache.content = data;
response(data);
}
});
},
minLength: 2,
});
return this;
}
}) (jQuery);
To use this function just write code like this:
$("input#tag").myAutocomplete({
dataUrl: "/auto_complete/tag",
dataSend: { category: $("input#category").val() }
});
Thanks Jeffery To for sharing with me to solve this problem.. ^_^

Categories