Django Manytomanyfield in Ajax Form - ajax

I implemented an Ajax CRUD. My Model has one ManyToMany field(category). If i choose only one item for this field everything will be good, but if choose multi items it shows form invalid error. Please tell me what should I do.
model.py:
class BusienssCategory(models.Model):
title = models.CharField(max_length=20, unique=True)
slug = models.SlugField(unique=True)
description = models.CharField(max_length=45)
def __str__(self):
return self.title
class BusienssProfile(models.Model):
title = models.CharField(max_length=20)
description = models.CharField(max_length=40)
category = select2.fields.ManyToManyField(BusienssCategory)
image = models.ImageField(upload_to=upload_image_path, null=True,
blank=True)
def __str__(self):
return self.title
form.py:
class BusinessForm(forms.ModelForm):
class Meta:
model = BusienssProfile
fields = ('title', 'category', 'shortDescription')
view.py:
def save_business_form(request, form, template_name):
data = dict()
form = BusinessForm(request.POST, request.FILES)
if request.method == 'POST':
if form.is_valid():
form.save()
data['form_is_valid'] = True
businesses = BusienssProfile.objects.all()
data['html_business_list'] = render_to_string('business/business_profile/partial_business_list.html', {
'businesses': businesses
})
else:
data['form_is_valid'] = False
context = {'form': form}
data['html_form'] = render_to_string(template_name, context,
request=request)
return JsonResponse(data)
ajax.js:
var saveForm = function() {
var form = $(this);
var data = new FormData($('form').get(0));
var categories = $("#id_category").val();
var featured = $('#id_featured').prop('checked');
var active = $('#id_active').prop('checked');
data.append("image", $("#id_image")[0].files[0]);
data.append("title",$("#id_title").val());
data.append("category", categories);
data.append("description",$("#id_Description").val());
$.ajax({
url: form.attr("action"),
data: data,
processData: false,
contentType: false,
type: form.attr("method"),
dataType: 'json',
success: function (data) {
if (data.form_is_valid) {
Command: toastr["success"]("The profile has been
deleted.", "Success");
}
else {
Command: toastr["error"]("Something has gone wrong!", "Failure")
}
},
error: function(XMLHttpRequest, textStatus, errorThrown, url) {
alert("Status: " + textStatus);
alert("Error: " + errorThrown);
}
});
return false;
};
I've already tested the form without Ajax and it doesn't show any error. I think something must be wrong in Multiselect return value.

Finally I solved the problem by using both of serializeArray and FormData together. I used Formdata to handle image field and serializeArray to serialize manytomanyField (and other fields). Here is my final js file:
var saveForm = function() {
var form = $(this);
serialData = form.serializeArray();
// We need to use FormData to upload image or file
var data = new FormData($('form').get(0));
data.append("image", $("#id_image")[0].files[0]);
var other_data = form.serializeArray();
$.each(other_data,function(key,input){
data.append(input.name,input.value);
});
$.ajax({
url: form.attr("action"),
data: data,
type: form.attr("method"),
dataType: 'json',
cache: false,
processData: false,
contentType: false,
success: function (data) {
...
}
return false;
};

Related

Why my controller not getting data from ajax

I'm new to this, I'm trying to get the data from an ajax query
This Is My Ajax
$('#insertfile').on('click',function() {
console.log('a');
var file = document.getElementById('files').files[0];
var name = document.getElementById('names').value;
if( $('#room-status-no').prop('checked') ) {
console.log("status: 1");
var status = 1;
} else {
var status = 0;
console.log("status: 0");
}
var id = document.getElementById('id').value;
let form = new FormData();
console.log(file);
form.append('file', file);
form.append('name', name);
form.append('status', status);
form.append('id', id);
form.append('_method', 'PATCH');
form.append('action', 'update_file');
console.log(id, name, status);
$.ajax({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
url: "{{ route('this is my route.update', 'update_file') }}",
type: "PATCH",
cache: false,
processData: false,
contentType : false,
dataType: 'json',
data: form,
beforeSend: function() {
$('body').append('<div id="spinnerLoading"><div class="sk-spinner sk-spinner-double-bounce"><div class="sk-double-bounce1"></div><div class="sk-double-bounce2"></div></div></div>');
},
This is my Controller
public function update(Request $request) {
$action = $request->action;
dd($request->all());
if($action == 'update_text'){
return $this->updatetextControl($request);
} else if($action == 'update_file') {
return $this->updateFileControl($request);
}
I'm trying to pass the form data to my laravel controller using dd($request->all());
I was unable to get any data in my controller, I'm not sure if my URL route is the problem or I cant have multiple update functions others thing in one controller, does anyone know a solution? it will be much appreciated, thanks

How submit captcha to the controller using ajax and form data

I have a form with some fields and file upload, rendering as a partial view using ajax in asp.net MVC. when submitting the form, I want to pass all the data to the controller. But if I use $("form").serialize(), it is not passing the selected file to the controller. So I am using formData() to pass the data to the controller. Till this point, everything works fine.
But after adding captcha using CaptchaMvc, it not reaching the controller. Even if I enter valid captcha, it is invalid in the controller.
This is how I send data to the controller using the ajax and formData
var data = new FormData();
var vidFile = null;
if ($("#FileUpload")[0].files.length > 0)
vidFile = $("#FileUpload")[0].files[0];
data.append("detail", $("#detail").val());
data.append("name", $("#name").val());
data.append("FileUpload", vidFile);
$.ajax({
url: "/home/submitData",
type: "POST",
contentType: false,
processData:false,
data: data,
success: function (response) {
if (response.success == true) {
} else {
}
}
});
Is there any way to pass the captcha as well to the controller?
Why can't you validate using different controller function, as follows:
At the time of submission, validate the captcha first, and depending on the result, call another controller function to submit data or show the error.
var submitData = function(){
var data = new FormData();
var vidFile = null;
if ($("#FileUpload")[0].files.length > 0)
vidFile = $("#FileUpload")[0].files[0];
data.append("detail", $("#detail").val());
data.append("name", $("#name").val());
data.append("FileUpload", vidFile);
$.ajax({
url: "/home/submitData",
type: "POST",
contentType: false,
processData:false,
data: data,
success: function (response) {
if (response.success == true) {
//Success
} else {
//Submission failed
}
}
});
}
var validateCaptcha = function(){
$.ajax({
url: "/home/validateCaptcha",
type: "POST",
data: $("form").serialize(),
success: function (response) {
if (response.success == true) {
submitData();
} else {
alert("Invalid Captcha entry");
}
}
});
}
$("form").submit(function(e){
validateCaptcha();
});

What happened when ajax call Action and nothing happen

I need to pass values to Controller for making a PDF.
I create a Var Filter with many data, and other variable with respective necessesary.
When I call Controller, nothing happen.
I'm NOT an expert in MVC and AJAX.
Can someone help me?
View JavaScript:
function GeneratePdfUsuarios() {
var Filter = {
Nombre: $("#F_Nombre").val(),
Cargo: $("#F_Cargo").val(),
Iniciales: $("#F_Iniciales").val(),
UserName: $("#F_Usuario").val(),
Email: $("#F_Correo").val(),
Enabled: $("#EstadosList").val(),
BirthDay_Since: $("#F_Fecha_Desde").val(),
BirthDay_to: $("#F_Fecha_Hasta").val(),
RoleName: $("#RolesList").val(),
Sucursal: $("#SucursalesList").val()
};
var Title = "Usuarios";
var Description = "Listado de usuarios del sistema";
GeneratePdfList(1, Filter, Title, Description);
}
function GeneratePdfList(pDataCoType, pFilter, pTitle, pDescription) {
var token = $('[name=__RequestVerificationToken]').val();
var _data = {
DataCoType: pDataCoType //A number for Enumeration
, Filter: pFilter //An Object with Data
, Title : pTitle // Title for PDF
, Description: pDescription // Simple Description fpr Pdf
, __RequestVerificationToken: token
};
//ShowLoading();
$.ajax({
contentType: 'application/json; charset=utf-8'
,dataType: 'json',
url: "/Utility/GeneratePdfList",
type: 'POST',
data: _data,//JSON.stringify({ '_data': _data }),
success: function (data) {
if (data['success']) {
swal("Info","Entro","success");
//window.location.href = "#Url.Action("Usuarios", "Account")";
} else {
swal({
title: "Error!",
text: data['error'] + " !",
type: "warning",
timer: 100500,
allowOutsideClick: false,
allowEscapeKey: false,
showConfirmButton: true
});
swal("Peligro","Algo Fallo en el controlador "+e.Message,"warning");
//var message = document.createTextNode(data['error']);
//var p = $('#genericError')
//p.empty();
//p.append(message);
}
},
error: function () {
swal("Peligro", "Failed " + e.Message, "warning");
}
});
}
ActionResult in Controller:

Handling Django Model Form Error in Ajax Submit

I want to sumbit a model form with ajax and using model form validation messages:
class ComplaintForm(forms.ModelForm):
class Meta:
model = Complaint
fields = [
'title','body'
]
def clean_body(self):
form_data = self.cleaned_data
body = self.cleaned_data.get('body', False)
if len(body) < 2:
raise forms.ValidationError(u'Please Add Complaint')
return body
def clean(self):
cd = self.cleaned_data
return cd
In my view:
def forms(request):
form = ComplaintForm()
if request.method == "POST":
if request.is_ajax():
form = ComplaintForm(request.POST)
if form.is_valid():
c = form.save(commit=False)
c.user_ip = get_client_ip(request)
c.user = request.user
c.news = news
c.save()
data = serializers.serialize('json', [c,])
else:
data = json.dumps([v for k,v in form.errors.items()])
return HttpResponseBadRequest(data, mimetype='application/json')
return HttpResponse(data, mimetype='application/json')
else:
form = ComplaintForm()
return render_to_response('main/form.html', {'form': form},
context_instance=RequestContext(request))
But, my problem is how could I send data through HttpResponseBadRequest ?
My js is:
$('.complaintform').submit(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "/form/",
dataType: "json",
data: $(this).serialize(),
success: function(data) {
$('p').html('ok');
},
error: function(data) {
//how could i insert model form errors here?
}
});
});
Edited my answer. I misunderstood your question initially.
Try this:
$('.complaintform').submit(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "/form/",
dataType: "json",
data: $(this).serialize(),
success: function(data) {
$('p').html('ok');
},
statusCode: {
400: function() {
var items = [];
$.each( data, function( val ) {
items.push( val );
});
$('p').html(items.join(""));
}
}
});
});
If that doesn't work, a dirty workaround would be:
1) in the view:
else:
data = json.dumps([v for k,v in form.errors.items()] + ['failed'])
return HttpResponseBadRequest(data, mimetype='application/json')
2) in javascript:
success: function(data) {
if jQuery.inArray("failed", data) {
data.splice("failed", 1);
var items = [];
$.each( data, function( val ) {
items.push( val );
});
$('p').html(items.join(""));
} else {
$('p').html('ok');
}
},
That will work if, for some strange reason, jquery thinks your HttpResponse is 'success'.

