laravel foreach doesn't load the latest saved data - javascript

I'm trying to make a shopping cart using laravel 7 and ajax. When i press add product, it save the product into the cart in the database. If the product is already in the cart, it will just add 1 to the quantity. If not, it will create a new order item in the cart. Then, it will return an output variable with html content through json response. Then i append the html data using javascript. The problem is when i add a product and the product isn't in the cart so it created a new order item. The json response doesn't seem to load the latest order item in the html. But when i add that same product the second time, it managed to append the html. Does the foreach didn't get the latest data from database?
This is the function in the controller
public function addItem($product_id, Request $request){
$order_id = auth()->user()->waitingOrder->first()->id;
$order = Order::find($order_id);
$bingo = false;
foreach ($order->orderItems as $key => $order_item) {
if ($product_id == $order_item->product_id) {
$order_item->quantity = $order_item->quantity + 1;
$order_item->save();
$bingo = true;
break;
}
}
if ($bingo == false) {
$new_item = new OrderItem();
$new_item->order_id = $order_id;
$new_item->product_id = $product_id;
$new_item->save();
}
$output = "";
foreach ($order->orderItems as $item) {
$output .= '<tr>'.
'<td align="left" width="15%">'.
'<img style="height: 80px; width: 80px;" src="'. asset('img/products/' . $item->product->image) .'">'.
'</td>'.
'<td align="center" width="20%">'.
$item->product->name .
'</td>'.
'<td>'.
rupiah($item->product->price) .
'</td>'.
'<td width="14%">'.
'<input type="number" class="form-control" name="quantity" value="'. $item->quantity .'" min="1" max="'. $item->product->stock .'">'.
'</td>'.
'<td>'.
rupiah($item->product->price * $item->quantity) .
'</td>'.
'<td>'.
'<a href="'. route('kasir.remove.item', $item->product->id ) .'" class="remove-btn">'.
'<span class="icon_close"></span>'.
'</a>'.
'</td>'.
'</tr>';
}
return response($output);
}
This is the javascript code
$(document).on('click', '.add-btn', function(event){
event.preventDefault();
$.ajax({
url: $(this).attr('href'),
success:function(data){
$('#orderItems').html(data);
}
});
});
function order(){
var customer_name = $('#customer_name').val();
var link = $('#order-btn').attr('href');
if (link != '#') {
$.ajax({
type: 'POST',
url: link,
data: {name:customer_name},
success:function(data){
$('#order_id').val(data.order_id);
$('#customer_name').prop('disabled', true);
$('#order-btn').attr('href', '#');
$('#cart-total').html("")
$('#cart-total').html(data.output)
}
});
}
}

Related

How to add more filter yet pager using Ajax

