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.
Related
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
I have created a discount coupon system, everything is working perfectly.
From the following form I send the information by ajax
<div class="form-group relative">
<div class="response">
<div class="success"></div>
<div class="warning"></div>
</div>
<form id="coupon" class="mt-2em" method="post" autocomplete="off" enctype="multipart/form-data">
<div class="form-group flex justify-between">
<div class="promo">
<input type="text" name="couponCode" maxlength="15" placeholder="Enter the coupon">
</div>
<div class="btn-promo">
<input id="submit_coupon" type="submit" name="ajaxData" value="Apply" formnovalidate>
</div>
</div>
</form>
</div>
And, this is my ajax code
$(function() {
var frm = $('#coupon');
frm.submit(function(e){
e.preventDefault();
var formData = frm.serialize();
formData += '&' + $('#submit_coupon').attr('name') + '=' + $('#submit_coupon').attr('value');
var url = "coupon.php";
$.ajax({
type: frm.attr('method'),
url: url,
data: formData,
})
.done(function(data) {
let res = JSON.parse(data);
if(res.status){
$(".checkout").load(" .checkout").fadeIn();
$(frm)[0].reset();
$(frm).hide();
} else {
if (typeof (res.message) === 'object') {
for (let name in res.message) {
$('.error').remove();
let msg = '<span class="error">' + res.message[name] + '</span>';
$(msg).insertAfter($('[name=' + name + ']', '#coupon'));
$('.error').fadeIn().delay(5000).fadeOut(5000);
}
} else {
$('.warning').fadeIn();
$('.warning').html(res.message).delay(8000).fadeOut(8000);
}
}
})
.fail(function( jqXHR, textStatus ) {
console.log(jqXHR.responseText);
console.log("Request failed: " + textStatus );
})
});
});
How do I mention this all right, but with the same ajax code, how can I send the coupon code automatically when the coupon is being shared by the URL?
That is, if I have the following in the url: example.com/?codecoupon=EADEAA So I want to automatically send that information to Ajax only if there are those parameters in the URL.
In your HTML:
<input type="text" name="couponCode" maxlength="15" placeholder="Enter the coupon" value="<?= isset($_GET['codecoupon']) ? $_GET['codecoupon'] : '' ?>">
(In order to avoid XSS injections you want to wrap it with htmlspecialchars)
In your JS you should make the sending code a function, then call it:
On submit
On load: only if the input is not empty.
The script will look something like this:
$(function() {
var frm = $('#coupon');
frm.submit(function(e){
e.preventDefault();
sendCoupon(frm);
});
if ($("input[name='couponCode']").val() !== "") {
sendCoupon(frm);
}
function sendCoupon(frm) {
var formData = frm.serialize();
formData += '&' + $('#submit_coupon').attr('name') + '=' + $('#submit_coupon').attr('value');
var url = "coupon.php";
$.ajax({
type: frm.attr('method'),
url: url,
data: formData,
})
.done(function(data) {
let res = JSON.parse(data);
if(res.status){
$(".checkout").load(" .checkout").fadeIn();
$(frm)[0].reset();
$(frm).hide();
} else {
if (typeof (res.message) === 'object') {
for (let name in res.message) {
$('.error').remove();
let msg = '<span class="error">' + res.message[name] + '</span>';
$(msg).insertAfter($('[name=' + name + ']', '#coupon'));
$('.error').fadeIn().delay(5000).fadeOut(5000);
}
} else {
$('.warning').fadeIn();
$('.warning').html(res.message).delay(8000).fadeOut(8000);
}
}
})
.fail(function( jqXHR, textStatus ) {
console.log(jqXHR.responseText);
console.log("Request failed: " + textStatus );
});
}
});
How to update the SESSION value on same page after AJAX call on post JSON value without refreshing page.
I'm stuck here. Any help solving the problem is highly appreciated. I what to run particular class in PHP based on the action button clicked. I.e When the user clicks the add button it initiates the AJAX call and sends the 'ADD' ID else if he/she clicks the update button it sends the 'UPDATE ID. I want to perform this without updating the page.
I have achieved getting the data, but the only issue is it updates only when I refresh the page
How do I update the SESSION in PHP once the AJAX sends the data. I'm a newbie, please take easy on me :) Thanks u
Index.php
<?php
session_start();
echo "SESSION: ".$_SESSION['pageType'];
?>
<!DOCTYPE>
<html lang="en-OM">
<div >AJAX: </div><div id="msg" style="display:inline"></div></div>
<a id="btnAdd" value="add" class="btnType" href="#" role="button">ADD</a><br>
<a id="btnUpdate" value="update" class="btnType" href="#" role="button">UPDATE</a><br>
<a id="btnDelete" value="delete" class="btnType" href="#" role="button">DELETE</a>
</html>
Jquery
<script>
$(document).ready(function () {
$('.btnType').click(function (ev) {
ev.preventDefault();
ev.stopImmediatePropagation();
let pageID;
pageID = $(this).attr('value');
$.ajax({
type: 'POST',
url: 'postData.php',
dataType: 'json',
data: {
pageType: pageID
},
beforeSend: function (data) {
},
success: function (data) {
$('#msg').text(data);
console.log(data);
return data;
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('<p>status code: ' + jqXHR.status +
'</p><p>errorThrown: ' + errorThrown +
'</p><p>jqXHR.responseText:</p><div>' + jqXHR.responseText +
'</div>');
console.log('jqXHR:');
console.log(jqXHR);
console.log('textStatus:');
console.log(textStatus);
console.log('errorThrown:');
console.log(errorThrown);
}
});
});
});
</script>
postData.php
session_start();
if (!empty($_POST['pageType'])) {
echo json_encode($_POST['pageType']);
$_SESSION['pageType']=$_POST['pageType'];
exit;
}
This should work better:
Index.php
<?php
session_start();
?>
<!DOCTYPE>
<html lang="en-OM">
<div >SESSION: </div><div id="msg" style="display:inline"><?php echo $_SESSION['pageType']; ?></div></div>
<a id="btnAdd" value="add" class="btnType" href="#" role="button">ADD</a><br>
<a id="btnUpdate" value="update" class="btnType" href="#" role="button">UPDATE</a><br>
<a id="btnDelete" value="delete" class="btnType" href="#" role="button">DELETE</a>
</html>
jQuery
$(document).ready(function () {
$('.btnType').click(function (ev) {
ev.preventDefault();
ev.stopImmediatePropagation();
let pageID;
pageID = $(this).attr('value');
$.ajax({
type: 'POST',
url: 'postData.php',
data: {
pageType: pageID
},
success: function (data) {
$('#msg').text(data);
console.log(data);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('<p>status code: ' + jqXHR.status +
'</p><p>errorThrown: ' + errorThrown +
'</p><p>jqXHR.responseText:</p><div>' + jqXHR.responseText +
'</div>');
console.log('jqXHR:');
console.log(jqXHR);
console.log('textStatus:');
console.log(textStatus);
console.log('errorThrown:');
console.log(errorThrown);
}
});
});
});
postData.php
session_start();
if (!empty($_POST['pageType'])) {
echo $_POST['pageType'];
$_SESSION['pageType']=$_POST['pageType'];
}
else
{
echo "error - no pagetype specified";
}
exit;
What I did:
1) move the initial echo of the Session value inside the "msg" div, so it can be overwritten by the result of the AJAX call
2) remove all references to JSON from the AJAX options and from the PHP. You aren't using (and don't need to use) JSON here to send a single piece of text.
3) added some basic fault tolerance to postData.php to ensure there is always some kind of output.
I am using a MVC structure and here is the JQuery:
<script type="text/javascript">
$('select[name="provider_id"]').change(function() {
var provider_id = $(this).val();
if (provider_id) {
$.ajax({
url: url + '/ProductsAjax/GetOutletByProvider',
type: 'POST',
dataType: 'json',
data: {
provider_id: provider_id
},
})
.done(function(data) {
$.each(data, function(index, item) {
var outlets = "<option value='" + item.id + "'>" + item.outlet_name + "</option>";
$('select[name="outlet"]').append(outlets);
console.log(item.id + ' ' + item.outlet_name);
})
})
.fail(function(jqXHR, textStatus, errorThrown) {
console.log(textStatus + ': ' + errorThrown);
console.warn(jqXHR.responseText);
});
} else {
$('select[name="outlet"]').empty();
}
});
</script>
It is outputting the correct data in console but the dropdown menu itself does not show the data at all. Nothing happens.
Here are the select menus:
<div class="form-group m-form__group">
<label for="example_input_full_name">
Select Service Provider
</label>
<select class="form-control m-bootstrap-select m_selectpicker" name="provider_id">
<option value="">Select Service Provider</option>
<?php foreach($data['sproviders'] as $service_provider): ?>
<option value="<?php echo $service_provider->service_provider_id; ?>"><?php echo $service_provider->sp_name; ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group m-form__group">
<label for="example_input_full_name">
Select Outlet
</label>
<select class="form-control m-bootstrap-select m_selectpicker" name="outlet" id="outlet">
</select>
</div>
Since the correct data is displaying in console, I can't figure out why it isn't pulling through into the second select menu.
Console data:
108 Branch One
109 Branch Two
110 Branch Three
<script type="text/javascript">
$('select[name="provider_id"]').change(function() {
var provider_id = $(this).val();
if (provider_id) {
$.ajax({
url: url + '/ProductsAjax/GetOutletByProvider',
type: 'POST',
dataType: 'json',
data: {
provider_id: provider_id
},
})
.done(function(data) {
var outlets="";
$.each(data, function(index, item) {
outlets += "<option value='" + item.id + "'>" + item.outlet_name + "</option>"; // concat all options
console.log(item.id + ' ' + item.outlet_name);
})
$('select[name="outlet"]').html(outlets); // add all options
})
.fail(function(jqXHR, textStatus, errorThrown) {
console.log(textStatus + ': ' + errorThrown);
console.warn(jqXHR.responseText);
});
} else {
$('select[name="outlet"]').empty();
}
});
</script>
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.