I'm trying to receive post data with php from ajax in same page but seems like i have some issues that i have no idea to solve them
here is my html/php code :
<select style="width:auto; margin-left:6%;" class="form-control" name="n-omran-select" id="num_omrane">
<option value='' >Choisir...</option>
<?php
while ($row = $result->fetch_assoc())
{
echo "<option value=".$row['N_omran'].">".$row['N_omran']."</option>";
}
?>
</select><br>
<?php
if (isset($_POST["selectName"])) { // try to receive post values but it seems that's not working
$selectOption = $_POST["selectName"];
$query = "SELECT nom,prenom,tel,adress,matricule_assu FROM `personnel` WHERE N_omran ='$selectOption'";
$result = mysqli_query($db,$query);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
if ($row) {
echo " <h4>Nom : {$row['nom']}</h4>
<h4>Prénom : {$row['prenom']}</h4>
<h4>Téléphone : {$row['tel']} </h4>
<h4>Maticule d'assurance : {$row['matricule_assu']}</h4>
<h4>Adresse : {$row['adress']}</h4>";
}
} ?>
And here is my Ajax post request :
$('#num_omrane').on('change', function () {
var n_omrane = $('#num_omrane').val();
if(n_omrane != ''){
$.ajax({
type: "POST",
url: "index.php",
data: {selectName: n_omrane},
success: function () {
alert("Post request successfully done")
}
});
}
});
the code below can replace all your data with the new ones with clean writing :)
// get data from Database
<?php
if (isset($_POST["selectName"])) { // try to receive post values but it seems that's not working
$selectOption = $_POST["selectName"];
$query = "SELECT nom,prenom,tel,adress,matricule_assu FROM `personnel` WHERE N_omran ='$selectOption'";
$result = mysqli_query($db,$query);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
} ?>
// show rows to be selected
<select style="width:auto; margin-left:6%;" class="form-control" name="n-omran-select" id="num_omrane">
<option value='' >Choisir...</option>
<?php while ($row = $result->fetch_assoc()) { ?>
<option value="<?= $row['N_omran'] ?>"> <?= $row['N_omran'] ?></option>
<?php } ?>
</select><br>
// show recieved data
<?php if ($row) { ?>
<div id="informations">
<h4>Nom : <span id="nom"><?= $row['nom'] ?></span></h4>
<h4>Prénom : <span id="prenom"><?= $row['prenom'] ?></span></h4>
<h4>Téléphone : <span id="tel"><?= $row['tel'] ?> </span></h4>
<h4>Maticule d'assurance : <span id="matricule_assu"><?= $row['matricule_assu'] ?></span></h4>
<h4>Adresse : <span id="adress"><?= $row['adress'] ?></span></h4>
</div>
<?php } ?>
// script for making ajax call
<script>
$('#num_omrane').on('change', function () {
var n_omrane = $('#num_omrane').val();
if(n_omrane != ''){
$.ajax({
type: "POST",
url: "index.php",
data: {selectName: n_omrane},
success: function (response) {
$("#nom").text(response.nom);
$("#prenom").text(response.prenom);
$("#tel").text(response.tel);
$("#matricule_assu").text(response.matricule_assu);
$("#adress").text(response.adress);
}
});
}
});
</script>
$json_data=file_get_contents('php://input');
$json=json_decode($json_data,true);
if(array_key_exists("selectName",$json)){
$selectOption =$json["selectName"];
}
Related
I want to make a dynamic dropdown using selectpicker bootstrap library, codeigniter 4, and AJAX.
I got a problem when I trigger to select the first dropdown, the second dropdown's option appended at third times select. Here I provide the video :
https://youtu.be/AVUBlhajZ_k
Here is my code:
MODEL :
function barangBySupp($namaSupp)
{
$supp = $namaSupp;
$data = $this->db->query("SELECT * FROM tablebarang WHERE supplier='$supp'");
$result = $data->getResultObject();
return $result;
}
CONTROLLER :
public function post()
{
$request = service('request');
if ($request->isAJAX()) {
$namaSupp = $request->getVar('id');
$data = $this->barangMasukModel->barangBySupp($namaSupp);
echo json_encode($data);
}
}
JAVASCRIPT
$("#selectOptSupp").on('changed.bs.select', function(e, clickedIndex, isSelected, previousValue){
const id = $('#selectOptSupp option:selected').data('nama');
const alamat = $('#selectOptSupp option:selected').data('alamat');
const noTelp = $('#selectOptSupp option:selected').data('notelp');
$('[name=namaSupp]').val(id);
$('[name=alamatSupp]').val(alamat);
$('[name=noTelp]').val(noTelp);
$.ajax({
type: "post",
url: "/BarangMasuk/post",
dataType: "JSON",
data: {
id: id
},
cache: false,
success: function(response) {
$.each(response, function(index, data){
$('#selBarang').append('<option data-nama="'+data['namaBarang']+'" data-harga="'+data['harga']+'" data-unit="'+data['unit']+'" value="'+data['namaBarang']+'" data-tokens="'+data['namaBarang']+'">'+data['namaBarang']+'</option>').selectpicker("refresh");
});
SHORT VIEW CODE :
<select id="selectOptSupp" class="form-control selectpicker" data-live-search="true">
<?php foreach ($supplier as $value) : ?>
<option data-nama="<?= $value['namaSupp']; ?>" data-notelp="<?= $value['noTelpSupp']; ?>" data-alamat="<?= $value['alamatSupp']; ?>" data-tokens="<?= $value['namaSupp'] ?>" name="" value="<?= $value['namaSupp'] ?>"><?= $value['namaSupp'] ?>
</option>
<?php endforeach; ?>
</select>
<select id="selBarang" class="form-control selectpicker" data-live-search="true">
// OPTION DATA SHOULD APPEND HERE WHEN #selectOptSupp fires
</select>
i am trying to display data inside using ajax in php, i have done the following code:
<table>
<select id="staff" name="staff">
<option value="#N">N</option>
<option value="#R">R</option>
<option value="#S">S</option>
<option value="#J">J</option>
<option value="#So">So</option>
<option value="#Sr">Sr</option>
<option value="#Jo">Jo</option>
<option value="#Sc">Sc</option>
<option value="#P">P</option>
</select>
<textarea id="show" rows="8" name="notice" class="form-control"></textarea>
</table>
$('#customer').change(function () {
var id = $(this).val();
$.ajax({
type: "GET",
url: "page2.php",
data: "pass_id=" + id,
success: function (data) {
alert(data);
document.getElementById("show").innerHTML = data;
}
});
});
below is my page2.php which fetches the data from database:
<?php
echo $get_id = $_GET['pass_id'];
include("db.php");
$sql = "select notice from admin where username='$get_id'";
while ($row = mysqli_fetch_array($sql)) {
echo $row['notice'];
}
?>
but this is not giving me any data in textbox area , can anyone please tell me what is wrong in my code?
You are using 'customer' instead of 'staff' please change and try
$('#staff').change(function () {
var id = $(this).val();
$.ajax({
type: "GET",
url: "page2.php",
data: "pass_id=" + id,
success: function (data) {
console.log(data);
document.getElementById("show").innerHTML = data;
}
});
});
<?php
$data = [];
$get_id = $_GET['pass_id'];
include("db.php");
$sql = "select notice from admin where username='$get_id'";
while ($row = mysqli_fetch_array($sql)) {
$data[] = $row['notice'];
}
echo json_encode($data);
?>
Use $('#staff').change(function () {
because your Id is staff not customer.
Change your id customer to staff
$('#staff').change(function () {
var id = $(this).val();
$.ajax({
type: "GET",
url: "page2.php",
data: "pass_id=" + id,
success: function (data) {
alert(data);
document.getElementById("show").innerHTML = data;
}
});
});
And also there is a mistake in your query, please try the below code.
<?php
$get_id = $_GET['pass_id'];
include("db.php");
$sql = "select notice from admin where username='$get_id'";
$result = mysqli_query($con,$sql);
while ($row = mysqli_fetch_array($result)) {
echo $row['notice'];
}
?>
Hope it will help.
I need to fill the states list on a dropdown when country is selected.
My code
view
<div class="form-group col-md-6">
<label for="inputEmail4" class="uppercase pull-left m-0">Country</label>
<!-- <input type="text" id="country" name="country" required value="<?php echo $row_all->country;?>" placeholder="Please enter your country name"> -->
<select name="country" id="country" required>
<option value="">--select country--</option>
<?php
if($countries->num_rows()>0)
{
foreach ($countries->result() as $countries_row) {
?>
<option <?php if($countries_row->id==$row_all->countryid){ echo "selected"; }?> value="<?php echo $countries_row->id;?>"><?php echo $countries_row->name;?></option>
<?php
} } ?>
</select>
</div>
<div class="form-group col-md-6">
<label for="inputPassword4" class="uppercase pull-left m-0">State</label>
<select name="state" id="state" >
</select>
</div>
<script type='text/javascript'>
// baseURL variable
var baseURL= "<?php echo base_url();?>";
$(document).ready(function(){
// City change
$('#country').change(function(){
var country = $(this).val();
alert(country);
// AJAX request
$.ajax({
url:'<?php echo base_url()?>main/get_states',
method: 'post',
data: {country: country},
dataType: 'json',
success: function(response){
alert(response);
// Remove options
//$('#state').find('option').not(':first').remove();
//$('#city').find('option').not(':first').remove();
// Add options
$.each(response,function(get_states,data){
$('#state').append('<option value="'+data['id']+'">'+data['name']+'</option>');
});
}
});
});
});
</script>
controller
function get_states()
{
$this->load->helper('url');
$postData = $this->input->post();
$this->load->model('candidate_model');
$data = $this->candidate_model->fetch_states($postData);
echo json_encode($data);
}
Model
candidates_model
function fetch_states($postData)
{
//$query = $this->db->query("SELECT * FROM states");
//return $query;
$response = array();
// Select record
$this->db->select('id,name');
$this->db->where('country_id', $postData['country']);
$q = $this->db->get('states');
$response = $q->result_array();
$response= json_encode($response);
return $response;
}
Model returns value from database and it is also can be access from the view.
I alert the response and it returns array like {"id":"36","name":"delhi"}.
I need to fill this results to dropdown with id states
Any help? Thanks in advance
Try This,
Model :
function fetch_states($country)
{
$this->db->select('id,name');
$this->db->where('country_id', $country);
$q = $this->db->get('states');
if ($q->num_rows() > 0) {
return $q->result_array();
}else{
return array();
}
}
Controller :
function get_states()
{
$this->load->helper('url');
$postData = $this->input->post();
$this->load->model('candidate_model');
$country = $postData['country'];
$state = $this->candidate_model->fetch_states($country);
$respose_array['state'] = $state;
echo json_encode($response_array);
exit();
}
View ajax code :
$.ajax({
url:'<?php echo base_url()?>main/get_states',
method: 'post',
data: {country: country},
dataType: 'json',
success: function(response){
$.each(JSON.parse(response.state),function(i,item){
$('#state').append('<option value="'+item.id+'">'+item.name+'</option>');
});
}
});
Table
Here when I select Category 1 from drop down I should get district names which comes under Category 1 and for Category 2 I should get districts of Category 2 and so on....
As of now in my code i'm pulling out all district names from my district table master by using district codes. But I should get district names based on category selection.
View:
<select class="form-control" name="category" id='cat_id'>
<?php
foreach($query1 as $row)
{
echo '<option value="'.$row->category.'">'.$row->category.'</option>';
}
?>
</select>
<select name="placename" id="placename">
<?php
foreach($query2 as $row)
{
echo '<option value="'.$row->district_name.'">'.$row-
>district_name.'</option>';
}
?>
</select>
Model:
function viewcatplace()
{
$this->db->select("district.district_name");
$this->db->from('district');
$this->db->join('jc_place_master', 'district.district_code =
jc_place_master.district');
$query = $this->db->get();
return $query->result();
}
Controller:
public function viewcatplace()
{
$this->load->model('JcMeetingExpense_model');
$data['query1'] = $this->JcMeetingExpense_model->viewcatprice();
$data['query2'] = $this->JcMeetingExpense_model->viewcatplace();
$this->load->view('JcMeetingExpense/place_view',$data);
}
You can use this demo for your solution : https://www.codexworld.com/dynamic-dependent-dropdown-codeigniter-jquery-ajax/
It can be only done by ajax:
In controller:
public function index()
{
$web = array();
$web['title'] = 'Select tool';
$web['content'] = 'web/category_index';
// $web['data'] = $this->Common_model->get_all('category','*','','');
$web['data'] = $this->db->query('SELECT DISTINCT category FROM category')->result();
$this->load->view('web_template', $web);
}
Load the category data in select option:
<select class="form-control" id="select_category">
<option value="" disabled selected>Select category</option>
<?php if (isset($data) && !empty($data)) : ?>
<?php foreach ($data as $key => $value) : ?>
<option value="<?php echo $value->category; ?>"><?php echo $value->category; ?></option>
<?php endforeach; ?>
<?php endif; ?>
</select>
<select class="form-control" id="append_district"></select>
Using jquery change event get the data using ajax call:
<script type="text/javascript">
$(document).on('change',"#select_category",function (e) {
var optVal= $("#select_category option:selected").val();
if (optVal) {
$.ajax({
type: "post",
url: "getCategoryDetails",
cache: false,
data: {'category' : optVal},
success: function(json){
try {
var obj = jQuery.parseJSON(json);
$('#append_district').empty();
var append_data = '';
if (obj.length > 0) {
$.each(obj, function( index, value ) {
append_data += '<option value="'+value.district+'">'+value.district+'</option>'
});
$('#append_district').append(append_data);
}
} catch(e) {
console.log('Exception while request..');
}
},
error: function(){
console.log('Error while request..');
}
});
}
});
</script>
The data can be get by JSON format.In controller add this method:
public function getCategoryDetails() {
$category = $_POST['category'];
$categoryData = $this->db->query('SELECT district FROM category where category="'.$category.'"')->result();
echo json_encode ($categoryData) ;
}
Hello friends this i am facing some problem...I have multiple check boxes and by selecting each check box i am inserting the users details to database by Ajax. the records records are inserting to database but my problem is that , suppose i have 5 users in the page, suppose i am selecting the 3 user check boxes and submit , and if the insertion succeed then i want that the 3 selected users will not shown on page. i use Google many tips but can't solve the problem.
//this is the menu.php
<li class="invitetab"><span>Invite</span></li>
$('.invitetab').one('click', function(){
var rp = '<?php echo $baseUrl ;?>/themes/gr-mist/pagemenu/parts/';
var v = '<?php echo $_GET['pageid'];?>';
var userid = '<?php echo $_SESSION['db_user_info']['id'] ?>';
$( document ).ready(function() {
$.ajax({
url: ""+rp+"invite.php?pageid="+v+"&userid="+userid,
type: 'POST',
beforeSend: function()
{
$("#loading_img").show();
},
success: function(data)
{
$("#loading_img").hide();
$("#Invite").append(data);
}
});
});
});
//And this is the invite.php
$('.gr-post-btn-submit').click(function(){ // when a feature button is selected
var rp = '<?php echo $config->baseUrl ;?>/themes/gr-mist/pagemenu/parts/';
var v = '<?php echo $_GET['pageid'];?>';
var userid = '<?php echo $user_id ?>';
var serialize = $('.abc').serialize(); // takes all the values of the filter
$.ajax({
type : 'POST',
url: ""+rp+"sendinv.php?pageid="+v+"&userid="+userid, // sends the values to ajax file
data : serialize,
beforeSend: function()
{
$("#loading_own").show();
$("#Invite").css({ opacity: 0.5 });
},
success: function(data)
{
$("#loading_own").hide();
$("#Invite").css({ opacity: 5.6 });
// $("#Invite").show();
//this is the portion where we have to do some thing to hide the inserting check boxes
}
});
});
<form method="post" class="abc" id="" name="inviteform"
enctype="multipart/form-data" action="#">
<?php
$sql = "select * from gr_user_friendships where toid=$user_id and status = 1";
$pagd = $_GET['pageid'];
$liked_users = $db->select($sql);
$count = 0;
for($i=0; $i<count($liked_users); $i++)
{
$extrct_fr = "select * from gr_page_likes where page_id=".$pagd." and receiver_id=".$liked_users[$i]['fromid'];
//echo $extrct_fr;
$frnd = $db->select($extrct_fr);
if(count($frnd)>0)
{
$invt = $db->select("select * from gr_user_friendships where toid=$user_id and fromid!=$frnd[0]['receiver_id']");
$invt_id = $invt[0]['fromid'];
}
else
{
$invt_id = $liked_users[$i]['fromid'];
}
if(!empty($invt_id))
$count = 1;
$user = "Select * from gr_users where id = $invt_id";
//echo $user;
$table = mysql_query($user);
$dbc = mysql_fetch_array($table);
$usid= $dbc['id'];
$bab = $dbc['name'];
$imgs = $dbc['avatar'];
$image_of_fr = $_SERVER['DOCUMENT_ROOT']."/uploads/users/".$usid."/profile/profile-pic/thumb/".$imgs;
$image_location_f = $config->baseUrl."/uploads/users/".$usid."/profile/profile-pic/thumb/".$imgs;
if(file_exists($image_of_fr))
{
$imgp = $image_location_f;
}
else
{
$imgp = $config->baseUrl."/themes/gr-mist/includes/images.jpg";
}
if(!empty($invt_id)){
?>
<style type="text/css">
#users_<?php echo $invt_id ?>
{
width:147px;
height:54px;
display:inline-block;
}
</style>
<input type="checkbox" class="checkbox1" id="gcc_<?php echo $invt_id ?>" name="pgliker[]" value="<?php echo $invt_id ?>"/>
<img width="30" height="30" src="<?php echo $imgp;?>"/>
<?php echo $bab; ?>
<?php
}
}//end of for
?>
<br>
<?php if($count){ ?>
<span style="color:blue; font-weight:bold;" >
<input type="checkbox" id="selecctall"/> Select All</span>
<input type="button" name="gr_submits" class="gr-post-btn-submit" value="invite" id="submits"/>
<?php } ?>
</form>
and this is the sendinv.php
global $db;
$myliker = $_POST['pgliker'];
$pageid = $_GET['pageid'];
$userid = $_GET['userid'];
foreach($myliker as $tps)
{
$sql = "Insert into gr_page_likes values('',$pageid,$userid,$tps,0)";
$db->insert($sql);
}
/**In you invite.php put the element which you want to hide after success
form submission into one div*//
//replace your one with this one.
<div id="gcc_<?php echo $invt_id ?>">
<input type="checkbox" class="checkbox1" name="pgliker[]" value="<?php echo $invt_id ?>"/>
<img width="30" height="30" src="<?php echo $imgp;?>"/>
<?php echo $bab; ?>
</div>
/**Now make an array in your sendinv.php and encode it with json incode***/
//replace your sendinv.php with this one.
$arr = array();
foreach($myliker as $tps)
{
$sql = "Insert into gr_page_likes values('',$pageid,$userid,$tps,0)";
$db->insert($sql);
$arr[] = $tps;
}
echo json_encode($arr);
exit;
/**After in your invite.php in the success block run
jquery foreach with the data and hide the checked boxes with the ids associted after submission. */
$.each( data, function( key, value ) {
// alert( key + ": " + value );
$("#gcc_"+value).hide();//the div for each checked user
});