I have the following ajax structure that allows me to display 10, 25, 50 and, 100 records
$(function() {
$(document).on('click', '.pagination li a', function(evt) {
evt.preventDefault();
url = $(this).attr('data-target');
ajaxLoad(url);
});
$('#amount_show').change(function(evt) {
evt.preventDefault();
ajaxLoad('pagination.php');
});
ajaxLoad('pagination.php');
function ajaxLoad(url) {
query_params = {
amount_show: $('#amount_show').val()
};
$('.data-pagination').html('<div class="loading">Loading...</div>');
$.ajax({
type: "GET",
url: url,
data: $.param(query_params),
success: function(data) {
$('.data-pagination').fadeOut('1000', function() { $(this).html(data) }).fadeIn('1000');
}
});
}
});
According to what I selected from the following HTML structure, ajax, it brings me the results sent correctly.
<select id="amount_show" name="amount_show">
<option value="10" selected>10</option>
<option value="25" >25</option>
<option value="50" >50</option>
<option value="100">100</option>
</select>
But I still can't understand how I can add more filters to my pager, for example type of client, type of user or a search engine.
Or search filter by date, I want to add so many filters to my pagination, but for this I need a little push of how to proceed.
This is my PHP code, can you explain to me how I can add more filters to the pager.
<?php
$strs = '';
$pagination_page = 'pagination.php';
$defaul_records = 10;
if (isset($_GET['page'])) {
$page = $_GET['page'] ? : '';
} else {
$page = 1;
}
if (isset($_GET['amount_show'])) {
$records_by_page = $_GET['amount_show'];
} else {
$records_by_page = $defaul_records;
}
$localization_sql = ($page - 1) * $records_by_page;
$stmtPD = $con->prepare("SELECT idCliente,
nomCliente
FROM cliente
ORDER BY idCliente DESC LIMIT $localization_sql, $records_by_page");
$stmtPD->execute();
$stmtPD->store_result();
if ($stmtPD->num_rows > 0):
ob_start();
$strs .= '<table id="data-table" class="table bootgrid-table">
<thead>
<tr>
<th>ID</th>
<th>CLIENTE</th>
<th>ACCIÓN</th>
</tr>
</thead>
<tbody>';
$stmtPD->bind_result(
$idCliente,
$nomCliente
);
while ($stmtPD->fetch()) {
$strs .= '<tr>
<td>'.$idCliente.'</td>
<td>'.$nomCliente.'</td>
<td>
<span class="view_data" id="'.$idCliente.'">Ver</span>
<span class="edit_data" id="'.$idCliente.'">Editar</span>
</td>
</tr>';
}
$stmtPD->close();
$strs .= '</tbody></table><div class="pagination"><ul class="pagination">';
$stmtPD = $con->prepare("SELECT * FROM cliente");
$stmtPD->execute();
$stmtPD->store_result();
$BD_records = $stmtPD->num_rows;
$stmtPD->close();
$con->close();
$total_page = ceil($BD_records / $records_by_page);
$prev = $page - 1;
$next = $page + 1;
if ($prev > 0) {
$strs .= "<li><a data-target='" . $pagination_page . "?page=1'><i class='icon-angle-double-arrow'></i></a></li>";
$strs .= "<li><a data-target='" . $pagination_page . "?page=$prev'><i class='icon-angle-left'></i></a></li>";
}
for ($i = 1;$i <= $total_page;$i++) {
if ($page == $i) {
$strs .= "<li><a class='page-link active' >" . $page . "</a></li>";
} else {
$strs .= "<li><a class='page-link' data-target='" . $pagination_page . "?page=$i'>$i</a></li>";
}
}
if ($page < $total_page) {
$strs .= "<li><a class='page-link' data-target='" . $pagination_page . "?page=$next'><i class='icon-angle-right'></i></a></li>";
$strs .= "<li><a class='page-link' data-target='" . $pagination_page . "?page=$total_page'><i class='icon-angle-double-right'></i></a></li>";
}
$strs .= '</ul></div>';
echo $strs;
else:
$stmtPD->close();
echo "no records..";
endif;
?>
Example of my table data:
idCliente nomCliente typeCliente dateCliente
1 Google VIP 2021-03-30 22:00:58.277400
2 StackOverflow PRIME 2021-03-30 21:00:58.277400
I would guess that pagination.php has code to connect to the database, construct a SELECT statement to fetch the desired rows, then deliver them back to the frontend?
I see ?page=<<number>>, but nothing (yet) about page size, nor about filtering.
Suggest constructing this inside the JS and send it:
pagination.php?page=3&page_size=25&color=green&size=big
Then, inside the PHP, use $_GET to see which arguments were sent, and react to whatever parameters are passed (and ! empty()).
Then construct the desired query, something like:
SELECT ...
FROM ...
WHERE color = 'green'
AND size = 'big'
ORDER BY ...
LIMIT 50, 25
Peform that; get the results; json_encode() them; and respond to the AJAX query.
Then, inside the JS, you need a callback to receive that result and present it to the user.
You might be better off with XHR instead of AJAX, since you don't really need the "Asynchronous" part of AJAX.

How do I pass data from an AJAX PHP result to a seperate PHP function through AJAX?

When selecting an option belonging to one PHP file, my goal is to pass this option's current row ID to a seperate PHP file so that I can use it there.
This is from the file I'm trying to fetch:
echo '<div id="folderContentTableContainer">';
echo '<table class="table table-searchable-asc">';
if (count($contents) > 0) {
// Start of table
foreach ($contents as $content) {
echo '<tr>';
echo '<td>' . $content['title'] . '</td>';
echo '<td>' . $content['id'] . '</td>';
echo '<td><a id="cloneContent" class="fa fa-clone"></a></td>';
echo '<td><a id="removeContent" class="fa fa-trash"></a></td>';
echo '</tr>';
}
} else {
// return nothing
Now I'll want to use $content['id'] in a seperate PHP file to query the database.
I'm currently fetching the file content like this:
$('#content').on('click', '#folderContainerUl li', function () {
var id = event.target.id;
$.ajax({
url: '<?php echo ROOTDIR; ?>pages/ajax/getPasswordsFolderContent.php',
type: 'POST',
data: ({
uuid: '<?php echo $_GET['uuid']; ?>',
folder: id
}),
success: function (content) {
$('#folders-content-container').html(content);
}
})
});
The file content will then be placed into the data from getPasswordsFolders.php, which includes this:
echo '<div id="folderUlContainer">';
echo '<ul id="folderContainerUl">';
foreach ($folders as $folder) {
$children = $mfdb->select('password_folders', '*', array('AND' => array('parent_id' => $folder['id']), 'ORDER' => 'title ASC'));
if (count($children) > 0) {
echo '<li id="' . $folder['id'] . '">' . $folder['title'] . '</li>';
echo '<ul>';
foreach ($children as $child) {
echo '<li id="' . $folder['id'] . '">' . $child['title'] . '</li>';
}
echo '</ul>';
echo '</li>';
} else {
echo '<li id="' . $folder['id'] . '">' . $folder['title'] . '</li>';
}
}
echo '</ul>';
echo '</div>';
firstly, as Rory McMcrossan said, you are duplicating the IDs, try to use classes instead.
then you can send an ajax request as following:
$('.cloneContent').click(function(){
var id = $(this).parent().prev().text();
$.ajax({
url:'your-url?id='+id,
method:'get',
...
});
//OR
$.ajax({
url:'your-url',
method:'post',
data:{id:id},
...
});
});
EDIT:
to simplify your work you can pass the id as an attribute of the anchor a as:
echo '<td><a class="fa fa-clone cloneContent" data="'.$content['id'].'"></a></td>';
so now you can get the id by:
var id = $(this).attr('data');
instead of: var id = $(this).parent().prev().text();

Get data from Database Using Ajax and PHP and Return Result as Dropdown list

I have the idea of what i wanted but need assistance on how to get it done.Below is the scenerio: I have a two dropdwon. The First dropdown is fetched from the DB, which works fine. At the change event of the first dropdown,the system should go to the Database, and fetch the result into the next dropdown. see what I have done so far for assistance:
JQUERY SECTION
<script type="text/javascript" src="includes/scripts/newJquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#locate").change(function(){
var selectedloc = $("#locate option:selected").val();
$.ajax({type: "POST",url:"process-loc.php",data:{loca:selectedloc}}).done(function(data){
var ans=jQuery.parse(data);
//using php-mysql before
var ps = ans.res;
$("#subloc").html(ps);
});
});
});
</script>
FrontEnd(HTML)
<tr>
<th>Primary Location:</th>
<?php
$result = mysqli_query($connection,"SELECT * FROM tab_location");?>
<td>
<select name="locate" class="form-control" id="locate">
<option>Select Main Location</option>
<?php while($rw = mysqli_fetch_array($result)){ ?>
<option value="<?php echo $rw['location_name'];?>"><?php echo $rw['location_name'];?></option>
<?php };?>
</select>
</td>
</tr>
<tr>
<th>Sub Location:</th>
<td id="subloc"></td>
</tr>
Process-loc.php
if(isset($_POST["loca"])){
include 'includes/session.php';
include 'includes/db_connection.php';
include 'includes/functions.php';
$main = $_POST["loca"];
$gets = "SELECT * FROM tab_fltlocation WHERE mainloc='".$main."'";
$get = mysqli_query($connection,$gets);
$gt = mysqli_fetch_array($get);
//$nos= $gt['opsNo'];
if(mysqli_num_rows($get)>=0)
{
echo json_encode(array("res"=>$gt));//or do a dropdown using <select name='subloc'><option value=$gt['loc']>$gt['loc']</option></select>
}else{
echo json_encode(array("res"=>"0"));
}
}
?>
This is what I wants to be displayed on the Front End page for the use:
$gt['loc']
How can I achieve this.
$query = "
SELECT
tariff_name
FROM tariff_setting";
$result = mysqli_query($this->_connection, $query);
while ($row = mysqli_fetch_assoc($result))
$response[] = $row['tariff_name'];
}
$tarrifList = json_encode($response);
// $tarrifList is the response and sent it in json encode format and decode on ajax success
// Javascript Process
var obj = JSON.parse(resdata);
var areaOption = "<option value=''>Select State</option>";
for (var i = 0; i < obj.length; i++) {
areaOption += '<option value="' + obj[i] + '">' + obj[i] + '</option>'
}
$("#patientSelectState").html(areaOption);
You can change your AJAX processor to do this:
Process-loc.php
/* Above code the same */
if(mysqli_num_rows($get)>=0) {
$out = '<select id="selSubLoc"><option value="">Choose One:</option>';
foreach($gt AS $loc){
$seld = ($_POST['loca'] == $loc) ' selected' ? : '' ;
$out .= '<option value="' .$loc. '" ' .$seld. '>' .$loc. '</option>';
}
$out .= '</select>';
}else{
$out = 0;
}
echo $out;
And change your front-end code's AJAX routine to be like this:
$.ajax({
type: "POST",
url:"process-loc.php",
data:{loca:selectedloc}
}).done(function(recd){
$("#subloc").html(recd);
});
The data received back from PHP will be in HTML format unless you use dataType: to change it, so you can build the HTML over on the PHP side and then just plop it into the #subloc table cell.
On the event of the first box call the function containing the ajax which would retrieve information from the database. This ajax call will get data according to the first input.
Now query your database and echo the results in a foreach loop(you can make a tag there only).
In the ajax 'success:' catch the data and display it.
//from the database
foreach ($info as $product)
{
echo "<option value=".$product['childsticker_id'].">".$product['name']</option>";
}
//ajax call page
success: function(result)
{
$("#states").html(result);
}
http://www.9lessons.info/2010/08/dynamic-dependent-select-box-using.html