Ajax Json calling MVC4 Controller Method Parameter Always Null

I am using Ajax with MVC4 web application. I've got a problem with passing values to action method. It's always pass the null as the parrameter value.
Here is my codes.
function onChange(arg) {
var adrId = $.map(this.select(), function (item)
{
return $(item).find('td').first().text();
});
GetEntries(adrId);//Calling the function
}
function GetEntries(adrId) {
//alert("AdrId >> "+adrId); here it shows value is 3465
$.ajax({
url: 'Customer/LoadCustomer',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ adrId: adrId }),
success: function (result) {
alert("success");
}
});
}
[HttpPost]
public JsonResult LoadCustomer(string adrId)//HERE value is ALLWAYS NULL.. :(
{
Address_SelectW adrList = new Address_SelectW();
adrList = this.commonObj.CustomersSelectByAdrKy(cky, usrKy, AdrKy);
return Json(adrList, JsonRequestBehavior.AllowGet);
}
Please help me to solve this problem. Thank you.. :)
===========================================================================
Additional Informations....
I have used another one to insert data. it's worked fine..
$("#btnSave").click(function () {
//var ContactID = $("#txtContactId").val();
var Company = $("#txtCompany").val();
var Status = $("#cmbStatus").val();
var IsActive = $("#IsActive").is(':checked');
var Comments = $("#txaComments").val();
var Country = $("#cmbCountry").val();
var Address1 = $("#txtAddress1").val();
//var Address2 = $("#txtAddress2").val();
var City = $("#txtCity").val();
var State = $("#txtState").val();
var PostalCode = $("#txtPostalCode").val();
var VatNo = $("#txtVatNo").val();
var RegNo = $("#txtRegNo").val();
var Phone = $("#txtPhone").val();
var Email = $("#txtEmail").val();
var AdrKey = $("#AdrID").val();
$.ajax({
url: "Customer/InsertCustomer",
data: {
//'ContactID': ContactID,
'Company': Company,
'Status': Status,
'IsActive': IsActive,
'Comments': Comments,
'Country': Country,
'Address1': Address1,
//'Address2': Address2,
'City': City,
'State': State,
'PostalCode': PostalCode,
'VatNo': VatNo,
'RegNo': RegNo,
'Phone': Phone,
'Email': Email
},
dataType: "json",
type: 'POST',
success: function (data) {
alert("Successfully Inserted!");
},
error: function () {
alert("error");
}
});
});
[HttpPost]
public ActionResult InsertCustomer(string Company, int Status, bool IsActive, string Comments, int Country, string Address1, string City, string State, string PostalCode, string VatNo, string RegNo, string Phone, string Email)
{
AdrCustomModel model = new AdrCustomModel();
bool process = false;
model.Company = Company;
model.Status = Status;
model.IsActive = IsActive;
model.Comments = Comments;
model.Country = Country;
model.Address1 = Address1;
model.City = City;
model.State = State;
model.PostalCode = PostalCode;
model.VatNo = VatNo;
model.Phone = Phone;
model.RegNo = RegNo;
model.Email = Email;
model.cky = cky;
model.ContactID = this.CustomerID(Status);
process = this.commonObj.InsertAdrCustomer(model,usrKy);
Accounts_Select accmodel = new Accounts_Select();
accmodel.CKy = cky;
accmodel.AccCd = model.ContactID;
accmodel.AccNm = Company;
accmodel.AccTypKy = this.commonObj.AccTypeKyByPrefixKy(Status);
process = this.commonObj.InsertAccount(accmodel, usrKy);
return Json(process, JsonRequestBehavior.AllowGet);
}
I have no idea about why this one is working fine and that one is not working. I have tried both JsonResult and ActionResult to Action method. And also tried with and without [HttpPost].
But always Parrameter value is NULL
I'm not sure if it will solve your problem but you can try this.
Place [WebMethod] attribute in your controller method.
or you can you can pass url with appended id like
'Customer/LoadCustomer'+ adrId
Put the property name in quotes:
data: JSON.stringify({ 'adrId': adrId }),
In your first example, you send a JSON object, in the second you just post data.
JSON is unnecessarily complicated to send just one value. Try this instead:
$.ajax({
url: 'Customer/LoadCustomer',
type: 'POST',
data: {'adrId': adrId },
dataType: 'json',
success: function (result) {
alert("success");
}
});
It required concatenate "" with the parameter which you wanna pass to Action method.
function GetEntries(adrId) {
var NewAdrId = ""+adrId; //<<<<<<<<<<<< Answer<<<<<<<<<<<<<<
$.ajax({
url: 'Customer/LoadCustomer',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ adrId: NewAdrId }),
success: function (result) {
alert("success");
}
});
}
// Thanks :)

Resources