I create a search form that using ajax as the action. In success ajax, how can I just load some specific div without load all refresh page.
This is my form
<?php
$properties = array('id' => 'form1');
echo form_open("", $properties);
?>
<fieldset>
<div class="controls" id="chekboxes">
<label class="checkbox "><input type="checkbox" name="criteria[]" id="nomorcb"/> Nomor Request </label>
<input type="text" class="input-xlarge focused" id="no" name="no" placeholder="Masukkan No Request..."/>
<label class="checkbox "><input type="checkbox" name="criteria[]" id="namacb"/> Nama User </label>
<input type="text" class="input-xlarge focused" id="nama" name="nama" placeholder="Masukkan Nama User..."/>
<label class="checkbox "><input type="checkbox" name="criteria[]" id="departementcb" /> Departement</label>
<div class="control-group">
<div class="controls">
<select class="input-xlarge" id="selectError" name="dep">
<option value="">-- Pilih departement --</option>
<?php
foreach ($dep as $data) {
echo "<option value='" . $data['nama_departement'] . "'>" . $data['nama_departement'] . "</option>";
}
?>
</select>
</div>
</div>
<label class="checkbox "><input type="checkbox" name="criteria[]" id="rentangcb"/> Rentang waktu</label>
<div class="controls" id="tanggal-rentang">
<input type="text" class="input-small datepicker" id="tanggal" value="" name="tgl_awal"><span> s/d </span>
<input type="text" class="input-small datepicker" id="tanggal2" value="" name="tgl_akhir">
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary" id="submit">Cari</button>
<button type="reset" class="btn" id="cancel">Cancel</button>
</div>
</fieldset>
<?php echo form_close(); ?>
this is the action's code for execute the form.
public function search() {
$id_request = $this->input->post('nomor');
$nama_user = $this->input->post('nama');
$departement = $this->input->post('departement');
$awal = $this->input->post('tgl_awal');
if ($awal != "") {
$awal = $this->input->post('tgl_awal');
} else {
$awal = "2014-01-01";
}
$timestamp_awal = strtotime($awal);
$tgl_awal = date("Y-m-d H:i:s", $timestamp_awal);
$akhir = $this->input->post('tgl_akhir');
if ($akhir != "") {
$akhir = $this->input->post('tgl_akhir');
} else {
$akhir = "2020-01-01";
}
$timestamp_akhir = strtotime($akhir);
$tgl_akhir = date("Y-m-d H:i:s", $timestamp_akhir);
$data = $this->model_request->search($id_request, $nama_user, $departement, $tgl_awal, $tgl_akhir);
echo json_encode($data);
}
and this is the Ajax jquery for form above :
$('form').on('submit', function() {
var nomor = $('#no').val();
var nama = $('#nama').val();
var departement = $('#selectError').val();
var tgl_awal = $('#tanggal').val();
var tgl_akhir = $('#tanggal2').val();
$.ajax({
url: '<?php echo base_url() . 'it_team/control_it/search' ?>',
type: 'POST',
data: {nomor: nomor,
nama: nama,
departement: departement,
tgl_awal: tgl_awal,
tgl_akhir: tgl_akhir},
dataType: 'json',
success: function(obj) {
//Please give me an idea
}
});
return false;
For testing, I try seearch and thank God, it gives me a success on json like this:
[{"id_request":"015","nama_user":"Dzil","departement":"IT","waktu_it_terima":"2015-06-19 02:51:05"},
{"id_request":"017","nama_user":"Dzil","departement":"IT","waktu_it_terima":"2015-06-19 13:32:46"}]
My problem is, the result of search form above will be displaying into a table in same page with the form above. You know, in tbody's table will be generate the object on based the return of json. I am newbie using json. The table looked like this
<div class="box-content" id="things_table2">
<table class="table table-bordered table-striped table-condensed" id="table1">
<thead>
<tr>
<th>No. </th>
<th>No Request</th>
<th>Nama user</th>
<th>Departement</th>
<th>Tanggal Request</th>
<th>Action</th>
</tr>
</thead>
<tbody id="hasil-pencarian">
// Result will be showing here
</tbody>
</table>
</div>
Any help it so appriciated.
Try like this (beware there are less fields in your json than in your table):
var data = [
{
'id_request': '015',
'nama_user': 'Dzil',
'departement': 'IT',
'waktu_it_terima': '2015-06-19 02:51:05'
},
{
'id_request': '017',
'nama_user': 'Dzil',
'departement': 'IT',
'waktu_it_terima': '2015-06-19 13:32:46'
}
];
var html = '';
for (var i = 0; i < data.length; i++) {
var td="";
for(var key in data[i]){
td+='<td>'+data[i][key]+'</td>';
}
html+="<tr>"+td+"</tr>";
}
$('#hasil-pencarian').html(html);
There is nothing special about json. Treat it like any js object, ie after parsing it.
Since its just an array of objects, you can iterate over it and do whatever.
var html = '';
$.each(data, function (index, element) {
// build your html
html += '<tr>;'
html += '<td>'+ index + 1 + '</td>';
html += '<td>'+ element.id_request + '</td>';
// same for other elements use `element.<key-name>`
// end tr after all the td's are done
html += '</tr>;'
});
Once you have iterated over all the elements, inject it in the dom.
$('.DOM-ELEMENT').html(html);
Related
I want to sent some data with ajax to a php file. I created a FormData, and then, i append all the data to it, that i want to send. I dont get any error message in the console.
My problem is, that the formdata is always empty, and the php file is not getting any data also.
The form:
<div class="tab-pane show" id="tab5">
<form id="AllapotForm" class="form-horizontal" method="post" enctype="multipart/form-data">
<table id="products" class="table table-hover">
<thead>
<tr class="tr_bold">
<!--width="33.3%"-->
<td class="left" >Létrehozva</td>
<td class="left" >Állapot</td>
<td class="left" >A megrendelő értesítve email-ben</td>
<td class="left" >Megjegyzés</td>
</tr>
</thead>
<tbody id="allapotok">
<?php
$get_r_allaptok = mysqli_query($kapcs,
"
SELECT
rendeles_allapot.*,
rendeles_allapotok.rendeles_allapotok_nev
FROM rendeles_allapot
LEFT JOIN rendeles_allapotok ON rendeles_allapot.allapot_allapot_id = rendeles_allapotok.rendeles_allapotok_id
WHERE allapot_rendeles_id = '$id' ORDER BY allapot_id ASC
")
or die(mysqli_error($kapcs));
if(mysqli_num_rows($get_r_allaptok) > 0 )
{
while($r_allapot = mysqli_fetch_assoc($get_r_allaptok))
{
if($r_allapot['allapot_notify'] == 0 ) { $ertesitve = "Nem"; }
if($r_allapot['allapot_notify'] == 1 ) { $ertesitve = "Igen"; }
echo '<tr>
<td class="left">'.$r_allapot['allapot_datetime'].'</td>
<td class="left">'.$r_allapot['rendeles_allapotok_nev'].'</td>
<td class="left">'.$ertesitve.'</td>
<td class="left">'.$r_allapot['allapot_comment'].'</td>
</tr>';
}
}
?>
</tbody>
</table>
<img src="<?php echo $host; ?>/images/assets/preloader.gif" id="preloaderImage2" style="display:none" class="img-responsive" style="margin:10px auto;">
<div class="form-group row">
<label class="control-label col-md-2">Állapot:</label>
<div class="col-md-2">
<select name="allapot" id="allapot" class="input input-select form-control">
<?php
$check_allapot = mysqli_query($kapcs, "SELECT allapot_allapot_id FROM rendeles_allapot WHERE allapot_rendeles_id = '$id' ORDER BY allapot_id DESC LIMIT 1");
if(mysqli_num_rows($check_allapot) > 0 )
{
$allapot_fetch = mysqli_fetch_assoc($check_allapot);
$ertek = $allapot_fetch['allapot_allapot_id'];
}
else
{
$ertek = intval($a['status']);
}
$get_allapotok = mysqli_query($kapcs, "SELECT rendeles_allapotok_id, rendeles_allapotok_nev FROM rendeles_allapotok WHERE rendeles_allapotok_status = 1 ORDER BY rendeles_allapotok_nev ASC");
if(mysqli_num_rows($get_allapotok) > 0 )
{
while($allapot = mysqli_fetch_assoc($get_allapotok))
{
$selected = $ertek == $allapot['rendeles_allapotok_id'] ? ' selected="selected"':'';
echo '<option ' . $selected . ' value="' . $allapot['rendeles_allapotok_id'] . '">' . $allapot['rendeles_allapotok_nev'] . '</option>'."\n";
}
}
?>
</select>
</div>
</div>
<div class="form-group row">
<label class="control-label col-md-2">Megrendelő értesítése email-ben:</label>
<div class="col-md-2">
<input type="checkbox" name="notify" id="notify" class="form-control" />
</div>
</div>
<div class="form-group row">
<label class="control-label col-md-2">Megjegyzés hozzáadása az email-hez:<span class="help">Amennyiben ezt bepipálja, a megjegyzés az ügyfélnek kiküldött üzenetbe is bele fog kerülni.</span></label>
<div class="col-md-2">
<input type="checkbox" name="add_text" id="add_text" class="form-control" />
</div>
</div>
<div class="form-group row">
<label class="control-label col-md-2">Fájl csatolása az email-hez:</label>
<div class="col-md-2">
<input type="file" name="file" id="file" class="form-control" />
</div>
</div>
<div class="form-group row">
<label class="control-label col-md-2">Megjegyzés:</label>
<div class="col-md-8">
<textarea name="comment" id="comment" style="width:100%;height:200px;"></textarea>
<div style="margin-top: 10px; text-align: center;">
<a class="saveButton btn btn-primary" style="color:#fff" onclick="allapot_modosit();" id="history_button">Állapot módosítása</a>
</div>
</div>
</div>
</form>
</div>
I call this function on a button click event.
function send_data()
{
var html;
var RendelesID = <?php echo $id; ?>;
var RendelesUserEmail = "<?php echo html($a['email']); ?>";
var RendelesUserName = "<?php echo html($a['nev']); ?>";
var webshopEmail = "<?php echo $webshopEmail; ?>";
var webshopName = "<?php echo $webshopName; ?>";
var Allapot = $( "#allapot option:selected" ).val();
var Comment = CKEDITOR.instances['comment'].getData();
if($("#notify").is(':checked')){var Notify = 1;}else{var Notify = 0;}
if($("#add_text").is(':checked')){var AddToEmail = 1;}else{var AddToEmail = 0;}
var formData = new FormData($('#AllapotForm')[0]);
formData.append('fileName', $('#file')[0].files[0]);
formData.append(RendelesID, RendelesID);
formData.append(RendelesUserEmail, RendelesUserEmail);
formData.append(RendelesUserName, RendelesUserName);
formData.append(webshopEmail, webshopEmail);
formData.append(webshopName, webshopName);
formData.append(Allapot, Allapot);
formData.append(Comment, Comment);
formData.append(Notify, Notify);
formData.append(AddToEmail, AddToEmail);
console.log(formData);
$.ajax({
type: 'POST',
cache: false,
url: 'files/update_rendeles_allapot.php',
//dataType: 'html',
enctype: 'multipart/form-data',
processData: false,
contentType: false,
data: { formData:formData },
beforeSend: function(){
$('#preloaderImage2').show();
},
success: function(data)
{
alert(data);
},
complete: function(){
$('#preloaderImage2').hide();
},
error: function (e) {
alert(e.responseText);
console.log(e);
}
});
}
data: { formData:formData },
You need to pass the form data object itself, not a plain object.
data: formData
Have you already seen this?
FormData created from an existing form seems empty when I log it
If yes try to check your network look to the Network then take a look at your request.
You can also try to check your API via Postman if it's working properly.
i created a dynamic form where you can add a form group. on a second page the input is sent by post. if i add more than one field, the radio buttons don't work anymore and the mail delivery doesn't work either
I tried to make a for-loop, but doesnt worked..
index.php (dynamic form):
<script>
var ct = 1;
function new_link()
{
ct++;
var div1 = document.createElement('div');
div1.id = ct;
// link to delete extended form elements
var delLink = '<div style="text-align:right;margin-right:65px">Delete</div>';
div1.innerHTML = document.getElementById('newlinktpl').innerHTML + delLink;
document.getElementById('newlink').appendChild(div1);
}
// function to delete the newly added set of elements
function delIt(eleId)
{
d = document;
var ele = d.getElementById(eleId);
var parentEle = d.getElementById('newlink');
parentEle.removeChild(ele);
}
</script>
<style>
#newlink {width:600px}
</style>
<form method="post" action="index2.php">
<div id="newlink">
<div>
</div>
</div>
<p>
<br>
<input type="submit" name="submit1">
</p>
<p id="addnew">
New
</p>
</form>
<div id="newlinktpl" style="display:none">
<div>
<table>
<tr>
<label>Ordner:</label>
<td> <input type="text" name="linkurl[]" value="" placeholder="New Folder" required></td>
</tr>
<tr>
<td>
<label>Write</label>
<input type="radio" name="berechtigung[] " value="W">
</td>
<td>
<label>Read</label>
<input type="radio" name="berechtigung[] " value="R">
</td>
<td>
<label>None</label>
<input type="radio" name="berechtigung[] " value="K ">
</td>
</tr>
</table>
</div>
</div>
index2.php: (POST-DATA)
<?php
if(count($_POST))
{
$len = count($_POST['linkurl']);
for ($i=0; $i < $len; $i++)
{
echo $_POST['linkurl'][$i] . '<br>';
echo $_POST['berechtigung'][$i] . '<br>';
}
}
?>
Hi guys i have an issue for displaying all data where a column with name header_id having same data. but when it displayed, his result
just one row. actually of data with header_id='100002' having 4 rows.Thanks.
Model:
function getdtHeaderid($header_id = FALSE) {
if ($header_id === FALSE)
{
$query = $this->db1->get('tbltransactiondtl');
return $query->result_array();
}
$query = $this->db1->get_where('tbltransactiondtl', array('header_id' => $header_id));
return $query->row_array();
}
Controller:
function getdtHeaderid() {
$header_id = $this->input->post('header_id');
$data=$this->M_selltransaction->getdtHeaderid($header_id);
echo json_encode($data);
}
View:
<div class="col-md-6">
<label for="header_id" class="col-md-4 control-label" style="text-align:left">Transaction No</label>
<label class="col-md-1 control-label">:</label>
<div class="col-md-6">
<div class="input-group input-group-unstyled">
<input type="text" class="header_id form-control" placeholder="Search" id="header_id" name="header_id"/>
<span class="input-group-addon"><i class="fa fa-search "></i></span>
</div>
</div>
</div>
<table>
<td><input type="text" width="10" class="detail_id form-control"
id="detail_id" name="detail_id[]" value="<?php $a =
set_value('detail_id[0]'); echo $a;?>" required ></td>
<td><input
type="text" width="10" class="item_code form-control" id="item_code"
name="item_code[]" value="<?php $a = set_value('item_code[0]'); echo
$a;?>" required ></td>
<td><input type="text" class="item_name
form-control" id="item_name" name="item_name[]" value=""
readonly></td>
</table>
<script type="text/javascript">
function getdHeaderid(header_id){
var header_id = header_id.val();
$.ajax({
type : "post",
data : {header_id:header_id},
url : "<?php echo base_url();?>index.php/transaction/selltransaction/getdtHeaderid",
dataType:"json",
cache :false,
success: function(data){
console.log(data);
$(".detail_id").val(data.detail_id);
$(".item_code").val(data.item_code);
$(".item_name").val(data.item_name);
}
});
}
$(document).ready(function() {
$('.header_id').on('keyup change', function() {
getdHeaderid($(this));
});
});
function getdtHeaderid($header_id = FALSE) {
if ($header_id === FALSE)
{
$query = $this->db1->get('tbltransactiondtl');
return $query->result_array();
}
$query = $this->db1->get_where('tbltransactiondtl', array('header_id' => $header_id));
return $query->result_array();
}
Here is Your Correct model function you were using row_array() instead of result_array() thats why getting only one result
update
$(".detail_id").val(data.detail_id);
$(".item_code").val(data.item_code);
$(".item_name").val(data.item_name);
to
$(".detail_id").val(data[0].detail_id);
$(".item_code").val(data[0].item_code);
$(".item_name").val(data[0].item_name);
Below is my HTML code. I can only get value returned by ajax request in that id="sss" field.
My Problems are listed below with images:-
<form id="dynamic2" action="<?= site_url('product/save') ?>" method="post">
<table class="table">
<tbody id="itemlist2" class="detailss">
<tr>
<td>
<select id="select-product" class="form-control" data-cell="B1" name="product_name[]">
<option value="">
</option>
<?php
foreach ($product as $key ):
?>
<option value="<?php echo $key['id'] ?>">
<?php echo $key['product_name'] ?>
</option>
<?php endforeach; ?>
</select>
</td>
<td>
<input type="text" id="sss" data-cell="C1" name="price[]" class="form-control" value="">
</td>
<td>
<input type="text" data-cell="D1" name="quantity[]" class="form-control">
</td>
<td>
<input type="text" data-cell="E1" name="discount[]" class="form-control">
</td>
<td>
<input type="text" data-cell="F1" name="total[]"
disabled="true" data-formula="(D1*C1)-(D1*C1*E1/100)"
class="form-control">
</td>
</tr>
</tbody>
<input type="submit" value="Submit" class="btn btn-primary">
</table>
</form>
I am not getting value returned by ajax request in dynamically created input fields.
Here is my dynamically created input field jS code.
<script type="text/javascript">
$(function() {
$form = $('#dynamic2').calx();
$('.addrowss').click(function() {
$itemlist = $('#itemlist2');
$counter = 5;
var i = ++$counter;
var tr = '<tr>' +
'<td><select id="select-product" class="form-control" data-cell="B' + i + '" name="product_name[]"><option value=""></option><?php
foreach ($product as $key ):
?><option value="<?php echo $key['product_name'] ?>"><?php echo $key['product_name'] ?></option><?php endforeach; ?></select></td>'+
'<td><input id="sss" type="text" data-cell="C' + i + '" name="price[]" class="form-control" value=""></td>' +
'<td><input type="text" data-cell="D' + i + '" name="quantity[]" class="form-control"></td>' +
'<td><input type="text" data-cell="E' + i + '" name="discount[]" class="form-control"></td>' +
'<td><input type="text" class="form-control" data-cell="F' + i + '" name="total[]" data-formula="(D' + i + '*C' + i + ')-(D' + i + '*C' + i + '*E' + i + '/100)"></td>' +
'<td>Remove</td>' +
'</tr>';
$('.detailss').append(tr);
$form.calx('update');
$form.calx('getCell', 'G1').setFormula('SUM(F1:F' + i + ')');
});
$('body').delegate('.remove', 'click', function() {
var tr = $(this).parent().parent();
var c = confirm("Do you want to remove this ?");
if (c) {
tr.remove();
}
});
});
</script>
Ajax Code
<script type="text/javascript">
$(document).ready(function() {
$("#select-product").change(function() {
var id = $(this).val();
// alert(id);
$.ajax({
type: "GET",
url: "<?php echo site_url('/product/view_data'); ?>",
data: {
"id": id
},
cache: false,
success: function(data) {
var tmp = data.split(",");
$('#sss').val(tmp[6]);
}
});
});
});
</script>
Product.php Controller
public function view_data()
{
if(isset($_GET['id'])){
$this->load->model('Product_model');
$id = $_GET['id'];
$param = $this->Product_model->get_ajax_value($id);
foreach($param as $a)
echo $a.",";
exit;
}
}
I am not exactly sure why it isn't returning all the correct data. But here might be a step to help you debug you problem.
Add a console.log(data); To see what is being returned from the ajax call. Use the console of your browser to see this.
Change your code to:
<script type="text/javascript">
$(document).ready(function () {
$("#select-product").change(function () {
var id = $(this).val();
// alert(id);
$.ajax({
type: "GET",
url: "<?php echo site_url('/product/view_data'); ?>",
data: {"id":id},
cache: false,
success: function(data){
console.log(data); //this will show what is returned.
var tmp = data.split(",");
$('#sss').val(tmp[6]);
}
});
});
});
I understand this isn't the complete answer to your code. But it might put you on the right track to seeing what the server is returning to your client side code.
I am trying to create a form with three select dropdown lists. user selects an option from select1 and based on the selected option, select2 gets populated, then user selects an option from select2 and based on selection, select3 gets populated.
following an example on stackoverflow I created this. the lists are getting populated fine but values are not passed when I hit submit button. if i select options from select1 and select2 only then values do get passed, but when i select option from select3 then no values are passed.
This is my PHP:
<?php
require "php/db.inc";
$db = new mysqli($hostName, $username, $password,'mms');//set your database handler
$query = "SELECT AcID, AcName FROM accounts WHERE ParentAcID ='0'";
$result = $db->query($query);
while($row = $result->fetch_assoc()){
$accountgroups[] = array("id" => $row['AcID'], "val" => $row['AcName']);
}
$query = "SELECT AcID, AcName, ParentAcID FROM accounts";
$result = $db->query($query);
while($row = $result->fetch_assoc()){
$accounts[$row['ParentAcID']][] = array("id" => $row['AcID'], "val" => $row['AcName']);
}
$query = "SELECT AcID, AcName, ParentAcID FROM accounts";
$result = $db->query($query);
while($row = $result->fetch_assoc()){
$subaccounts[$row['ParentAcID']][] = array("id" => $row['AcID'], "val" => $row['AcName']);
}
$jsonAcGroup = json_encode($accountgroups);
$jsonAc = json_encode($accounts);
$jsonSubAc = json_encode($subaccounts);
?>
This is my Javascript:
<script type='text/javascript'>
<?php
echo "var account_group = $jsonAcGroup; \n";
echo "var accounts = $jsonAc; \n";
echo "var sub_accounts = $jsonSubAc; \n";
?>
function loadAccountGroup(){
var select = document.getElementById("AcGroupSelect");
select.onchange = updateAccount;
for(var i = 0; i < account_group.length; i++){
select.options[i] = new Option(account_group[i].val,account_group[i].id);
}
}
function updateAccount(){
var catSelect = this;
var catid = this.value;
var subcatSelect = document.getElementById("AcSelect");
AcSelect.options.length = 0; //delete all options if any present
subcatSelect.onchange = updateSubAccount;
for(var i = 0; i < accounts[catid].length; i++){
subcatSelect.options[i] = new Option(accounts[catid][i].val,accounts[catid][i].id);
}
}
function updateSubAccount(){
var catSelect2 = this;
var catid2 = this.value;
var subcatSelect2 = document.getElementById("SubAcSelect");
SubAcSelect.options.length = 0; //delete all options if any present
for(var i = 0; i < sub_accounts[catid2].length; i++){
subcatSelect2.options[i] = new Option(sub_accounts[catid2][i].val,sub_accounts[catid2][i].id);
}
}
function start() {
loadAccountGroup();
updateAccount();
updateSubAccount();
}
window.onload = start;
</script>
This is my FORM:
<form class="form" method="post" action="form_test.php">
<table class='table table-striped'>
<tr>
<td>
<div class="form-group">
<label for="Companyname" class="control-label">Account Group</label>
</div>
</td>
<td>
<div class="form-group">
<label for="Companyname" class="control-label">Account</label>
</div>
</td>
<td>
<div class="form-group">
<label for="Companyname" class="control-label">Sub Account</label>
</div>
</td>
<td>
<div class="form-group">
<label for="Companyname" class="control-label">Debit</label>
</div>
</td>
<td>
<div class="form-group">
<label for="Companyname" class="control-label">Credit</label>
</div>
</td>
</tr>
<tr>
<td>
<div class="form-group">
<select class="form-control" name="AcGroupSelect" id='AcGroupSelect'></select>
</div>
</td>
<td>
<div class="form-group">
<select class="form-control" name="AcSelect" id='AcSelect'></select>
</div>
</td>
<td>
<div class="form-group">
<select class="form-control" name="SubAcSelect" id='SubAcSelect'></select>
</div>
</td>
<td>
<div class="form-group">
<input type="text" class="col-sm-1 form-control" name="DebitAmount" placeholder="Debit Amount">
</div>
</td>
<td>
<div class="form-group">
<input type="text" class="col-sm-1 form-control" name="CreditAmount" placeholder="Credit Amount">
</div>
</td>
</tr>
</table>
I had a similar problem. Once you get your values from the drop down list you still need to somehow put them into you form and submit them.
have a look at this I managed to solve it like this.
Populating the third menu based on previous dropdown values
Also have you got a submit button? Can't see how you submit in your form. Also missing closing form tag
Finally I figured it out. this script works just fine. the problem was not in the script but rather in the html. the top menu was hiding one line output n i was banging my head for getting the blank page.