Ajax request data could not show into the input field - javascript

I have created a loop which contains a dropdown list and input field.
What I need is:
When I select a value from dropdown list of Fruit Genres, the Unit Price field will display value come from database. I did all of these, but could not display value to the Unit Price field.
Here is my code:
View page:
<div class="table-responsive">
<table class="table table-hover" id="item-tbl">
<thead>
<tr>
<th class="text-center">Fruit Type</th>
<th class="text-center">Fruit Genres</th>
<th class="text-center">Qty</th>
<th class="text-center">Unit Price</th>
<th class="text-center">Sub Total</th>
</tr>
</thead>
<tbody>
<?php for($i=1; $i<=3; $i++){ ?>
<tr style="">
<td><?php echo $this->Form->input('fruit_type_id', ['options'=>$fruit_types, 'empty'=>'Select Fruit Type', 'label'=>false, 'name'=>'detail_orders['.$i.'][fruit_type_id]']); ?></td>
<td><?php echo $this->Form->input('fruit_genre_id', ['options'=>$fruit_genres, 'empty'=>'Select Fruit Genre', 'label'=>false, 'name'=>'detail_orders['.$i.'][fruit_genre_id]', 'class'=>'fruit_genre']); ?></td>
<td><?php echo $this->Form->input('quantity', ['type'=>'text', 'label'=>false, 'name'=>'detail_orders['.$i.'][quantity]', 'class'=>'quantity', 'id'=>'quantity_'.$i]); ?></td>
<td><?php echo $this->Form->input('price', ['type'=>'text', 'label'=>false, 'name'=>'detail_orders['.$i.'][price]', 'class'=>'price', 'id'=>'price_'.$i]); ?></td>
<td><?php echo $this->Form->input('sub_total', ['type'=>'text', 'label'=>false, 'name'=>'detail_orders['.$i.'][price]', 'class'=>'sub_total']); ?></td>
</tr>
<?php } ?>
</tbody>
</table>
Javascript:
<script type="text/javascript">
$(document).ready(function() {
$(".fruit_genre").on('change' , function() {
var fruitGenreId = +$(this).val();
var priceId = $(this).closest('tr').find('.price').attr('id');
// alert(priceId);
$.ajax({
type: "GET",
url: baseURL+"orders/getFruitById/"+fruitGenreId+".json",
beforeSend: false,
success : function(returnData) {
if(returnData.response.code == '200'){
console.log(returnData.response.data.unit_price);
// $(this).closest('tr').find('.price').val(returnData.response.data.unit_price);
$(priceId).val(returnData.response.data.unit_price);
};
}
})
}).trigger('change');
});
OrdersController.php
public function getFruitById($id){
$this->viewBuilder()->layout('ajax');
$this->loadModel('FruitGenres');
$item = $this->FruitGenres->get($id);
if (!empty($item)) {
$response['code'] = 200;
$response['message'] = 'DATA_FOUND';
$response['data'] = $item;
}else{
$response['code'] = 404;
$response['message'] = 'DATA_NOT_FOUND';
$response['data'] = array();
}
$this->set('response', $response);
$this->set('_serialize', ['response']);
}
I have got the expected data to the javascript console. but could not pass the data to the input field.
I have tried:
$(this).closest('tr').find('.price').val(returnData.response.data.unit_price);
instead of
$(priceId).val(returnData.response.data.unit_price);
into the ajax success function, but it did not worked.
if I add a static id like the following:
$('#price_1').val(returnData.response.data.unit_price);
then it works.
Can anyone please help me? I am stuck on it.
I am using cakephp 3 for my project.

priceId is a value like price_1 without #. To make it a selector by id - prepend it with #:
$("#" + priceId).val(returnData.response.data.unit_price);
You can even simplify your code:
// you get id of the found element so as to find this element again
// you can store founded element instead of it's id
var priceDiv = $(this).closest('tr').find('.price');
// in success callback:
priceDiv.val(returnData.response.data.unit_price);

You can select the element directly instead of getting its ID and select with another jQuery call.
Another thing to note - this in the submit callback refer to the callback function itself, not the element.
$(document).ready(function() {
$(".fruit_genre").on('change' , function() {
var fruitGenreId = +$(this).val();
var $price = $(this).closest('tr').find('input.price'); // Get the element
$.ajax({
type: "GET",
url: baseURL+"orders/getFruitById/"+fruitGenreId+".json",
beforeSend: false,
success : function(returnData) {
if(returnData.response.code == '200'){
console.log(returnData.response.data.unit_price);
// Use $price directly as a jQuery object
$price.val(returnData.response.data.unit_price);
};
}
})
}).trigger('change');
});

Related