Table does not disappear on AJAX call

I am trying to remove to this table on successful delete from an AJAX to PHP call.
Below is the function ,
list.php
<script type="text/javascript">
function massDelete()
{
if (!confirm("Are you sure"))
{
return false;
}
else
{
var selecedids = $("#selectedids").val();
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("success").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "ajax_delete.php?massDelete=" + selectedids.value, true);
xhttp.send();
}
}
return false;
}
</script>
the above code successfully gives me the selected ID for deletion
on this PHP side which is on another File
ajax_delete.php
<?php
if (!empty($_REQUEST['massDelete'])) {
$selectId = $_REQUEST['massDelete'];
$finalId = ltrim($selectId, ",");
$sql = mysql_query("delete from contact_form where contactUser_id in ($finalId)", $con);
if ($sql) {
// echo '<script>';
//echo 'var parent = document.getElementById("fullTable")';
//echo 'element.remove(parent)';
//echo '</script>';
echo "sucess deleted";
} else {
echo "Please select a Contact to delete";
}
}
?>
The response does give me the successful message, but somewhere I want to disappear the below HTML table in response
list.php
<?php
echo '<table id="fullTable">';
echo "<tr><td> ";
echo '<input type="checkbox" name="checkAll" id="checkAll"/></td>';
echo '<td colspan="8" align="right">';
echo '<button type="submit" onClick="return massDelete()" name="delete" class="deleteall" id="deleted">Delete All</button></td>';
echo "</tr>
<tr>
<th></th>
<th>FIRST NAME</th>
<th>LAST NAME</th>
<th>EMAIL</th>
<th>PHONE</th>
<th>FAX</th>
<th></th>
<th></th>
<th></th>
</tr>";
while ($row = mysql_fetch_array($results)) {
echo '<div id="checkboxlist">';
echo '<tr class="show">';
echo '<td><input name="checkbox[]" type="checkbox" class="checkbox1" value="' . $row['contactUser_id'] . '" id="Checkbox1"></td>';
echo '<td>' . $row['first_name'] . '</td>';
echo '<td>' . $row['last_name'] . '</td>';
echo '<td>' . $row['email'] . '</td>';
echo '<td>' . $row['phone'] . '</th>';
echo '<td>' . $row['fax'] . '</td>';
echo '<td>Edit</td>';
echo '<td><a class="delete" href="#" id="' . $row['contactUser_id'] . '">Delete</a></td>';
echo '<td>View</td>';
echo '</div>';
}
} else {
echo '<td colspan="9"><h1>No contacts found.</td></h1>';
}
?>
I am confused to what should I do so that if one row is deleted than only that row disappears,
but if all the checkboxes are selected for deletion, than on sucess, tha whole table should disappear..
So it sounds like the php successfully deletes it since when you refresh the page the correct data shows up.
But if the page has to be refreshed for it to show up properly, you need to make sure you are returning the correct information, and parsing it correctly. Just console.log() the response xhttp.responseText, and see if the correct data is returned, and then double check you are parsing it correctly (changing the dom appropriately).
You don't need to refresh your page to show it's correct. You need to use javascript to remove the row on success. Here's the basics:
var deletedRow = $('#fullTable');
$.post('script.php', {data:data}, function(){
if(data == "success"){
deletedRow.remove(); //This will remove the row from the view
}
});
Ajax can return a call and you give a statement that shows if success, you have to have javascript actually delete it. Yes, we know it's removed from the database, so you can successfully remove the view from the page.
UPDATE This is using jQuery, not pure javascript. But it's only an example to show that you need to delete the element using javascript and it won't just disappear because it's not in your database anymore.
Finally after referring to this remove any element using Jquery
I found the solution, and I also changed the AJAX function code which is mentioned below,
function massDelete()
{
var element = $(this);
var selecedids = $("#selectedids").val();
var info = 'massDelete=' + selectedids.value;
if(confirm("Are you sure you want to delete this?"))
{
$.ajax({
type: "POST",
url: "ajax_delete.php",
data: info,
success: function(){
}
});
$this.parent("#fullTable").load("list.php");
}
return false;
}
the $this.parent("#fullTable").load("list.php"); statement reloaded that table hence reflecting only those information which are present in the database.

