AJAX fails to get data from input - javascript

I am trying to create/insert data into the database, but I am still getting an error for getting the data I've input. I tried using the dump and die method, and I encountered that no data is being gotten from the data that has been input. What could be wrong with my codes?
Here is the result of the inspected element
Click to see image
My Modal
<div id="modalAddChild" class="modal fade" tabindex="-1" aria-labelledby="modalAddChild">
#csrf_field
{{ method_field('PUT') }}
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title"><b>Add Child</b></h4>
<button type="button" class="btn btn-sm btn-secondary" data-bs-dismiss="modal">X</button>
</div>
<div class="modal-body">
<p><i>Note: In Weight, it is required to put (.) regardless if it is (.0).</i></p>
<p><i>Note: In Height, do not add (.) if it is (.0) but it is allowed to put (.) if it's any number.</i>
</p>
<form id="saveChild" method="post">
<div class="form-group row">
<div class="col-sm-6">
<label for="mothersname">Mother's Name:</label>
<input type="text" class="form-control" id="mothersname" name="mothersname" required>
</div>
<div class="col-sm-6">
<label for="childsname">Child's Name:</label>
<input type="text" class="form-control" id="childsname" name="childsname" required>
</div>
</div>
<div class="form-group row">
<div class="col-sm-6">
<label>Indigenous:</label>
<select class="form-control" id="ind_id" name="ind_id" required>
<option value="">YES or NO</option>
#foreach ($indigenous as $key => $value)
<option id="{{ $key }}" value="{{ $key }}">{{ $value }}</option>
#endforeach
</select>
</div>
<div class="col-sm-6">
<label>Sex:</label>
<select class="form-control" id="sex_id" name="sex_id" required>
<option value="">M or F</option>
#foreach ($sex as $key => $value)
<option id="{{ $key }}" value="{{ $key }}">{{ $value }}</option>
#endforeach
</select>
</div>
</div>
<div class="form-group row">
<div class="col-sm-6">
<label>Date of Birth:</label>
<input type="text" class="form-control" id="birthdate" name="birthdate"
placeholder="YYYY-MM-DD" required>
</div>
<div class="col-sm-6">
<label>Actual Date of Weighing:</label>
<input type="text" class="form-control" id="actualdate" name="actualdate"
placeholder="YYYY-MM-DD" required>
</div>
</div>
<div class="form-group row">
<div class="col-sm-6">
<label>Weight(kg):</label>
<input type="text" class="form-control" id="weight" name="weight" required>
</div>
<div class="col-sm-6">
<label>Height(cm):</label>
<input type="text" class="form-control" id="height" name="height" required>
</div>
</div>
<div class="form-group row">
<div class="col-sm-6">
<label for="zone">Zone:</label>
<input type="text" class="form-control" id="zone" name="zone" required>
</div>
<div class="col-sm-6">
<label>Age in Months:</label>
<input type="text" class="form-control" id="ageinmonths" name="ageinmonths" required>
</div>
</div>
<div class="form-group">
<button type="submit" value="Submit" class="btn btn-flat btn-primary" id="saveBtn">Submit</button>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
My AJAX
<script type="text/javascript">
$('#saveChild').submit('click', function() {
var zone = $('#zone').val();
var mothersname = $('#mothersname').val();
var childsname = $('#childsname').val();
var ind_id = $('#ind_id').val();
var sex_id = $('#sex_id').val();
var birthdate = $('#birthdate').val();
var actualdate = $('#actualdate').val();
var weight = $('#weight').val();
var height = $('#height').val();
var ageinmonths = $('#ageinmonths').val();
var dataString="zone="+zone+"&mothersname="+mothersname+"&childsname="+childsname+"&ind_id="+ind_id+"&sex_id="+sex_id
+"&birthdate="+birthdate+"&actualdate="+actualdate+"&weight="+weight+"&height="+height+"&ageinmonths="+ageinmonths;
$.ajax({
type: "POST",
dataType: "JSON",
data: dataString,
url: "insert_child",
success: function(data) {
console.log(data);
if (data == "success"){
alert("Data successfully added!");
} else if (data = "failed") {
alert("ERROR IN FETCHING DATA!");
}
displayData();
}
});
return false;
});
$('#saveBtn').click(function() {
$('#modalAddChild').modal('hide');
});
$('#modalAddChild').on('hidden.bs.modal', function(e) {
$(this)
.find("input,textarea,select")
.val('')
.end()
.find("input[type=checkbox], input[type=radio]")
.prop("checked", "")
.end();
})
</script>
This old ajax is working before but I changed it to the ajax mentioned above but both of them are not working anymore.
My OLD Ajax
<script type="text/javascript">
$('#saveChild').submit('click', function() {
var zone = $('#zone').val();
var mothersname = $('#mothersname').val();
var childsname = $('#childsname').val();
var ind_id = $('#ind_id').val();
var sex_id = $('#sex_id').val();
var birthdate = $('#birthdate').val();
var actualdate = $('#actualdate').val();
var weight = $('#weight').val();
var height = $('#height').val();
var ageinmonths = $('#ageinmonths').val();
$.ajax({
type: "POST",
dataType: "JSON",
data: {
zone: zone,
mothersname: mothersname,
childsname: childsname,
ind_id: ind_id,
sex_id: sex_id,
birthdate: birthdate,
actualdate: actualdate,
weight: weight,
height: height,
ageinmonths: ageinmonths,
"_token": "{{ csrf_token() }}"
},
url: "insert_child",
success: function(data) {
alert("Data successfully added!");
displayData();
}
});
return false;
});
$('#saveBtn').click(function() {
$('#modalAddChild').modal('hide');
});
$('#modalAddChild').on('hidden.bs.modal', function(e) {
$(this)
.find("input,textarea,select")
.val('')
.end()
.find("input[type=checkbox], input[type=radio]")
.prop("checked", "")
.end();
})
</script>