Call php function from Javascript inside php file

I have a php file that shows all the user details in table form. On click of edit, I am want to set something from DB to local storage using javascript.
So to show a table of users I am doing the following:
<table cellspacing="0">
<tr>
<th>ID</th>
<th>Name</th>
<th>View</th>
<th>Edit</th>
</tr>
<?php
$count=1;
$sel_query="Select * from user_details ORDER BY id desc;";
$result = mysqli_query($con,$sel_query);
while($row = mysqli_fetch_assoc($result)) {
?>
<tr>
<td align="center"><?php echo $count; ?>
<td align="center"><?php echo $row["docname"]; ?>
<td align="center">View</td>
<td align="center">Edit</td>
</tr>
<?php $count++; } ?>
</table>
The above shows the records in the table perfectly.
Now when edit is clicked, I call a javascript function. (This is called before I click on edit? I am not sure why?)
<script type="text/javascript">
function handleLinkClick (e) {
e.preventDefault ();
var id = e.target.href.split ("?").pop ();
var key = <?php echo add(id);?>
console.log(key);
localStorage.setItem ("myKey", key);
//window.location.href = e.target.href;
}
</script>
Now from javascript function, I am trying to call a PHP function a variable is sent from javascript to PHP function to fetch corresponding records details and return that data to javascript, below is the PHP function:
function add($id){
$sel_query="select * from user_details where id=$id";
$result = mysqli_query($con,$sel_query);
while($row = mysqli_fetch_assoc($result))
{
$key = $row["rawText"];
echo $key;
}
return $key;
}
?>
I don't see any results. I am not sure why I am not getting any results? Can some give me the right syntax or correct me?
Thanks!

Retrieve data from database using ajax

