How to put a alert error message in django form? - ajax

I have actually followed this tutorial to perform ajax request on error in form field.
Then I performed the following:
My models:
class Company(models.Model):
user = models.ForeignKey(User,related_name="Company_Owner",on_delete=models.CASCADE,null=True,blank=True)
name = models.CharField(max_length=50,blank=False)
books_begining_from = models.DateField(default=datetime.date(2018,4,1), blank=False)
gst_enabled = models.BooleanField(default=False)
composite_enable = models.BooleanField(default=False)
My views:
def validate_gst_billing(request):
data = {
'is_enable' : Company.objects.filter(gst_enabled = False,composite_enable = True)
}
if data['is_enable']:
data['error_message'] = 'To enable composite billing GST should be enabled'
return JsonResponse(data)
In my html:
<script>
$("#id_composite_enable").change(function () {
var form = $(this).closest("form");
$.ajax({
url: form.attr("data-validate-gst-billing-url"),
data: form.serialize(),
dataType: 'json',
success: function (data) {
if (data.is_enable) {
alert(data.error_message);
}
}
});
});
</script>
I want to throw an error message to the users as an alert if they try to submit a form with the gst_enable field set to False and the composite_enable field set to True.
Any idea what is wrong in my code?
Thank you

I think you should use error method in ajax like this :
$.ajax({
url: '/api/list',
success: function(data , textStatus ,jqXHR){
console.log(data)
},
error: function(jqXHR, textStatus, errorThrown){
console.log(textStatus)
console.log(errorThrown)
}
});
you can right click in your page select inspect element and in the console tab see your console log

For what I see, you are not setting any boolean on 'is_enable'. Add .exists() method to the queryset to get a boolean.
def validate_gst_billing(request):
data = {
'is_enable' : Company.objects.filter(gst_enabled=False, composite_enable=True).exists()
}
if data['is_enable']:
data['error_message'] = 'To enable composite billing GST should be enabled'
return JsonResponse(data)

Related

How can i get a value from the controller to my gsp page using AJAX

I am new to AJAX and grails so any help is appreciated. on my GSP page, on button click I am trying to retrieve a variable from the controller:
$.ajax({
url:'${createLink(controller: 'store', action: 'getNum')}',
type: 'GET',
dataType: 'json',
data: {num: num}, // the num is defined before and access properly
error: function() {
alert("error");
},
success: function(data) {
alert(data);
}
});
this is my controller function:
def getNum(){
String num = params.num
Long locnum = num as Long
int result = storeService.getNum(locnum)
String json = JsonOutput.toJson([count: result])
return json
}
I am going into the error and getting an "error" alert. I was wondering how I could utilize AJAX to get the number I need for my GSP page?
Thank you.
I would modify your JavaScript code like so:
$.ajax({
url:'store/getNum',
method: 'POST'
data: {'num': num}, // the num is defined before and access properly
error: function() {
alert("error");
},
success: function(data) {
alert(data);
}
});
And then modify your Grails controller code like so:
def getNum() {
Long locnum = = params.long('num')
int result = storeService.getNum(locnum)
return render([count: result] as JSON) // you will need to import grails.converters.JSON
}
A tip for the future is to set a breakpoint in your Grails controller method and run the application in Debug mode to ensure that the controller method is being called. If it is not being called, click on the Network tab on your internet browser's Developer Tools and then press the button on your GSP page to inspect the HTTP request being made by the AJAX call.

Vuejs post returns json data but wont assign to vues data object

Hey guys I am using vuejs and ajax to send formData and return a json response. There's a json response comes though however I cant assign it to the vue data object. Any ideas as to why? Heres my method. I know the function is firing as it hits the other page and returns json data in the console. Message, nameExists, and error wont assign even though all our in the vue data property and is spelled correctly.
addTemplate: function() {
this.sub = true;
this.itemName = this.itemName.trim();
var addTemplateForm = document.getElementById("addTemplateForm");
var fd = new FormData(addTemplateForm);
if (this.validItemName == true /* etc...*/) {
$.ajax({
url:'addTemplateBackend.php',
type:'POST',
dataType: 'json',
data: fd,
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
error: function(data){
this.message = data.message;
alert('error');
},
success: function(data){
alert('success');
this.error = data.error;
this.message = data.message;
console.log(data);
this.nameExists = data.nameExists;
if(data.success == true){
$('#successModal').modal('show');
}
}
});
}
}
You need to either bind this:
success: function (data) {
this.message = data.message;
}.bind(this)
or use ES6 "fat arrow" syntax:
success: data => {
this.message = data.message;
}
See How does the "this" keyword work?.

Ajax not returning desired results or not working at all

