Submit form with data values inserted from AJAX in Laravel - php

I have the following section of html:
<div class="box-body" style="display:none;" id="claimFreightDetails">
<input type="text" disabled class="form-control" id="pulledProNumber" name="pulledProNumber"><br>
<strong>Origin Information</strong><br>
<textarea disabled class="form-control" id="claimFreightOrigin" name="claimFreightOrigin"></textarea><br>
<strong>Consignee Information</strong><br>
<textarea disabled class="form-control" id="claimFreightConsignee" name="claimFreightConsignee"></textarea><br>
<strong>Weight</strong>
<input type="text" disabled class="form-control" id="claimWeight" name="claimWeight"><br>
<strong>Pieces Count</strong><br>
<input type="text" disabled class="form-control" id="claimPieces" name="claimPieces"><br>
</div>
Now, I have an AJAX POST request where the response inserts the returned data into those fields and textareas:
<script>
$(document).on('click', '#pullDetails', function() {
$('#freightBillDetails').removeClass('hidden');
$.ajax({
type:'POST',
url: '/carrier/claims/pullDetails',
data: {
num: $('input[name=proNumber]').val(),
_token: $('input[name=_token]').val()},
dataType: 'json',
success: function(data) {
if(data.details != undefined) {
console.log('success');
var results = JSON.parse(data.details);
$('#pulledProNumber').val(results.SearchResults[0].SearchItem);
$('#claimWeight').val(results.SearchResults[0].Shipment.Weight);
$('#claimPieces').val(results.SearchResults[0].Shipment.Pieces);
$("#claimFreightOrigin").html(results.SearchResults[0].Shipment.Origin.Name + '
'+ results.SearchResults[0].Shipment.Origin.Address1 +'('+results.SearchResults[0].Shipment.Origin.Address2+')
'+ results.SearchResults[0].Shipment.Origin.City + ', '+ results.SearchResults[0].Shipment.Origin.State + ' '+ results.SearchResults[0].Shipment.Origin.PostalCode);
$("#claimFreightConsignee").html(results.SearchResults[0].Shipment.Consignee.Name + '
'+ results.SearchResults[0].Shipment.Consignee.Address1 +'('+results.SearchResults[0].Shipment.Consignee.Address2+')
'+ results.SearchResults[0].Shipment.Consignee.City + ', '+ results.SearchResults[0].Shipment.Consignee.State + ' '+ results.SearchResults[0].Shipment.Consignee.PostalCode);
$('#openInvoicesOverlay').html('');
$('#openInvoicesOverlay').removeClass('overlay');
$('#claimFreightDetails').show();
}else{
console.log('failed');
console.log(data);
console.log(data.details['SearchResults'].SearchItem);
}
},
error: function(data) {
console.log('error');
console.log(data);
}
});
});
</script>
The problem is, when I go to submit the form that surrounds this (many more fields, this section is just pulled through an API from a Third-Party), all of the data fields except the ones that are referenced in the AJAX are included in the POST request for the overall form.

You need to also remove disabled property after you get ajax response using this
$('.YourDisabledInput').prop("disabled", false);
here is your solution:
<script>
$(document).on('click', '#pullDetails', function() {
$('#freightBillDetails').removeClass('hidden');
$.ajax({
type:'POST',
url: '/carrier/claims/pullDetails',
data: {
num: $('input[name=proNumber]').val(),
_token: $('input[name=_token]').val()},
dataType: 'json',
success: function(data) {
if(data.details != undefined) {
console.log('success');
var results = JSON.parse(data.details);
$('#pulledProNumber').val(results.SearchResults[0].SearchItem);
$('#claimWeight').val(results.SearchResults[0].Shipment.Weight);
$('#claimPieces').val(results.SearchResults[0].Shipment.Pieces);
$("#claimFreightOrigin").html(results.SearchResults[0].Shipment.Origin.Name + '
'+ results.SearchResults[0].Shipment.Origin.Address1 +'('+results.SearchResults[0].Shipment.Origin.Address2+')
'+ results.SearchResults[0].Shipment.Origin.City + ', '+ results.SearchResults[0].Shipment.Origin.State + ' '+ results.SearchResults[0].Shipment.Origin.PostalCode);
$("#claimFreightConsignee").html(results.SearchResults[0].Shipment.Consignee.Name + '
'+ results.SearchResults[0].Shipment.Consignee.Address1 +'('+results.SearchResults[0].Shipment.Consignee.Address2+')
'+ results.SearchResults[0].Shipment.Consignee.City + ', '+ results.SearchResults[0].Shipment.Consignee.State + ' '+ results.SearchResults[0].Shipment.Consignee.PostalCode);
$('#openInvoicesOverlay').html('');
$('#openInvoicesOverlay').removeClass('overlay');
$('#claimFreightDetails').show();
$('#pulledProNumber').prop("disabled", false);
$('#claimWeight').prop("disabled", false);
$('#claimPieces').prop("disabled", false);
$('#claimFreightOrigin').prop("disabled", false);
$('#claimFreightConsignee').prop("disabled", false);
}else{
console.log('failed');
console.log(data);
console.log(data.details['SearchResults'].SearchItem);
}
},
error: function(data) {
console.log('error');
console.log(data);
}
});
});
</script>

just change the the .val to .attr('value') as laravel is pulling from the DOM and jQuery .val doesnt reflect there.
you can check this link
jQuery changing form values not affecting the DOM
also you can test it on jQuery website

disabled input fields will not be submitted with the form. That's the behaviour of disabled.

I guess you were using the wrong name for input.
There is no input name "proNumber". In the HTML it is "pulledProNumber".
And also the field is disabled too.
Please update your code and see if it fix the problem.

Related

how to show data not found when ajax call codeigniter using select option

how to show data not found,
when ajax call data not found using select option
<div class="col-md-6 col-12">
<div class="mb-1">
<label class="form-label" for="country-floating"><?php echo display('city')?></label>
<select name="city" id="city" class="select2 form-select" >
<option value="">No Selected</option>
</select>
</div>
</div>
where my ajax call function are as
<script type="text/javascript">
$(document).ready(function(){
$('#state').change(function(){
var id=$(this).val();
$.ajax({
url : "<?php echo base_url('suppliers/get_city');?>",
method : "POST",
data : {id: id},
async : true,
dataType : 'json',
success: function(data){
var html = '';
var i;
for(i=0; i<data.length; i++){
html += '<option value='+data[i].id+'>'+data[i].city_name+'</option>';
}
$('#city').html(html);
},
error: function(jqXHR, textStatus, errorThrown){
alert('Error: ' + textStatus + ' - ' + errorThrown);
}
});
return false;
});
});
</script>
I don't understand anything now , please help
my code is working properly i just want to show that when no data is found then i want to show "data not found" in select option

Get value on appended element with button submit

When I click the submit on button, the appended elements are not submitted. I already tried to change append() to appendTo() and html(). Please help.
$('select[name="bidang"]').on('change', function(e) {
e.preventDefault();
var id_bidang = $(this).val();
// AJAX request
$.ajax({
url: '<?php echo base_url()?>form_jurnal/getSubBidang',
method: 'GET',
data: {
id_bidang: id_bidang
},
dataType: "json",
success: function(response) {
$('select[id="sub_bidang"]').empty();
$.each(response, function(key, value) {
$('select[id="sub_bidang"]')
.append('<option value="' + value.id_subbidang + '
selected ">'+ value.nama_subbidang +'</option>');
});
}
});
});
<label>Sub Bidang :</label>
<select id="sub_bidang" name="sub_bidang">
<option>--Pilih Sub Bidang--</option>
</select>

Autocomplete issue

I am trying to display users list in input field with jquery auto-complete function. I facing issue in displaying name and selection update value to field.
My PHP Code:
include '../_db.php';
// get what user typed in autocomplete input
$name = trim($_GET['name']);
$param = "%{$name}%";
$query = $conn->prepare('SELECT emp_number, emp_firstname, emp_lastname FROM `hs_hr_employee` WHERE emp_firstname LIKE ? OR emp_lastname LIKE ? ');
$query->bind_param('ss', $param,$param);
$query->execute();
$query->bind_result($emp_number,$emp_firstname,$emp_lastname);
$a_json = array();
$a_json_row = array();
while( $query->fetch() )
{
$a_json_row["emp_number"] = $emp_number;
$a_json_row["fname"] = $emp_firstname;
$a_json_row["lname"] = $emp_lastname;
array_push($a_json, $a_json_row);
}
$json = json_encode($a_json);
print $json;
$query->close();
My JS Code
$(function()
{
$( "#search-emp" ).autocomplete(
{
source: function (request, response)
{
var form_data = {
ajax : '1',
name : $("#search-emp").val(),
actioncall : 'search-emp'
};
$.ajax({
type: "POST",
url: "_ajax.php",
data: form_data,
success: function(response)
{
$.each( response, function( key, value )
{
//alert( key + ": " + value );
console.log('element at index ' + key + ' is ' + JSON.parse(value));
});
//console.log(response);
},
dataType: 'json'
});
}
}, {minLength: 3 });
});
Getting Response
[{"emp_number":1,"fname":"Arslan","lname":"Hassan"},{"emp_number":2,"fname":"Muneeb","lname":"Janjua"
},{"emp_number":3,"fname":"hr","lname":"user"}]
My HTML code
<form class="form-inline">
<div class="form-group">
<label for="exampleInputName2">Employee Name: </label>
<input id="search-emp" type="text" class="form-control" placeholder="*">
</div>
<div class="form-group">
<label for="exampleInputEmail2">Date Range: </label>
<input type="text" class="form-control" id="dp-from" placeholder="From">
<input type="text" class="form-control" id="dp-to" placeholder="To">
</div>
<button type="submit" class="btn btn-primary">Genrate Report</button>
</form>
The problem it's because jQuery auto-complete wants to have 2 fields named label and value. The content from label will be displayed in the auto-complete.
Because your server return other name for the keys you have 2 options:
Change the server to return a json like:
[{"emp_number":1,"fname":"Arslan","lname":"Hassan", "label":"Arslan Hassan", "value": "Arslan Hassan"},....]
Or on the success callback from ajax create an array with this fields (label and value) and pass this array to response() callback.
You can find more informations here: http://api.jqueryui.com/autocomplete/#option-source
In your AJAX request,
$.ajax({
type: "POST",
url: "_ajax.php",
data: form_data,
success: function(response)
{
$.each( response, function( key, value )
{
//alert( key + ": " + value );
console.log('element at index ' + key + ' is ' + JSON.parse(value));
});
//console.log(response);
},
dataType: 'json'
});
specify the contentType to get the correct response.
contentType: "application/json",

Refresh div using ajax

I need to refresh a select (by id) when the ajax call is successful.
But i have no idea how to process
ajax function :
$('#insertForm').on('click', function(){
var form_intitule = $('input[name=form_intitule]').val();
$.ajax({
type: "GET",
url: "lib/function.php?insertForm="+insertForm+"&form_intitule="+form_intitule,
dataType : "html",
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest + '--' + textStatus + '--' + errorThrown);
},
success:function(data){
/*here i need to reload #listeFormation*/ }
});
});
html.php
<div class="form-group">
<label for="nomSalarie" class="col-sm-1 control-label" id="nameSelect">Formations</label>
<div class="col-sm-11">
<select name="listeFormation[]" id="listeFormation" class="form-control" multiple>';
while($ligne = $displayFormation->fetch()){
$data['formation'] .='<option value="'. $ligne['form_id'].'">'.$ligne['form_intitule']. " [" . $ligne['form_organisme'] . "]".'</option>';
}
</select>
</div>
</div>
There are 2 ways in my thought:
Use the $.load() from jQuery like: (it's a GET which inject the response into the node you select)
$('#insertForm').on('click', function(){
var form_intitule = $('input[name=form_intitule]').val();
$("#listeFormation").load(
"lib/function.php",
{
insertForm: insertForm,
form_intitule: form_intitule
},
function(response, status, xhr){
if(status == "error"){
alert(xhr + '--' + xhr.status + " " + xhr.statusText);
}else{
// Process the HTML you want here.. lets call: 'html_you_want_to_inject'
$('#listeFormation').html(html_you_want_to_inject);
}
}
});
});
Using your code, you could use simplely:
$("#listeFormation").html(html_you_want_to_inject);
I guess one point to think is about to remove the PHP from the div and turn this div dinamic since the page load with your Javascript. You kill your PHP each time the AJAX runs, rewriting the content in runtime.

Ajax request with jQuery not working

I haven't developed a long time, I lost a few reflexes.
Can someone help me?
According to Google Chrome, it happens nothing when I press submit :
HTML
<form>
<label for="title">Title :</label>
<input type="text" id="title" />
<label for="comment">Comment :</label>
<input type="text" id="comment" />
<label for="project">Project :</label>
<input type="text" id="project" />
<input type="submit" value="Submit" />
</form>
JavaScript
$(function(){
$('form').submit(function(){
return false;
$.ajax({
type: 'POST',
url: 'http://support.foo.com/insert_bug.aspx',
data: 'username=mr%20dog&password=dog%3Ddog&short_desc=' + $('#title').val() + '&comment=' + $('#comment').val() + '&projectid=' + $('#project').val(),
success: function(msg){
alert(msg);
}
})
});
});
insert_bug.aspx
string username = Request["username"];
string password = Request["password"];
string short_desc = Request["short_desc"];
string comment = Request["comment"];
string projectid_string = Request["projectid"];
If I send the url from my browser, the bug is added.
The problem is that you're returning from the submit event handler before your call to .ajax, which means your AJAX call is never even reached. You could move the return statement to the end of the function body:
$('form').submit(function(){
//AJAX call...
return false;
});
Or you could use the preventDefault method of the event object to the same effect:
$('form').submit(function(e){
e.preventDefault();
//AJAX call...
});
I'm surprised if anything happens anywhere - you are returning false from teh submit function, before calling the $.ajax function.
Try:
$(function(){
$('form').submit(function(){
$.ajax({
type: 'POST',
url: 'http://support.foo.com/insert_bug.aspx',
data: 'username=mr%20dog&password=dog%3Ddog&short_desc=' + $('#title').val() + '&comment=' + $('#comment').val() + '&projectid=' + $('#project').val(),
success: function(msg){
alert(msg);
}
});
return false;
});
});

Categories