Php ajax sort data based on user selected input

I have a html form in which user can select an option upon which ajax call should be fired to php controller.
<form action="<?php echo URL . 'task/show_list/' . $this->tasks[0]->list_id;?>" method="GET" id="#sortTaks">
<select name="sort_task" id="selectSortTask">
<option value="" selected="selected">Sort by:</option>
<option value="byName">Name</option>
<option value="byDeadline">Deadline</option>
<option value="byPriority">Priority</option>
<option value="byStatus">Status</option>
</select>
<input type="submit" value="Submit">
</form>
Now, i would like that sort functionality provided asynchronously with ajax. This is the corresponding php code:
//controller
public function show_list($list_id)
{
if (isset($list_id)) {
$task_model = $this->loadModel('TaskModel');
$check = $task_model->checkUserPermission($list_id);
if ($check) {
$tasks = $task_model->showTasks($list_id);
$this->view->tasks = $tasks;
$this->view->render('task/task');
} else {
header('location:' . URL . 'dashboard/index');
}
} else {
header('location:' . URL . 'dashboard/index');
}
}
//model
public function showTasks($list_id)
{
if (isset($_GET['sort_task']) and !empty($_GET['sort_task'])) {
$sort_parameter = strip_tags($_GET['sort_task']);
$sort_order = $this->sortData($sort_parameter);
$sort_order = 't.task' . $sort_order;
} else {
$sort_order = 't.task_name';
}
$sql = "SELECT t.task_name, t.task_id, t.task_priority, t.task_deadline, t.task_completed, l.list_id
FROM task AS t
LEFT JOIN list AS l ON l.list_id = :list_id AND l.list_id = t.list_id
WHERE l.user_id = :user_id
ORDER BY $sort_order";
$query = $this->db->prepare($sql);
$query->execute(array(':list_id' => $list_id, ':user_id' => $_SESSION['user_id']));
return $query->fetchAll();
}
//view snippet
echo '<td>' . $value->task_name . '</td><td>' . $priority . '</td><td>';
echo $task_deadline->format('l jS \of F Y h:i:s A');
echo '</td><td>';
echo $overdue_until->format('%R %a day/s, %h hours, %i minutes');
echo '</td><td>' . $status . '</td>';
echo '<td><a href="' . URL . 'task/edit_task/' . $value->list_id . '/' . $value->task_id . '">Edit</td>';
echo '<td><a href="' . URL . 'task/delete_task/' . $value->list_id . '/' . $value->task_id . '">Delete</td>';
echo '<td><a href="' . URL . 'task/completed/' . $value->list_id . '/' . $value->task_id . '">Completed</td>';
echo '</tr>';
What is the best approach in solving this problem? I'm a little bit confused with how should ajax call look like regarding mvc structure and presenting sorted data back to user.
Any help is much appreciated.
For now i have this:
$(document).ready(function(){
$('#selectSortTask').change(function(e){
e.preventDefault();
var sortParam = $('#selectSortTask').val();
$.ajax({
url: $(this).attr('action'),
type: "GET",
data: {sort_task: sortParam},
dataType: 'json',
success: function(data){
alert(data);
},
error: function(error){
alert(error);
}
});
return false;
});
});
Which alerts object Object as error. How to modify this ajax call and model/view/controller to get desired result? Alerts are for debugging purposes.

Categories

Resources