I want to get data from database by using ajax. The data will be fetched by choosing the drop down option and click the search button and data will show up in the table. I've written the proper query and it runs very well. All I want is just show the data from database to the table with ajax. I've read tutorials and questions in Stackoverflow but still got no solution. Here's the sample of interface,
Here's my controller :
function getDataExcelKK() {
$station = $this->input->get('station');
$data = $this->M_dbstatmanagement->getDataExcelKK($station);
$this->load->view('v_lhastat_admin', $data);
}
The model :
function getDataExcelKK($station) {
$this->db->select("F.NAMA_FILE AS NAMA_FILE, DATE_FORMAT(F.TANGGAL_UPLOAD, '%d-%m-%Y %H:%i:%s') AS TANGGAL_UPLOAD");
$this->db->from("fileupload F");
$this->db->join("user U", "F.ID_USER = U.ID_USER");
$this->db->where("U.DOMISILI", $station);
$this->db->order_by("F.TANGGAL_UPLOAD DESC");
$query = $this->db->get();
return $query->result_array();
}
The view (table) :
<table class="table table-striped table-bordered table-hover table-condensed table-checkable order-column" id="lhaStatAdmin">
<thead>
<tr>
<th width="10%">No.</th>
<th width="10%">File Name</th>
<th width="10%">Upload Date</th>
</tr>
</thead>
<tbody id="isi-data">
<?php
$no = 1;
$i = 0;
foreach($getExcelFromKK as $key => $row) {?>
<tr>
<td><?php echo $no++;?></td>
<td><?php echo $row['NAMA_FILE'];?></td>
<td><?php echo $row['TANGGAL_UPLOAD'];?></td>
</tr>
<?php } ?>
</tbody>
</table>
And here's my ajax :
$('#button-search').on('click', function() {
var station = $('#stationChoose').val();
$.ajax({
async : true,
type : 'GET',
url : '<?php echo base_url();?>sms/getDataExcelKK',
data : {"station": station},
success :
function(data) {
$('#isi-data').html(data);
}
});
});
UPDATE : Instead of retrieve data into table, I got a table inside table when I click 'Search' button.
try those in your success in ajax
var preparedString = '';
for(var i=0;i<data.length;i++){
var preparedString += '<tr>'+
'<td>'+(i+1)+'</td>'+
'<td>'+data[i].NAMA_FILE+'</td>'+
'<td>'+data[i].TANGGAL_UPLOAD+'</td>'+
'</tr>'
}
$('#isi-data').append(preparedString);
so your ajax should look like this
$('#button-search').on('click', function() {
var station = $('#stationChoose').val();
$.ajax({
async : true,
type : 'GET',
url : '<?php echo base_url();?>sms/getDataExcelKK',
data : {"station": station},
success :
function(data) {
var preparedString = '';
for(var i=0;i<data.length;i++){
var preparedString += '<tr>'+
'<td>'+(i+1)+'</td>'+
'<td>'+data[i].NAMA_FILE+'</td>'+
'<td>'+data[i].TANGGAL_UPLOAD+'</td>'+
'</tr>'
}
$('#isi-data').append(preparedString);
}
});
});
Try this, keep url in double quotes.
$('#button-search').on('click', function() {
var station = $('#stationChoose').val();
$.ajax({
async : true,
type : 'GET',
url : "<?php echo base_url();?>sms/getDataExcelKK",
data : {"station": station},
success :
function(data) {
$('#isi-data').html(data);
}
});
});
you ether create the html from you data and append it(as #Ivan Tabaka sed) or you create your html in the PHP and append it in your html
is it possible to load full table in another view(ex.'table.php') and deposit this view on by replacing previous full table (can apply datatable in table.php) , after that for every table row become clickable to open modal, every tr become <tr onclick="action(3)">.
script:
function action(argument) {
// body...
alert(argument);
}
Try to set async to false.
$.ajax({
async : false,
type : 'GET',
url : "<?php echo base_url();?>sms/getDataExcelKK",
data : {"station": station},
success :
function(data) {
$('#isi-data').html(data);
}
});

Unable to remove a table row after ajax success

In my html-php table:
<tr id="idrow">
<td><?php echo $user_id; ?></td>
<td ><?php echo $user_name; ?></td>
<td>
<input type="button" class="btn btn-danger btn-xs delete " value="Cancella sin id" onclick="deleteFunction(<?php echo $user_id; ?>)"/>
</td>
</tr>
there is a button to erase sql row by a ajax call, using the id field.
My problem is on update table after success:
my js code is:
function deleteFunction(valor) {
var $tr = $('#datatable-id').closest('tr');
var id = valor;
var parametros = {
"id" : id
};
console.log(parametros);
$.ajax({
type: "POST",
url: "deleteTabla.php",
data: parametros,
success: function(result){
//$("#idrow").remove();
$tr.remove();
},
error: function () {
console.log('ajax error');
}
});
}
Using $("#idrow").remove(), the first row is removed, not the button related one.
I suppose the trick is on var $tr = $('#datatable-id').closest('tr');, the reference to tr label?
Any help is appreciated.
If I understand correctly, every row has the same id (idrow). This is your first mistake. Ids have to be unique throughout the whole page. Create the rows with a unique Id and pass it to the function:
<tr id="idrow_<?php echo $user_id; ?>">
...
<td>
<input type="button" onclick="deleteFunction('<?php echo $user_id; ?>')"/>
</td>
</tr>
In your function, just do this:
function deleteFunction(valor) {
...
$('#idrow_'+valor).remove();
...
}
The closest tr to the #datatable-id will always be the first row.
If you want to delete a particular row try assigning an id.
<tr id="<?php echo $user_id;?>">
....
</tr>
Then in the function:
function deleteFunction(valor) {
var $tr = $('#' + valor);
// delete after request is success
$tr.remove()
}
Try this
<tr id="idrow_<?= $user_id ?>">
And on success:
$("#idrow_" + valor).remove();
Change your selector at the beginning of the function to this: var $try = $("#idrow")

I would like to change table value using ajax

I have a select-option and i choose one,i wanna change tablo value from database.
In my View :
<select id="Room" >
<option value="Joseph">Joseph Room</option>
<option value="Macro">Macro Lounge</option>
</select>
<table>
<tr>
<td>Day</td>
<?php
foreach ($posts as $post)
{
echo "<td>{$post->seancehour}</td>";
}
?>
</tr>
<tr>
<td><?php echo $post->seanceday; ?></td><td><?php echo $post->seancename; ?></td>
</tr>
</table>
I use ajax and want to change dynamiccally table value.My javascript is :
<script type="text/javascript">
$(document).ready(function () {
$('#Room').change(function () {
var room = document.getElementById("Room").value;
$.ajax({
type: 'POST',
data: {room: room},
url: '<?php echo site_url('Homepage/index'); ?>',
success: function (result) {
alert(result);//I dont know what has to be here.
}
});
});
});
</script>
In my Controller,I go mymodel and get database value.
public function index()
{
$room = $this->input->post('room');
if ($room == 'Macro')
{
$this->data['pasts'] = $this->SeanceModel->getMacro();
}
else
{
$this->data['posts'] = $this->SeanceModel->getJoseph();
}
$this->load->view('Homepage', $this->data);
}
For example when i open the page day=Sunday hour=12pm,if i change joseph or macro,this values must be change in the table.

I am not getting response from ajax request

I am getting no response from ajax request . i am posting a ajax call to processor.php file and the processor.php file is processing the file and sending the processed file back to javascript i am gerring my result in my console log but it is not showing in the html.
My javascript code is :
function add_to_cart(item_name,item_price){
$('.user-info').slideUp('1200');
$('.cart-status').slideDown('1200');
var dataString = "item_name=" + item_name + "&item_price=" + item_price + "&page=add_to_cart";
$.ajax({
type: "POST",
url: "php/processor/processor.php",
data:dataString,
beforeSend:function(){
$(".cart-show-product").html('<h3>Your Cart Status</h3><img src="images/loading.gif" align="absmiddle" alt="Loading...." class="center" /><br><p class="center">Please Wait...</p>');
},
success: function(response){
console.log(response);
$(".cart-show-products").html(response);
}
});
}
and my php is :
if(isset($_POST['item_name']) && !empty($_POST['item_name']) && isset($_POST['item_price']) && !empty($_POST['item_price']))
{
$sql = mysqli_query($conn,
'SELECT * FROM
products_added
where
username = "'.mysqli_real_escape_string($conn, $_SERVER['REMOTE_ADDR']).'"
and
item_added="'.mysqli_real_escape_string($conn, $_POST['item_name']).'"'
);
if(mysqli_num_rows($sql) < 1)
{
mysqli_query($conn,
"INSERT INTO products_added values(
'',
'".mysqli_real_escape_string($conn, $_SERVER['REMOTE_ADDR'])."',
'".mysqli_real_escape_string($conn, $_POST['item_name'])."',
'".mysqli_real_escape_string($conn, $_POST['item_price'])."',
'".mysqli_real_escape_string($conn, '1')."',
'".mysqli_real_escape_string($conn, $_POST['item_price'])."'
'".mysqli_real_escape_string($conn, date("d-m-Y"))."')"
);
?>
<table class="cart-show-products">
<thead>
<tr>
<td>Sl.No</td>
<td>Item</td>
<td>Qty</td>
<td>Price</td>
<td>Action</td>
</tr>
</thead>
<tbody>
<?php
$sl_no = 1;
$sql = mysqli_query(
$conn,
'SELECT sum(amount) as grandtotal
FROM products_added
WHERE username = "'.mysqli_real_escape_string($conn, $_SERVER['REMOTE_ADDR']).'"
ORDER BY id'
);
$row = mysqli_fetch_array($sql);
$grandtotal = strip_tags($row['grandtotal']);
$sql = mysqli_query(
$conn,
'SELECT
id,
item_added,
price,
quantity
FROM products_added
WHERE username = "'.mysqli_real_escape_string($conn, $_SERVER['REMOTE_ADDR']).'"
ORDER BY id'
);
$row = mysqli_fetch_array($sql);
$item_id = strip_tags($row['item_id']);
$item_name = strip_tags($row['item_added']);
$item_price = strip_tags($row['price']);
$quantity = strip_tags($row['price']);
?>
<tr class="items_wrap items_wrap<?php echo $item_id; ?>">
<td><?php echo $sl_no++; ?></td>
<td><?php echo $item_name ?></td>
<td><?php echo $quantity ?></td>
<td><?php echo $item_price ?></td>
<td><i class="fa fa-times"></i></td>
</tr>
</tbody>
</table>
<?php
}
If you're getting a response in the console, then the issue must be with your HTML. I think part of the problem is you've created a section on the HTML page wiht a class that is the same as the table the AJAX call is bringing into the page. I would suggest changing the HTML element to us an ID instead. Something like
<div id="products-table"></div>
And then change your JavaScript to
function add_to_cart(item_name,item_price){
$('.user-info').slideUp('1200');
$('.cart-status').slideDown('1200');
var dataString = "item_name=" + item_name + "&item_price=" + item_price + "&page=add_to_cart";
$.ajax({
type: "POST",
url: "php/processor/processor.php",
data:dataString,
beforeSend:function(){
$("#products-table").html('<h3>Your Cart Status</h3><img src="images/loading.gif" align="absmiddle" alt="Loading...." class="center" /><br><p class="center">Please Wait...</p>');
},
success: function(response){
console.log(response);
$("#products-table").html(response);
}
});
}
If you stay with the class names you've used, subsequent updates are going to have problems because you'll have 2 elements on the page with the same class. Your script could potentially be confused about which one to change.
If this is your actual code, then you have a syntax error in your PHP file. There are a missing close bracket for:
if(isset($_POST['item_name']) && !empty($_POST['item_name']) && isset($_POST['item_price']) && !empty($_POST['item_price']))
The second problem is, you are not print anything, if this condition has failed.
Note
You do not need to use isset, if you are checking empty. empty will return false, if the variable not set.
You can debug your respons by check NET tab in your web developer tools, or see, what is the response of the AJAX.

Categories