I have an Ajax call to my controller action looks like this:
var m = $.ajax({
mtype: "GET",
url: '#Url.Action("GetBrandForValidation")',
data: { actionparameter: value },
async: false,
cache: false
});
As u can see i return actionparametter to my controller and controller have to return either true or false which has to be my "m" value, but i cant get it to work. Any ideas?
Controller Code:
public virtual JsonResult GetBrandForValidation(string actionparameter)
{
var vendorId = _service.GetVendorIdByUsername(GetUserName());
bool k;
var brands = _service.GetBrandsByVendor(vendorId);
var brand = new BrandsViewModel();
brand.BrandName = "Opret ny Brand...";
brands.Add(brand);
foreach (var brandsViewModel in brands)
{
if (brandsViewModel.BrandName == "Intet")
{
brandsViewModel.BrandName = "";
}
}
var list = brands.Select(s => s.BrandName);
if (list.Contains(actionparameter))
{
k = true;
}
else
k = false;
return Json(k,JsonRequestBehavior.AllowGet);
}
And full function code :
var checkBrands = function(value, colname) {
var m = $.ajax({
mtype: "GET",
url: '#Url.Action("GetBrandForValidation")',
data: { actionparameter: value },
async: false,
cache: false
});
if (m == true)
return [true, ""];
else
return [false, "Brand eksistere ikke"];
};
Im quite new and very awfull at javascript, so dont judge hard
Is the ajax call being made in JavaScript? If so, mtype should be type.
var checkBrands = function(value, colname) {
$.ajax({
mtype: "GET",
url: '#Url.Action("GetBrandForValidation")',
data: { actionparameter: value },
async: false,
cache: false,
success: function(data){
if(data == 'm'){
//do something
}else{
//do something
}
}
});
};
SOLVED
var checkBrands = function (value, colname) {
var m = $.ajax({
mtype: "type",
url: '#Url.Action("GetBrandForValidation")',
async: false,
cache: false,
data: { actionparameter: value }
}).responseText;
if (m == 'true'){
return [true, ""];
}
else return [false, "Brand eksistere ikke"];
};
Related
From the function django I return JSON to JS
paymentparking = paidparking.objects.filter(expirationdate__range=(startdate, enddate)).values('expirationdate','price')
return JsonResponse({'result': list(paymentparking)})
Here I need to get all the expirationdate values. How can this be done and how can the cycle be organized?
$.ajax({
type: "POST",
url: "statistics",
data: {
'startdate': finalDateStrStart,'enddate': finalDateStrEnd,
},
dataType: "json",
cache: false,
success:function (data) {
for (let i = 0; i < 100; i++)
{
console.log(data.result[i].expirationdate)
}
}
});
You could maybe do something like this:
success: function (data) {
if(data.result) {
for (let i = 0; i < data.result.length; i++) {
console.log(data.result[i].expirationdate)
}
}
}
Use Array.map() to iterate over elements and return an array of expirationdate.
success: function (data) {
data?.result && data.result.map(obj => console.log(obj.expirationdate));
}
I'm trying to send an ajax form to a controller, but the data attribute arrive empty to the controller, this is my code:
var fd = new FormData();
fd.append('asd', 123);
console.log(fd);
var idServicio = $("#id-building-form-add-new-stand").val();
var idEdificio = $("#id-service-form-add-new-stand").val();
var piso = $("#id-floor-form-add-new-stand").val();
var idJornada = $("#id-jornada-form-add-new-stand").val();
fd.append("idServicio", idServicio);
fd.append("idEdificio", idEdificio);
fd.append("piso", piso);
fd.append("idJornada", idJornada);
fd.append("jsonStand", JSON.stringify(jsonStand));
fd.append("accion", "1");
console.log(fd);
after I put my ajax code:
$.ajax({
method: "POST",
mimeType: "multipart/form-data",
url: epStand,
processData: false,
contentType: false,
data: fd,
success: function (statusM) {
//toggleModalCargando();
var data = JSON.parse(statusM);
if (data.status === 1) {
console.log("éxito");
$.unblockUI();
} else {
if (data.status === 0) {
$.unblockUI();
throwAlert(data.dataObject[0].message, "error");
} else {
$.unblockUI();
throwAlert(data.descripcion, "error");
}
}
}
});
However the fd variable is empty in all my logs console and of course in the controller.
JS:
function getJSON(){
$.ajax({
url: "getgroupednotification.json",
type: "GET",
crossDomain: true,
success:function(res){
$.each(res,function(index, value){
//console.log(res);
//console.log(value);
$.each(value.Notifications, function(index_, value_){
if(value.Source == 'CIRIS'){
var i = value.Notifications.length;
if(value_.ReadFlag != 1){
}
}
});
});
});
i want to get the notification.length if ReadFlag == 0. Im using Source == CIRIS for this example.
This is the link to my JSON
https://api.myjson.com/bins/navph
You could use something like this:
function getJSON() {
$.ajax({
url: "https://api.myjson.com/bins/navph",
type: "GET",
crossDomain: true,
success: function(res) {
var lens = res.filter(function(item) {
// filter by source
return item.Source === 'CIRIS';
}).map(function(item) {
// get only Notifications
return item.Notifications;
}).map(function(notification){
// get lengths of notifications which have at least 1 RedFlag not 0
return (notification.filter(function(item){
return item.RedFlag !== 0;
}).length)
})
console.log(lens[0]);
}
})
}
getJSON();
Facing error on JSON.stringify(ApplObj) :
How to post this object to controller
JQuery Code -
var ApplName = $("#ApplicantName").val();
var ApplMobile = $("#ApplicantMobile").val();
var ApplEmail = $("#ApplicantEmailId").val();
var ApplFHName = $("#ApplicantFHName").val();
var ApplObj = {
ApplicantName: ApplName, ApplicantMobile: ApplMobile, ApplicantEmailId: ApplEmail, ApplFHName: ApplicantFHName
}
$.ajax({
url: '#Url.Action("SaveApplicatDetail", "Dashboard")',
data: JSON.stringify(ApplObj),
dataType: 'json',
type: 'POST',
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data);
}
});
Controller Code...
this jsonresult used for save records and return value...
this code is working in other project....
public JsonResult SaveApplicatDetail()
{
try
{
var resolveRequest = HttpContext.Request;
TicketMasterModel TMM = new TicketMasterModel();
resolveRequest.InputStream.Seek(0, SeekOrigin.Begin);
string jsonString = new StreamReader(resolveRequest.InputStream).ReadToEnd();
if (jsonString != null)
{
TMM = (TicketMasterModel)js.Deserialize(jsonString, typeof(TicketMasterModel));
}
int TicketId = 0;
using (var db = new UnitOfWork())
{
DAL.tbl_TrnTicketMaster TM = new DAL.tbl_TrnTicketMaster();
TM.ApplicantName = TMM.ApplicantName;
TM.ApplicantMobile = TMM.ApplicantMobile;
TM.ApplicantEmailId = TMM.ApplicantEmailId;
TM.ApplicantFHName = TMM.ApplicantFHName;
TM.FK_CompanyId = 1;
TM.CustomerId = UserSession.UserId;
TM.IsSubmissionLocked = false;
TM.CreatedBy = UserSession.UserId;
db.tbl_TrnTicketMaster.Insert(TM);
TicketId = TM.PK_TicketId;
}
return Json(TicketId, JsonRequestBehavior.AllowGet);
}
catch (Exception)
{
throw;
}
}
basically JSON.stringify turns a Javascript object into JSON text and stores that JSON text in a string.
try this,
var ApplName = $("#ApplicantName").val();
var ApplMobile = $("#ApplicantMobile").val();
var ApplEmail = $("#ApplicantEmailId").val();
var ApplFHName = $("#ApplicantFHName").val();
var ApplObj = {
'ApplicantName': ApplName, 'ApplicantMobile': ApplMobile, 'ApplicantEmailId': ApplEmail, 'ApplFHName': ApplicantFHName
}
$.ajax({
url: '#Url.Action("SaveApplicatDetail", "Dashboard")',
data: JSON.stringify(ApplObj),
dataType: 'json',
type: 'POST',
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data);
}
});
Problem Resolved -
"JSON.stringify" is used array to convert it.
var ApplName = $("#ApplicantName").val();
var ApplMobile = $("#ApplicantMobile").val();
var ApplEmail = $("#ApplicantEmailId").val();
var ApplFHName = $("#ApplicantFHName").val();
var ApplDetails = {
ApplicantName: ApplName,
ApplicantMobile: ApplMobile,
ApplicantEmailId: ApplEmail,
ApplicantFHName: ApplFHName
}
var ApplObj = { ApplicantDetail: ApplDetails };
$.ajax({
url: '#Url.Action("SaveApplicatDetail", "Dashboard")',
data: JSON.stringify(ApplDetails),
dataType: 'json',
type: 'POST',
contentType: "application/json; charset=utf-8",
success: function (data) {
}
});
I want to find a way,give a dom as parameter and get data, from image_preview.
and separate image_preview.model() and image_preivew.on_chage() is event handler
make image_preview reusable not hardcode inside
I espect I will call image_preview pass dom in parameter, and return src as response , then I can use repsponse do something like append ...
var image_preview = {
on_change: function(wrap_dom, input_dom) {
$(wrap_dom).on('change', input_dom, function(event) { // I have to use on change because there are possible the `input dom` is new append...
var el_obj = $(this)[0];
var form_data = new FormData();
var file_length = el_obj.files.length;
for (var i = 0; i < file_length; i++) {
form_data.append("file[]", el_obj.files[i]);
}
image_preview.model(form_data).done(function(response) {
// console.log(response); // this is work
return response;
});
});
},
model: function(form_data) {
return $.ajax({
url: uri_public+'/admin/ajax/preview_file',
type: 'POST',
data: form_data,
processData: false,
contentType: false,
// async: false
});
}
}
var app_thumbnail = {
preview_controller: function() {
var wrap_dom = '.thumbnail';
var input_dom = '.upload-form input';
var result = image_preview.on_change(wrap_dom, input_dom);
// pass result to render view like append dom....
},
render: function() {
},
}
app_thumbnail.preview_controller();
Here is the easiest thing you can do:
var image_preview = {
on_change: function(wrap_dom, input_dom) {
$(wrap_dom).on('change', input_dom, function(event) {
var el_obj = $(this)[0];
var form_data = new FormData();
var file_length = el_obj.files.length;
for (var i = 0; i < file_length; i++) {
form_data.append("file[]", el_obj.files[i]);
}
image_preview.model(form_data).done(function(response) {
app_thumbnail.preview_controller(response);
});
});
},
model: function(form_data) {
return $.ajax({
url: uri_public+'/admin/ajax/preview_file',
type: 'POST',
data: form_data,
processData: false,
contentType: false,
// async: false
});
}
}
var app_thumbnail = {
preview_controller: function(response) {
var wrap_dom = '.thumbnail';
var input_dom = '.upload-form input';
var result = response;
}
}
// If you want to initialize it.
// image_preview.on_change(..., ...);