I have been trying to load return a JsonResults action from a controller in MVC using ajax call. I can see that the alert() function is triggering well but the ajax is not executing. I have search for several sources but to no avail.
public JsonResult FillBusinessLicenceL3(int? selectedID)
{
var bl3_Items = db.LevelThreeItems.Where(l3 => l3.LevelTwoItem_ID == selectedID);
return Json(bl3_Items, JsonRequestBehavior.AllowGet);
}
The below too is the javascript calling for the json method.
<script>
function FillBussLicence_L3items() {
alert("You have clicked me");
var bl2_Id = $('#BussLicenceL2_ID').val();
//alert(document.getElementById("BussLicenceL2_ID").value);
alert(bl2_Id);
$.ajax({
url: 'StartSurvey/FillBusinessLicenceL3/' + bl2_Id,
type: "GET",
dataType: "JSON",
data: "{}", // { selectedID : bl2_Id },
//contentType: 'application/json; charset=utf-8',
success: function (bussLicence_L3items) {
$("#BussLicenceL3_ID").html(""); // clear before appending new list
$.each(bussLicence_L3items, function (i, licenceL3) {
$("#BussLicenceL3_ID").append(
$('<option></option>').val(licenceL3.LevelThreeItem_ID).html(licenceL3.LevelThreeItem_Name));
});
}
});
}
Also, I have tried this one too but no execution notice.
Thanks a lot for your help in advance.
After looking through the browser's console, I noticed that the LINQ query was tracking the database and was creating a circular reference so I changed the query to the following and voila!!
public JsonResult FillBusinessLicenceL3(int? selectedID)
{
var bl3_Items = db.LevelThreeItems.
Where(k => k.LevelTwoItem_ID == selectedID).
Select(s => new { LevelThreeItem_ID = s.LevelThreeItem_ID, LevelThreeItem_Name = s.LevelThreeItem_Name });
return Json(bl3_Items, JsonRequestBehavior.AllowGet);
}
There was nothing wrong with the ajax call to the controller.

how to? with knockout js validations

I've started using knockout js validations with http://ericmbarnard.github.com/Knockout-Validation/ validation engine, and I'm not clear as to how to do the following:
1) Say I want to set a particular field required based on a condition. How do I do that?
e.g.
this.Username = ko.observable().extend({ required: true }); // make required = true only if this.UserType = 2, etc...
2) I've got the validation messages firing right next to the field being validated. I want only an '*' to appear next to the field and display the error messages in a validationsummary field at the bottom of the page. All validation errors should display there. How to do that?
3) The form submit to be avoided until the form validation is passed. Rightnow, I get the validation error messages, still the form gets submitted. So I guess I'm doing something wrong. Following is my code:
$(document).ready(function () {
var model;
// enable validation
ko.validation.init();
$.ajax({
type: "POST",
url: SERVER_PATH + '/jqueryservice/DataAccessService.asmx/GetData',
async: false,
data: "{ }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result, status) {
model = new ViewModel(result);
ko.applyBindings(model);
},
error: GetDataError
});
$('#submit').click(function () {
var data = ko.toJS(model);
delete data.Vehicles;
delete data.CopyWeeks;
delete data.SetupTotal;
delete data.CloseTotal;
var mappedItems = ko.utils.arrayMap(data.DailyItemList, function (item) {
delete item.Add;
delete item.Delete;
return item;
});
data.DailyItemList = mappedItems;
$.ajax({
type: "POST",
url: SERVER_PATH + '/jqueryservice/DataAccessService.asmx/ProcessData',
async: false,
data: ko.toJSON(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result, stat) {
alert(success);
return false;
},
error: function (e) {
alert(e);
}
});
});
});
Thanks in advance for your help.
EDIT:
I've seen that I can set the validation configuration as follows:
ko.validation.configure({
decorateElement : false,
errorMessageClass: 'errorMsg',
insertMessages : false,
parseInputAttributes : true,
messageTemplate: 'sErrorMsg'
});
ko.validation.init();
but I'm not sure how I can define my error message template 'sErrorMsg'
1). Say I want to set a particular field required based on a condition....
For this ko validation contains a native rule. You can do something like :
var myObj = ko.observable().extend({ required: {
onlyIf: function() {
//here you can place your codition and can return..
//true or false accordingly
}
}});
2). I've got the validation messages firing right next to the field being validated..
For this you should check Validation Binding. In this validationOptions can do the job for you.
Update: here's a fiddle which demonstrate the use of messageTemplate binding as per your requirement.
http://jsbin.com/ocizes/3/edit
3). The form submit to be avoided until the form validation is passed....
For this you can use use group , like :
yourViewModel.Errors = ko.validation.group(yourViewModel);
Now the Errors property contains the error messages of your observables, if any. So before submitting the form you can put check something like :
if(yourViewModel.Errors().length == 0) {
//submit the form
}
else {
yourViewModel.Errors.showAllMessages();
//this line shows all the errors if validation fails,
//but you can omit this.
}

Unable to receive json data in controller with knockout

I am new with knockout and mvc, so I need some help, my question is
my dropdown list is populating successfully from server, and on clicking save button calls Save method in controller. But problem is that in controller I am unable to receive json data i.e it is null. here is my code in view
var initialData = #Html.Raw( new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(Model));
var viewModel = function(){
var self = this;
self.HomeAgencies = ko.observableArray(initialData.HomeAgencies);
self.selectedOrgUnit = ko.observable();
self.Save = function () {
$.ajax({
url: "#Url.Action("Save")",
type: "POST",
data: ko.toJSON(this),
contentType: "application/json; charset=utf-8",
dataType:"json",
success: function(result) {alert(result.message)}
});
}
}
var vm = new viewModel();
ko.applyBindings(vm);
Where in controller i have following code
public JsonResult Save(string someData)
{
var message = string.Format("Saved {0} ", "successfully");
return Json(new { message });
}
string someData is always null, where I am expecting some json data.
Try to replace this to self in data and introduce field name and remove contentType.
$.ajax({
url: '#Url.Action("Save")',
type: 'POST',
data: { someData: ko.toJSON(self) },
dataType: 'json',
success: function (result) { alert(result.message); }
});
In your case context of the method can be changed from your object to html element that invoked them method or to window.
issue resolved. Problem was at controller side, in Action of controller pass the same model class instead parsing json manually.

Resources