Serialize (form) in Ajax with ImageField - javascript

I have a forms.ImageField in my model called Post. When I create an instance of it, I do it via Ajax, while posting serialized data with data=$(this).serialize() to my PostCreateAPIView, which is a generic API CreateView of Django REST Framework, but this method serializes data only and ignores my image.
Here's my code:
My CreateAPIView:
class PostCreateAPIView(generics.CreateAPIView):
serializer_class = PostModelCreateSerializer
permission_classes = [permissions.IsAuthenticated]
def perform_create(self, serializer):
print(self)
serializer.save(user = self.request.user)
My Form:
class PostModelCreateForm(forms.ModelForm):
content = forms.CharField(
label="",
help_text="",#text to help
widget=forms.Textarea( attrs={
'cols' : "50", #size
'rows' : "6", #size
'placeholder' : 'Votre publication',
'style' : 'resize : none'
}))
group = forms.ChoiceField(choices=USER_GROUPS, label='')
class Meta:
model = Post #we define the model
fields = [
"content",
"group",
"photo"
]
$(document.body).on("submit", ".post_form_class",function(event){
event.preventDefault();
this_ = $(this);
var formData = this_.serialize();
$.ajax({
method : "POST",
url : createPostUrl,
data : formData,
success : function(data){
},
error : function(data){
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id = 'post-form' class="post_form_class" method="POST" action="" enctype="multipart/form-data">
<input type='hidden' name='csrfmiddlewaretoken' value='6bgEU7jPVxXskBGJzP7KzSj9mz75k2dpSqG9Fn1kfghUeWQPTKCbm8JJc5za0ecl' />
<p></p>
<div id="div_id_content" class="form-group"> <div class="controls "> <textarea name="content" cols="50" rows="6" placeholder="Votre publication" style="resize : none" class="textarea form-control" required id="id_content">
</textarea> </div> </div> <div id="div_id_group" class="form-group"> <label for="id_group" class="control-label requiredField">
Group<span class="asteriskField">*</span> </label> <div class="controls "> <select name="group" class="select form-control" id="id_group"> <option value="1" selected>Département juridique</option> <option value="2">Département ingénieurs</option> <option value="3">Département Commerce</option> <option value="4">Nouveau</option>
</select> </div> </div> <div id="div_id_photo" class="form-group"> <label for="id_photo" class="control-label ">
Photo
</label> <div class="controls "> <input type="file" name="photo" class="clearablefileinput" id="id_photo" /> </div> </div>
<div class="row">
<div class='col-sm-2 '>
<input class="btn btn-primary submit_form" id="submit_form" type="submit" value="Publier"/>
</div>
<div class='col-sm-1 col-sm-offset-8 '>
<span class='post-chars-left' > </span>
</div>
</div>
</form>
N.B: I've tried formData = new FormData(this_); but I get this error:
TypeError: Argument 1 of FormData.constructor does not implement interface HTMLFormElement

Thanks to Luca, here is the answer:
$(document.body).on("submit", ".post_form_class",function(event){
event.preventDefault();
var formData = new FormData(this);
$.ajax({
method : "POST",
url : createPostUrl,
data : formData,
processData:false,
contentType:false,
success : function(data){
location.reload(true);
},
error : function(data){
console.log("ERROR:CH0x2 while fetching after creation form submit");
console.log("data :",data.status, data.statusText);
}
});
});

Related

How to Submit a Form by using a button at the same time click event on anchor link?

I have a from with button to submit it. Now i would like to pass same variables to another page to inset them in database. For that, i would like to pass the variables using an anchor link with GET with id's.
But how do it add an anchor link to the form where when i submit the form using the button the anchor link also gets triggered..
function splitAndResolve() {
var errorIds = [];
$('[name="error-selection-checkboxes"]:checked').each(function() {
errorIds.push($(this).val().split("-")[1]);
});
var taskVersion = 1;
if (errorIds.length > 0 && errorIds.length < $('[name="error-selection-checkboxes"]').length) {
var dataObj = {
'errorReportIdsToRemove': errorIds,
'user': 'user#mail.com'
};
var baseUrl = $(location).attr("href").substring(0, $(location).attr("href").lastIndexOf('/') + 1);
var splitTaskResponse = $.ajax({
url: "/task/3f2456c6b44c3b29c651f8d55c1bb34ac4da11bb6d605a00629e79f2a95c4a70/split",
type: "POST",
data: dataObj,
async: false,
error: function(xhr, status) {
if (xhr.status == 400) {
window.location.href = "/400";
alert("Failed resolving the task, please retry upon reload.");
} else {
window.location.href = "/500";
alert("Failed resolving the task, please retry upon reload.");
}
}
}).responseJSON;
var taskId = splitTaskResponse.newTaskId;
// We need to update the version without which version on the UI and the DB are different.
taskVersion = splitTaskResponse.currentTaskPostSplit.version;
window.open(baseUrl + taskId, '_blank');
}
dataObj = {
'taskResolutionStatus': $("#inputResolution").val(),
'taskResolutionStatusDetail': $("#inputResolutionDetail").val(),
'taskResolutionNote': $("#inputNotes").val(),
'changeset': $("#inputChangeset").val(),
'requiresReview': $("#requiresReviewCheckBox").is(':checked'),
'version': taskVersion
};
$.ajax({
url: "/task/3f2456c6b44c3b29c651f8d55c1bb34ac4da11bb6d605a00629e79f2a95c4a70",
type: "POST",
data: dataObj,
async: false,
error: function(xhr, status) {
if (xhr.status == 400) {
window.location.href = "/400";
alert("Failed resolving the task, please retry upon reload.");
} else {
window.location.href = "/500";
alert("Failed resolving the task, please retry upon reload.");
}
}
});
enableStatusDropdown();
return true;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="form-horizontal clearfix" onsubmit="return splitAndResolve()">
<div class="form-group">
<label for="changeset" class="col-sm-2 control-label">Changeset</label>
<div class="col-sm-10">
<input class="form-control" type="text" name="changeset" id="inputChangeset" readonly="">
</div>
</div>
<div class="form-group">
<label for="taskResolutionStatus" class="col-sm-2 control-label">Resolution</label>
<div class="col-sm-10">
<select class="form-control resolutionDropdown" name="taskResolutionStatus" id="inputResolution">
<option disabled="" selected="" value=""> -- Choose one -- </option>
<option value="ESCALATE">Escalate</option>
<option value="ALREADY_FIXED_IN_OSM">Already fixed in osm</option>
<option value="NOT_ENOUGH_INFORMATION">Not enough information</option>
<option value="NO_FIX_REQUIRED">No fix required</option>
<option value="FIXED">Fixed</option>
</select>
</div>
</div>
<div class="form-group" id="inputResolutionDetailDropdown">
<label for="taskResolutionStatusDetail" class="col-sm-2 control-label">Detail</label>
<div class="col-sm-10">
<select class="form-control resolutionDropdown" name="taskResolutionStatusDetail" id="inputResolutionDetail">
<option value="LOW_PRIORITY_AREA">Low priority area</option>
<option value="KNOWN_BUG">Known bug</option>
<option value="ERROR_BASED_ON_BAD_DATA">Error based on bad data</option>
<option value="TRUE_EXCEPTION">True exception</option>
</select>
</div>
</div>
<div class="form-group">
<label for="taskResolutionNote" class="col-sm-2 control-label">Notes</label>
<div class="col-sm-10">
<textarea class="form-control" name="taskResolutionNote" id="inputNotes" rows="3"></textarea>
</div>
</div>
<div class="form-group">
<label for="requiresReview" class="col-sm-2 control-label">Requires review</label>
<div class="col-sm-2">
<input class="form-control" name="requiresReview" type="checkbox" style="box-shadow: none" id="requiresReviewCheckBox">
</div>
</div>
<input id="taskResolutionButton" type="submit" class="btn btn-primary">
<button id="taskCancelButton" type="button" class="btn btn-default" onclick="hideResolutionOverlay()">Cancel</button>
</form>
<input id="taskResolutionButton" type="submit" class="btn btn-primary" onclick="$('#your_form_id').submit();>

how to autofill the form with ajax laravel?

I trying to autofill my form with cnic which i set as unique. If Cnic exists then all fields against the entered cnic with autofill. how i will do that? I have uploaded my form , jquery and controller. If you need more data to understand you can ask. I am getting data but form is not filling with ajax request. how to resolve this issue?
My form:
<form class="form" method="post" action="{{route('add.member')}}">
<input type="hidden" name="_token" value="{{csrf_token()}}">
<div class="row justify-content-md-center">
<div class="col-md-6">
<div class="form-body">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="name">Name</label>
<input type="text" id="name" class="form-control" placeholder="Enter Name" name="name" value="{{old('name')}}">
#if ($errors->has('name'))
<span style="color: red" class="help-block">{{ $errors->first('name') }}</span>
#endif
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="cnic">CNIC</label>
<input type="number" id="cnic" class="form-control" placeholder="Enter CNIC" name="cnic" value="{{old('cnic')}}">
#if ($errors->has('cnic'))
<span style="color: red" class="help-block">{{ $errors->first('cnic') }}</span>
#endif
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="mobile_number">Mobile Number</label>
<input type="number" id="mobile_number" class="form-control" placeholder="Enter Mobile Number" name="mobile_number" value="{{old('mobile_number')}}">
#if ($errors->has('mobile_number'))
<span style="color: red" class="help-block">{{ $errors->first('mobile_number') }}</span>
#endif
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="party_joining_year">Party Joining Year</label>
<input type="text" id="party_joining_year" class="form-control" placeholder="Enter Party Joining Year" name="party_joining_year" value="{{old('party_joining_year')}}">
#if ($errors->has('party_joining_year'))
<span style="color: red" class="help-block">{{ $errors->first('party_joining_year') }}</span>
#endif
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="qualification">Qualification</label>
<input type="text" id="qualification" class="form-control" placeholder="Enter Qualification" name="qualification" value="{{old('qualification')}}">
#if ($errors->has('qualification'))
<span style="color: red" class="help-block">{{ $errors->first('qualification') }}</span>
#endif
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="party_position">Party Position</label>
<input type="text" id="party_position" class="form-control" placeholder="Enter Party Position" name="party_position" value="{{old('qualification')}}">
#if ($errors->has('party_position'))
<span style="color: red" class="help-block">{{ $errors->first('party_position') }}</span>
#endif
</div>
</div>
</div>
<div class="form-group">
<label for="profession">Profession</label>
<input type="text" id="profession" class="form-control" placeholder="Enter Profession" name="profession" value="{{old('qualification')}}">
#if ($errors->has('profession'))
<span style="color: red" class="help-block">{{ $errors->first('profession') }}</span>
#endif
</div>
<div class="form-group">
<label for="district">District/Tahseel</label>
<input type="text" id="district" class="form-control" placeholder="Enter District" name="district" value="{{old('qualification')}}">
#if ($errors->has('district'))
<span style="color: red" class="help-block">{{ $errors->first('district') }}</span>
#endif
</div>
</div>
</div>
</div>
</form>
Ajax:
$("#cnic").focusout(function(e){
// alert($(this).val());
var cnic = $(this).val();
$.ajax({
type: "POST",
url: "{{route('get.all.fields')}}",
data: {'cnic':cnic},
dataType: 'json',
success : function(e) {
if(e===0){
$('.flash-message').html('Data not found');
$('#cnic').val('');
}
else {
$('.flash-message').html('');
r = $.parseJSON(e); //convert json to array
$('#name').autocomplete({
source: r.name,
}); //assign name value
$('#mobile_number').autocomplete({
source: r.mobile,
}); //assign email value
$('#party_joining_year').autocomplete({
source: r.party_joining_year,
}); //assign department value
$('#qualification').autocomplete({
source: r.qualification,
}); //assign department value
$('#party_position').autocomplete({
source: r.party_position,
}); //assign department value
$('#profession').val(r.profession).autocomplete({
source: r.profession,
}); //assign department value
$('#district').val(r.profession).autocomplete({
source: r.district,
}); //assign department value
$("#cnic").html(e);
}
}
});
});
</script>
My Controller:
public function getAllFields(Request $request)
{
$getFields = Member::where('cnic', $request->get('cnic'))->get(['name','mobile','party_joining_year','qualification','party_position','profession','district']);
return json_encode($getFields[0]['mobile']);
}
Route:
Route::post('/get_fields', 'MemberController#getAllFields')->name('get.all.fields');
In your controller you should be returning a proper JSON response
public function getAllFields(Request $request)
{
try {
$getFields = Member::where('cnic',$request->cnic)->first();
// here you could check for data and throw an exception if not found e.g.
// if(!$getFields) {
// throw new \Exception('Data not found');
// }
return response()->json($getFields, 200);
} catch (\Exception $e) {
return response()->json([
'message' => $e->getMessage();
], 500);
}
}
You shouldn't need to parse the json as
dataType: 'json'
will automatically expect JSON and the response variable will already be an object and you just need to map it like
$("#cnic").focusout(function(e){
// alert($(this).val());
var cnic = $(this).val();
$.ajax({
type: "POST",
url: "{{route('get.all.fields')}}",
data: {'cnic':cnic},
dataType: 'json',
success : function(data) {
$('#name').val(data.name);
$('#mobile_number').val(data.mobile);
$('#party_joining_year').val(data.party_joining_year);
...
},
error: function(response) {
alert(response.responseJSON.message);
}
});
});
You must read the laravel docs carefully. you don't need to get the inputs if you want a row from db.
The ->get() method returns an array of al the matched rows.
The ->first() method returns only the first row that matches the where clause.
So you must first correct the eloquent query. If you want to specify the columns that you want to retrieve from the database you must use the ->select method. But I don't see any reason to do that. so your controller must look like this:
public function getAllFields(Request $request)
{
$getFields = Member::where('cnic',$request->get('cnic'))->first();
return json_encode($getFields);
}
After that, you must decode the JSON array with jquery and add the values one by one.
$("#cnic").focusout(function(e){
// alert($(this).val());
var cnic = $(this).val();
$.ajax({
type: "POST",
url: "{{route('get.all.fields')}}",
data: {'cnic':cnic},
dataType: 'json',
success : function(e) {
if(e.length === 0){
$('.flash-message').html('Data not found');
$('#cnic').val('');
}
else {
$('.flash-message').html('');
r = $.parseJSON(e); //convert json to array
$('#name').val(r.name);
$('#mobile_number').val(r.mobile);
$('#party_joining_year').val(r.party_joining_year)
and so on...
$("#cnic").html(e); //-> I dont realy understand why you use this part of code?
}
}
});
});
Remember: you must get the fields from "r" object exactly by the name of database column that you retrieve the data.

Select change not works

I have PartialView
Here is code
<form>
<div class="form-group">
<label for="recipient-name" class="col-form-label">Выберите проект</label>
<select id="projectId" name="add_triangolazione" class="form-control">
</select>
</div>
<div class="form-group">
<label for="recipient-name" class="col-form-label">От:</label>
<input type="date" class="form-control" id="datefrom">
</div>
<div class="form-group">
<label for="recipient-name" class="col-form-label">До:</label>
<input type="date" class="form-control" id="dateto" placeholder="YYYY-MM-DD" data-date-split-input="true" >
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Наименование услуги:</label>
#Html.DropDownList("Service", null, "XXXX", htmlAttributes: new { #class = "form-control", #id = "serviceIdProject" })
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">График работы:</label>
<div>
<label for="message-text" class="col-form-label">С:</label>
<input type="time" class="form-control" id="workTime">
</div>
<div>
<label for="message-text" class="col-form-label">По:</label>
<input type="time"" class="form-control" id="workTimeTo">
</div>
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Количество:</label>
<textarea class="form-control" id="quantity"></textarea>
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Тариф:</label>
<textarea class="form-control" id="rate" readonly></textarea>
</div>
It loading into modal via script
Here is script code
$(document).on('click', '#addShow', function () {
ShowAndPopulate();
});
function ShowAndPopulate() {
$('#addProposalManager').load('/Manage/AddProposalManager', function () {
let email = $('#userId').text();
let getProposalsUrl = '/manage/populateprojects';
model = {
email: email
},
$.ajax({
url: getProposalsUrl,
data: JSON.stringify(model),
contentType: 'application/json; charset=utf-8',
type: 'POST',
dataType: 'json',
processData: false,
success: function (data) {
var list = data;
$.each(list, function (i, d) {
$('#projectId').append('<option value="' + d.Id + '">' + d.Name + '</option>');
});
}
})
});
}
Also in this field
#Html.DropDownList("Service", null, "XXXX", htmlAttributes: new { #class = "form-control", #id = "serviceIdProject" })
I need to do something on value change
So I wrote this code at script
$('#serviceIdProject').change(function () {
alert("Gotcha!");
// ServiceChange();
});
But when I change value, nothing happens.
Where can be my problem?
Thank's for help
Try using event delegation and also you seem to be using the wrong ID for the select:
$(document).on('change' , '#projectId' , function () {
alert("Gotcha!");
// ServiceChange();
});

Error 500 on return all in Laravel Controller

Hi I am trying to send form data using ajax to my controller in Laravel. In my controller I am trying to return $request->all() to see if the form data is present. I am getting an error 500 internal server error and I am not sure why. I have setup my Exceptions/Handler.php to receive errors and also checked the error log.
Here is my HTML and Ajax:
<div class="container">
<div class="row">
<h1>Create your post</h1>
<div class="form-group">
<label for="title">Title</label>
<input type="text" name="title" id="title" class="form-control">
</div>
<div class="form-group">
<label for="post">Post</label>
<textarea name="post" rows="8" cols="80" id="post" class="form-control"></textarea>
</div>
<div class="form-group">
<label for="image">Add image</label>
<input type="file" name="image" id="image" class="form-control">
</div>
<input type="submit" name="submit" value="Submit Post" id="submit" class="btn btn-primary">
</div>
</div>
<script>
$(document).ready(function(){
$("#submit").on("click", function(e){
e.preventDefault();
var formData = new FormData();
var fileData = $('#image').prop('files')[0];
var title = $('#title').val();
var post = $('#post').val();
formData.append('fileData', fileData);
formData.append('title', title);
formData.append('post', post);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr("content")
}
});
$.ajax({
url:'/post/create/create',
type: "POST",
data: {
formData: formData
},
dataType: 'json',
success:function(response){
toastr.success(response.response);
},
error: function(error){
toastr.error(error.error)
}
});
});
});
</script>
Here is my controller:
public function create(Request $request) {
$request->all();
return response()->json(['responseText' => 'Success!'], 200)
}
missing ;
public function create(Request $request) {
$request->all();
return response()->json(['responseText' => 'Success!'], 200); //<--here
}

JQuery serialize ajax loaded form

The serialize() function returns an empty string , This is my code :
Code to return form :
$.ajax({
url: 'api/form',
type: 'get',
crossDomain: true,
}).done(function(response){
fields = JSON.parse(response);
html = '';
$.each(fields, function(index,field){
html += field;
});
html += '<div class="btn-clear"></div><button class="btn payment">Pay</button></div>';
$("#cart-content").html(html);
}).fail(function() {
console.log('Failed');
});
Javascript code executed after user clicks payment button :
$("body").on('click','.payment',function() {
var frmData = $("#customer").serialize();
console.log(frmData);
});
But it log an empty string !!
The form after it's ajax loaded :
<form id="customer"><div class="form-group">
<label class="control-label">Full name</label>
<input name="name" class="form-control" type="text">
</div><div class="form-group">
<label class="control-label">E-mail</label>
<input name="email" class="form-control" type="text">
</div><div class="form-group">
<label class="control-label">Mobile</label>
<input name="mobile" class="form-control" type="text">
</div><div class="form-group">
<label class="control-label">Country</label>
<select id="country" name="country" class="form-control" type="text"><!-- countries ... --></select>
</div></form>
Try your serialize like this
$("#form").submit(function () {
var data = $('#form').serialize();
Use the form ID as the target. Here I used #form. Submit the form, serialize the forms inputs.

Categories