well in your first line off java script you wrote:
$('#saveChild').submit('click', function()
this is wrong, the jquery submit event only gets a function, but you passed a 'click' event as well.
you should write it like this:
$('#saveChild').submit(function()...

Related

How to submit form including image on button click [duplicate]

This question already has answers here:
Sending formdata for file upload using ajax
(3 answers)
Closed 9 months ago.
I have this HTML:
<form id="form" enctype="multipart/form-data">
<div class="row">
<div class="col">
<div class="mb-3">
<label for="design_title" class="form-label">Ttile of the design</label>
<input type="text" name="design" class="form-control" id="design_title">
</div>
</div>
<div class="col">
<div class="mb-3">
<label for="design" class="form-label">Upload a new design</label>
<input type="file" name="design" class="form-control" id="design">
</div>
</div>
</div>
<div class="mb-3">
<div class="row">
<div class="col">
<label for="fontsize" class="form-label">Enter the font size</label>
<input type="number" name="design_font_size" class="form-control" id="fontsize">
</div>
<div class="col">
<label for="position_x" class="form-label">Position X</label>
<input type="number" name="design_x" class="form-control" id="position_x">
</div>
<div class="col">
<label for="position_y" class="form-label">Position Y</label>
<input type="number" name="design_y" class="form-control" id="position_y">
</div>
</div>
</div>
<div class="mb-3">
<label class="form-label" for="domain">Choose a domain</label>
<select name="domain" id="domain" class="form-control" data-form="design_output">
<option value="">--Choose--</option>
<?php
$get_domain = mysqli_query( $mysqli, "SELECT * FROM eg_domains");
if( mysqli_num_rows( $get_domain ) > 0 ) {
while( $get_result = mysqli_fetch_array( $get_domain, MYSQLI_ASSOC ) ) {
$domain_name = $get_result['domain_name'];
$company = $get_result['company_name'];
$domain_id = $get_result['domain_id'];
echo "<option value='$domain_id'>$domain_name ($company)</option>";
}
}
?>
</select>
</div>
<button type="button" class="btn btn-primary ajax-btn output-desing" data-form="output_design">Output Design</button>
<button type="submit" class="btn btn-success ajax-btn">Save Design</button>
<div class="mt-3">
<div class="result"></div>
</div>
</form>
Now, on Output Design button click I want to get all the data including image.
So, I am doing this in JQuery/Ajax:
$(document).on("click", ".output-desing", function (e) {
e.preventDefault();
var form = document.querySelector(".output-desing");
var form_name = form.dataset.form;
var data = $("#form").serialize() + "&form=" + form_name;
// var data = '1';
console.log(data);
$.ajax({
dataType: "html",
type: "GET",
url: 'helper/process.php',
data: data,
contentType: false,
cache: false,
processData: false,
beforeSend: function () {
$(".output-design").val("Please wait...");
},
success: function (data) {
$(".output-design").html(data);
}
});
});
But I can get only form data not image data.
How can I get all the data including image data on that button click?
Anyways, I fix it this way:
var form = document.querySelector(".output-desing");
var form_name = form.dataset.form;
var data = new FormData(document.getElementById("form"));
data.append('form', form_name);

Display other inputs based on the value of another input using Laravel and AJAX

I'm a beginner in Laravel and I'm trying to create a form and submit it to the database.
I managed to save the data to the database using the following code.
My blade:
<form id="castingform" method="post" action="castingss" enctype="multipart/form-data">
{{ csrf_field() }}
<input type="hidden" id="id_hidden" name="id" />
<div class="form-row">
<div class="form-group col-md-6">
<label for="casting_name">Nom</label>
<input type="text" class="form-control" id="casting_name" name="casting_name" placeholder="Nom" >
<span class="text-danger">{{ $errors->first('casting_name') }}</span>
</div>
<div class="form-group col-md-6">
<label for="casting_cin">CIN</label>
<input type="text" class="form-control" id="casting_cin" name="casting_cin" placeholder="Cin">
<span class="text-danger">{{ $errors->first('casting_cin') }}</span>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="casting_email">Email</label>
<input type="text" class="form-control" id="casting_email" name="casting_email" placeholder="Email">
<span class="text-danger">{{ $errors->first('casting_email') }}</span>
</div>
<div class="form-group col-md-6">
<label for="casting_phone">Téléphone</label>
<input type="tel" class="form-control" id="casting_phone" name="casting_phone" placeholder="Téléphone">
<span class="text-danger">{{ $errors->first('casting_phone') }}</span>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="casting_age">Age</label>
<input type="number" class="form-control" id="casting_age" name="casting_age" placeholder="Age">
<span class="text-danger">{{ $errors->first('casting_age') }}</span>
</div>
<div class="form-group col-md-6">
<label for="casting_sexe">Sexe</label>
<div class="custom-control custom-radio">
<input type="radio" name="casting_sexe" id="casting_sexeh" class="custom-control-input" value="homme">
<label class="custom-control-label" for="casting_sexeh">Homme</label>
</div>
<div class="custom-control custom-radio">
<input type="radio" name="casting_sexe" id="casting_sexef" class="custom-control-input" value="femme">
<label class="custom-control-label" for="casting_sexef" >Femme</label>
</div>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="casting_city">City</label>
<input type="text" class="form-control" name="casting_city" id="casting_city">
<span class="text-danger">{{ $errors->first('casting_city') }}</span>
</div>
<div class="form-group col-md-6">
<label for="casting_address">Address 2</label>
<input type="text" class="form-control" id="casting_address" name="casting_address" >
<span class="text-danger">{{ $errors->first('casting_address') }}</span>
</div>
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">Upload</span>
</div>
<div class="custom-file">
<input type="file" name="casting_photo" class="custom-file-input" id="casting_photo">
<label class="custom-file-label" for="casting_photo">Choose file</label>
</div>
</div>
<div class=" col-md-6">
<span id="store_image" text-align: center></span>
</div>
</br> </br> </br> </br> </br>
<span class="result"></span>
<div class="form-group" align="center">
<input type="hidden" name="action" id="action" />
<input type="hidden" name="hidden_id" id="hidden_id" />
<input type="submit" name="action_button" id="action_button" class="btn btn-warning" value="ADD" />
</div>
<div class=" col-md-6">
<span id="form_result"></span>
</div>
</form>
<!--------------------- script---------------------
<script type="text/javascript">
$(document).ready(function(){
$('#castingform').on('submit', function(event){
event.preventDefault();
if($('#action').val() == 'Add')
{
$.ajax({
url:"{{ route('castingss.store') }}",
method:"POST",
data: new FormData(this),
dataSrc: "",
contentType: false,
cache:false,
processData: false,
dataType:"json",
success:function(data)
{
var html = '';
if(data.errors)
{
html = '<div class="alert alert-danger">';
for(var count = 0; count < data.errors.length; count++)
{
html += '<p>' + data.errors[count] + '</p>';
}
html += '</div>';
}
if(data.success)
{
alert('je suis là');
html = '<div class="alert alert-success">' + data.success + '</div>';
$('#sample_form')[0].reset();
$('#datatableRows').DataTable().ajax.reload();
}
$('#form_result').html(html);
}
})
}
});
});
</script>
My controller:
public function store(Request $request)
{
$rules = array(
'casting_name' => 'required',
'casting_cin' => 'required|max:8|unique:castings',
'casting_email' => 'required|email|unique:castings',
'casting_phone' => 'required',
'casting_age' => 'required',
'casting_sexe' => 'required',
'casting_city' => 'required',
'casting_address' => 'required',
'casting_photo' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048'
);
$error = Validator::make($request->all(), $rules);
if($error->fails())
{
return response()->json(['errors' => $error->errors()->all()]);
}
$image = $request->file('casting_photo');
$new_name = rand() . '.' . $image->getClientOriginalExtension();
$image->move(public_path('castingimages'), $new_name);
$form_data = array(
'casting_name' => $request->casting_name,
'casting_cin' => $request->casting_cin,
'casting_email' => $request->casting_email,
'casting_phone' => $request->casting_phone,
'casting_age' => $request->casting_age,
'casting_sexe' => $request->casting_sexe,
'casting_city' => $request->casting_city,
'casting_address' => $request->casting_address,
'casting_photo' => $new_name
);
Casting::create($form_data);
return response()->json(['success' => 'Data Added successfully.']);
}
All works very well for me, but now I wanted to add something else to my form.
I wanted based on the value of the input age to display other inputs.
This means if the age is less than 18, two other inputs, one for the name of the guarantor and the other for the identification number of the guarantor, had to be displayed and the age was recorded in the database with the name and the identifier of the guarantor and if the age is over 18 years old we do nothing we record the data in the database with the age of 18 years old.
How could I do this? If you have an idea please give me the lead to follow to achieve this.
EDIT
<script type="text/javascript">
$(document).ready(function(){
$('#castingform').on('submit', function(event){
event.preventDefault();
var castingAgeInput = document.getElementById('casting_age');
var guarantorContainer = document.querySelector('.js-guarantor-container');
var guarantorIdentificationNumberContainer = document.querySelector('.js-guarantor_identification_number-container');
castingAgeInput.addEventListener('change', function(evt) {
if (+evt.target.value < 18) {
guarantorContainer.removeAttribute('hidden');
guarantorIdentificationNumberContainer.removeAttribute('hidden');
} else {
guarantorContainer.setAttribute('hidden', true);
guarantorIdentificationNumberContainer.setAttribute('hidden', true);
}
if($('#action').val() == 'Add')
{
$.ajax({
url:"{{ route('castingss.store') }}",
method:"POST",
data: new FormData(this),
dataSrc: "",
contentType: false,
cache:false,
processData: false,
dataType:"json",
success:function(data)
{
var html = '';
if(data.errors)
{
html = '<div class="alert alert-danger">';
for(var count = 0; count < data.errors.length; count++)
{
html += '<p>' + data.errors[count] + '</p>';
}
html += '</div>';
}
if(data.success)
{
alert('je suis là');
html = '<div class="alert alert-success">' + data.success + '</div>';
$('#sample_form')[0].reset();
$('#datatableRows').DataTable().ajax.reload();
}
$('#form_result').html(html);
}
})
}
});
});
</script>
But it doesn't work
You can just add these fields hidden and toggle their visibility:
var castingAgeInput = document.getElementById('casting_age');
var guarantorContainer = document.querySelector('.js-guarantor-container');
var guarantorIdentificationNumberContainer = document.querySelector('.js-guarantor_identification_number-container');
castingAgeInput.addEventListener('change', function(evt) {
if (+evt.target.value < 18) {
guarantorContainer.removeAttribute('hidden');
guarantorIdentificationNumberContainer.removeAttribute('hidden');
} else {
guarantorContainer.setAttribute('hidden', true);
guarantorIdentificationNumberContainer.setAttribute('hidden', true);
}
});
<div class="form-group col-md-6">
<label for="casting_age">Age</label>
<input type="number" class="form-control" id="casting_age" name="casting_age" placeholder="Age">
<span class="text-danger">{{ $errors->first('casting_age') }}</span>
</div>
<div class="form-group col-md-6 js-guarantor-container" hidden>
<label for="guarantor">Guarantor</label>
<input type="number" class="form-control" id="guarantor" name="guarantor" placeholder="Guarantor">
<span class="text-danger">{{ $errors->first('guarantor') }}</span>
</div>
<div class="form-group col-md-6 js-guarantor_identification_number-container" hidden>
<label for="guarantor_identification_number">Guarantor identification number</label>
<input type="number" class="form-control" id="guarantor_identification_number" name="guarantor_identification_number" placeholder="Age">
<span class="text-danger">{{ $errors->first('guarantor_identification_number') }}</span>
</div>

how to upload files from 2 different file input in from with ajax using formData?

I'm trying to upload 2 file which is in form with ajax but when i print_r($_POST) and print_r($_FILES) it showing me empty array.
here is my html code:
<form id="addFloorEntityTypeFrom" method="POST" action="api/apiRoute.php" enctype="multipart/form-data boundary=----WebKitFormBoundary0BPm0koKA">
<div class="col-md-12">
<div class="form-group">
<label for="categories">Category *</label>
<select class="form-control" id="categories" name="category" required>
<option value="">Please select category</option>
<?php foreach ($categories as $category) {
echo "<option value=\"" . $category['entityTypeId'] . "\">" . $category['entityName'] . "</option>";
} ?>
</select>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label for="typeSVG" class="sr-only">Upload SVG *</label>
<div class="input-group">
<input type="text" name="filename" class="form-control custom-file" placeholder="Please select base svg file" readonly>
<span class="input-group-btn">
<div class="btn btn-dark custom-file custom-file-uploader">
<input type="file" id="typeSVG" name="entityTypeBaseSVG" onchange="this.form.filename.value = this.files.length ? this.files[0].name : ''" required/>
Browse
</div>
</span>
</div>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label for="baseImage" class="sr-only">Upload style Image *</label>
<div class="input-group">
<input type="text" name="baseImage_filename" class="form-control custom-file" placeholder="Please base style image" readonly>
<span class="input-group-btn">
<div class="btn btn-dark custom-file custom-file-uploader">
<input type="file" id="baseImage" name="base_style_image" onchange="this.form.baseImage_filename.value = this.files.length ? this.files[0].name : ''" required />
Browse
</div>
</span>
</div>
</div>
</div>
<div class="col-md-12">
<button type="button" name="addFloorEntity" onclick="SaveEntity(this, true)" class="btn btn-dark mt-3">Save</button>
<button type="button" onclick="closeBaseEntity()" class="btn btn-default mt-3">Cancel</button>
</div>
</form>
here is my JavaScript code.
var formData = new FormData();
var formDataArray = $(form[0]).serializeArray();
for(let i = 0; i < formDataArray.length; i++) {
if(formDataArray[i].name !== 'entityTypeBaseSVG' || formDataArray[i].name !== 'base_style_image') {
formData.append(formDataArray[i].name, formDataArray[i].value);
}
}
formData.append('entityTypeBaseSVG', $('#typeSVG')[0].files[0]);
formData.append('base_style_image', $('#baseImage')[0].files[0]);
$.ajax({
method: "POST",
url: baseUrl + 'newIFPAdmin/api/apiRoute.php',
data: formData,
cache: false,
contentType: false,
processData: false,
}).done(function (response) {
console.log('response', response);
});
this is my server side code..
print_r(json_decode(file_get_contents('php://input'), true));
print_r($_POST);
print_r($_FILES);
exit;
response is:
Array
(
)
Array
(
)
Please try this code. It's working fine. Review screenshot.
https://ibb.co/wJWLfW5
<form id="addFloorEntityTypeFrom" method="POST" action="" enctype="multipart/form-data boundary=----WebKitFormBoundary0BPm0koKA">
<div class="col-md-12">
<div class="form-group">
<label for="categories">Category *</label>
<select class="form-control" id="categories" name="category" required>
<option value="">Please select category</option>
<?php foreach ($categories as $category) {
echo "<option value=\"" . $category['entityTypeId'] . "\">" . $category['entityName'] . "</option>";
} ?>
</select>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label for="typeSVG" class="sr-only">Upload SVG *</label>
<div class="input-group">
<input type="text" name="filename" class="form-control custom-file" placeholder="Please select base svg file" readonly>
<span class="input-group-btn">
<div class="btn btn-dark custom-file custom-file-uploader">
<input type="file" id="typeSVG" name="entityTypeBaseSVG" onchange="this.form.filename.value = this.files.length ? this.files[0].name : ''" required/>
Browse
</div>
</span>
</div>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label for="baseImage" class="sr-only">Upload style Image *</label>
<div class="input-group">
<input type="text" name="baseImage_filename" class="form-control custom-file" placeholder="Please base style image" readonly>
<span class="input-group-btn">
<div class="btn btn-dark custom-file custom-file-uploader">
<input type="file" id="baseImage" name="base_style_image" onchange="this.form.baseImage_filename.value = this.files.length ? this.files[0].name : ''" required />
Browse
</div>
</span>
</div>
</div>
</div>
<div class="col-md-12">
<button type="button" name="addFloorEntity" onclick="SaveEntity(this, true)" class="btn btn-dark mt-3">Save</button>
<button type="button" onclick="closeBaseEntity()" class="btn btn-default mt-3">Cancel</button>
<script>
function SaveEntity()
{
var formData = new FormData();
var formDataArray = $("form").serializeArray();
for(let i = 0; i < formDataArray.length; i++) {
if(formDataArray[i].name !== 'entityTypeBaseSVG' || formDataArray[i].name !== 'base_style_image') {
formData.append(formDataArray[i].name, formDataArray[i].value);
}
}
formData.append('entityTypeBaseSVG', $('#typeSVG')[0].files[0]);
formData.append('base_style_image', $('#baseImage')[0].files[0]);
$.ajax({
method: "POST",
url: 'demo.php',
data: formData,
cache: false,
contentType: false,
processData: false,
}).done(function (response) {
console.log('response', response);
});
}
</script>

How ajax work in dynamically generated div

I am doing sales of product in which I use AJAX to capture data based on a selection from a dropdown to another one. When I dynamically create a field it works only once i want it to work N number of time.
Here is my HTML & PHP Code:
<div class="row col-md-12 mrg-top-20">
<h4 class="card-title" style="color:#ff0033">Sales Details</h4><br>
<div class="col-md-12"></div>
<div class="row col-md-12" data-duplicate="add">
<div class="col-md-4">
<label>Select <strong>Installation Date</strong></label>
<div class="form-group">
<div class="timepicker-input input-icon form-group">
<i class="ti-time"></i>
<input type="text" name="ins_date" class="form-control datepicker-1" placeholder="Datepicker" data-provide="datepicker">
</div>
</div>
</div>
<div class="col-md-4" id="sel_dynamic">
<div class="form-group">
<label>Select <strong>Manufacturer</strong></label>
<select name="manu" id="manu" class="form-control" style="width:100%">
<option disabled="disabled" selected="selected">Select Manufacturer</option>
<?php
$data = mysqli_query($conn,"SELECT * FROM manufacturer_details");
while($itemcat = mysqli_fetch_array($data))
{
?>
<option value="<?php echo $itemcat['MANUFACTURER_ID']; ?>"><?php echo $itemcat['MANUFACTURER_NAME'];?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Select <strong>Modal</strong></label>
<select name="modal" id="modal" class="form-control" style="width:100%">
<option value="" selected disabled="disabled">Select Modal...</option>
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Ser<strong>ial</strong></label>
<input type="text" name="serial" placeholder="Enter Serial No" class="form-control">
</div>
</div>
<div class="col-md-4">
<label>Select <strong>AMC Start Date</strong></label>
<div class="form-group">
<div class="timepicker-input input-icon form-group">
<i class="ti-time"></i>
<input type="text" name="amc_date" class="form-control datepicker-1" placeholder="Datepicker" data-provide="datepicker" data-date-format="mm/dd/yyyy">
</div>
</div>
</div>
<div class="col-md-4">
<label>Select <strong>AMC End Date</strong></label>
<div class="form-group">
<div class="timepicker-input input-icon form-group">
<i class="ti-time"></i>
<input type="text" name="amc_edate" class="form-control datepicker-1" placeholder="Datepicker" data-provide="datepicker" data-date-format="mm/dd/yyyy">
</div>
</div>
</div>
</div>
<div>
<input type="button" id="add" data-duplicate-add="add" class="btn btn-info" value="+"/>
</div>
<div >
<input type="button" data-duplicate-remove="add" class="btn btn-info" value="-"/>
</div>
</div>
Here is My Js Script to Call Ajax Each Time
<script type="text/javascript">
$(document).ready(function()
{
$("#sel_dynamic").on("change","#manu",(function() //just try to use on change
{
var id = $("#manu").val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "ajax_modal.php",
data: dataString,
cache: false,
success: function(html)
{
$("#modal").html(html);
}
});
});
});
</script>
Here is my Ajax File
<?php
include('script/db.php');
if($_POST['id'])
{
$id=$_POST['id'];
$sql=mysqli_query($conn,"select * from modal_details where MANUFACTURER_ID='".$id."'");
?>
<option selected disabled="disabled">Select Modal Name</option>
<?php
while($row = mysqli_fetch_assoc($sql))
{
$id = $row['MODAL_ID'];
$data = $row['MODAL_NAME'];
echo '<option value="'.$id.'">'.$data.'</option>';
}
}
?>
Whenever I create a new field dynamically my AJAX is not working.
Try this :
<script type="text/javascript">
$(document).ready(function()
{
$(document).on('change','#manu',function()
{
var id = $("#manu").val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "ajax_modal.php",
data: dataString,
cache: false,
success: function(html)
{
$("#modal").html(html);
}
});
});
});
</script>
The comments made it clear that you are duplicating your form. I think you have duplicate IDs on your page and your jQuery event will not work anymore. An ID may only occur once.
Take a look here:
Clone form and increment
Add the class to select as shown below:
<select name="manu" id="manu" class="form-control manuClass" style="width:100%">
And use the below script
<script type="text/javascript">
$(document).ready(function()
{
$(document).on('change','.manuClass',function()
{
var id = $(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "ajax_modal.php",
data: dataString,
cache: false,
success: function(html)
{
$(this).parent().parent().next().children().children("#modal").html(html);
}
});
});
});
</script>

validations not working for checking empty fields

validations not working for checking empty fields
while clicking create button no message is alerting
and console is clear not showing any error
my Jquery code:
var assign_report_form = $('#assign_report_form');
$('#create').on('click', function(){
var source_id = $('#src_id option:selected').text();
var username = $('#username').val();
var email = $('#email').val();
var query_name = $('#query_name').val();
var channel = $('#channel').val();
var condition = $('#condition').val();
if((source_id =="")||(username == "")||(email == "")||(query_name == "")||(channel == "")||(condition == "")){
$('#error_message').show().delay(5000).fadeOut();
}
else{
// var data = {'source_id': source_id,
// 'username':username,
// 'email':email,
// 'query_name':query_name,
// 'channel': 'email',
// 'condition': condition
// }
// console.log('data',data)
$.ajax({
url:'/add_report/',
type:'POST',
data:{'source_id': source_id,
'username':username,
'email':email,
'query_name':query_name,
'channel': 'email',
'condition': condition
},
success: function(res){
if(res =='success')
// $('#Add_modal').modal('toggle');
// $('#success_message').show().delay(5000).fadeOut();
// $("input[type=text],input[type=email],select").val("");
// }
// else{
// $('#error_message').show().delay(5000).fadeOut();
// }
console.log('form saved..')
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown)
}
})
event.preventDefault();
}
});
});
validations not working for checking empty fields
while clicking create button no message is alerting
and console is clear not showing any error
Here is the html code:
<button type="button" data-toggle="modal" data-target="#Add_modal" class="btn btn-secondary" id="add_row" style="margin-right: 10px;">Add</button>
<!-- Add New Report Model -->
<div class="modal fade" id="Add_modal" tabindex="-1" role="dialog" aria-labelledby="modalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h3 class="modal-title" id="lineModalLabel">Assign New Report</h3>
</div>
<div class="modal-body">
<!-- content goes here -->
<div class="alert alert-warning" id="#error_message" style='display:none;'>
<strong>Error!</strong>Please fill Empty fields
</div>
<form id="assign_report_form">
{% csrf_token %}
<!-- <input type="hidden" id="src_id" value="{{ source_id }}"/> -->
<div class="form-group">
<label for="username">Source ID</label>
<select id="src_id" class="form-control" name="source_id">
{% for source in sources %}
<option value="{{source_id}}" selected>{{ source.id }}</option>
{% endfor %}
</select>
</div>
<div class="form-group">
<label for="username">Username:</label>
<input type="text" class="form-control" name="username" id="username" placeholder="Username">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" class="form-control" name="email" id="email" placeholder="Email">
</div>
<div class="form-group">
<label for="queryname">Query_Name</label>
<input type="text" class="form-control" name="query_name" id="query_name" placeholder="Query_Name">
</div>
<div class="form-group">
<label for="channel">Channel</label>
<input type="text" class="form-control" name="channel" id="channel" placeholder="Channel">
</div>
<div class="form-group">
<label for="condition">Condition</label>
<input type="text" class="form-control" name="condition" id="condition" placeholder="Condition">
</div>
<input type="button" id="create" class="btn btn-primary" value='Create'/>
</form>
</div>
</div>
</div>
In your html code you need to omit the "#" in id="#error_message" and write id="error_message" instead.
You should always use $('<dropdown selector>').val();, like in your case.
var source_id = $('#src_id option').val();
This will work always for select elements.

Categories