Pass numeric value from one php file to another - javascript

I have 2 php files, the first file is the index file where the pagination is found, and an ajax script for getting the table data which is found on the second file.
The ajax script from the first file is also sending sorting option that the user requested to the second file. The second file will then sort and calculate the number of result that is found.
Since the pagination is in first file, I need the result from the second file to calculate the proper number of pages for my pagination.
I have this pagination script
<ul class="pagination mx-1 mx-md-0">
<?php
if(!empty($total_pages)){
for($i=1; $i<=$total_pages; $i++){
if($i == 1){
?>
<li class="pageitem active" id="<?php echo $i;?>">
<a href="JavaScript:Void(0);" data-id="<?php echo $i;?>" class="page-link" ><?php echo $i;?></a>
</li>
<?php
}
else {
?>
<li class="pageitem" id="<?php echo $i;?>">
<?php echo $i;?>
</li>
<?php
}
}
}
?>
</ul>
I have this ajax script for my first file
$("#target-content").load("pagination.php?page=1");
$(".page-link").click(function(){
var id = $(this).attr("data-id");
var sort = $("#myselect").val();
var select_id = $(this).parent().attr("id");
var categorytype = MyApp.categorytypes;
$.ajax({
url: "secondfile.php",
type: "GET",
data: {
page : id,
sorted:sort,
categorytype:categorytype
},
cache: false,
success: function(dataResult){
$("#target-content").html(dataResult);
$(".pageitem").removeClass("active");
$("#"+select_id).addClass("active");
}
});
});
for my 2nd file I have this code
<? php
$limit= 2;
$sqls = "SELECT COUNT(id) FROM producttable $categorytypes ORDER BY $sortertype
$sorterorder LIMIT $start_from, $limit";
$rs_results = mysqli_query($conn, $sqls);
$row = mysqli_fetch_row($rs_results);
$total_records = $row[0];
$total_pages = ceil($total_records / $limit);
?>
and to pass my data to the first file I tried creating another ajax script
$(document).ready(function() {
var numb = <?php echo $total_pages ?>;
$.ajax({
url: "inde.php",
type: "GET",
data: {
numb:numb
}
});
});
and tried to get the values in the first file using GET [] but it seems that it doesn't work. Am I doing something wrong here? should I rewrite my whole code?
My displayed tables are going well, its just the number of pages that are shown when I'm sorting the data in my table.

Here is what I would do. Drop that last code bit you showed and in your second .php file echo out the total_pages like this
<? php
$limit= 2;
$sqls = "SELECT COUNT(id) FROM producttable $categorytypes ORDER BY $sortertype
$sorterorder LIMIT $start_from, $limit";
$rs_results = mysqli_query($conn, $sqls);
$row = mysqli_fetch_row($rs_results);
$total_records = $row[0];
$total_pages = ceil($total_records / $limit);
echo $total_pages;
?>
then in your ajax script, update your pagination using JS and you have your $total_pages passed through as dataResult
$.ajax({
url: "secondfile.php",
type: "GET",
data: {
page : id,
sorted:sort,
categorytype:categorytype
},
cache: false,
success: function(dataResult){
// dataResult will contain $total_pages
$("#target-content").html(dataResult);
$(".pageitem").removeClass("active");
$("#"+select_id).addClass("active");
updatePagination(dataResult);
}
});

Related

Display content from the database when a div with an ID is clicked (AJAX)

I have a list of divs with unique IDs (they are inserted from my database). When I click on one of them I want to display content from my database in another div. For example, I have a div with class pizza. The query should look like this: SELECT * FROM product WHERE name = 'pizza'. So depending on what div you click you get different content. The code below doesn't work and is incomplete. I was trying to do some research myself, but I couldn't find anything useful.
//head
<script>
$(function () {
$('.product').on('click', function (e) {
e.preventDefault();
$.ajax({
type: "post",
url: 'php/recipe-container.php',
data: new FormData(this),
processData: false,
contentType: false,
success: function(response) {
$(".display_recipe").html(response);
},
error: function () {
}
});
});
});
</script>
//HTML
<div class="product" id="pizza">pizza</div>
<div class="product" id="lasagna">lasagna</div>
<div class="product" id="sushi">sushi</div>
<div class="display_recipe"></div>
// PHP (recipe-container.php)
<?php
function display_recipe(){
$con = mysqli_connect("localhost", "root", "", "cookbook");
$product = "'pizza'"; //just a placeholder
$sql = "SELECT * FROM product WHERE name = $product";
$res = mysqli_query($con,$sql);
while($row = mysqli_fetch_assoc($res)) {
$name = $row['name'];
$description = $row['description'];
$date = $row['date'];
echo $name;
echo "<br>";
echo $description;
echo "<br>";
echo $date;
echo "<br>";
}
mysqli_close($con);
}
display_recipe();
?>
Right now when I click the button nothing happens, even "pizza" placeholder doesn't work. Is there a simple way to do it?
JS file (AJAX code)
You can get the id attribute on click of the div with the class 'product' as coded below:
jQuery(function () {
jQuery('.product').on('click', function (e) {
var product = jQuery(this).attr('id');
$.ajax({
type: "post",
url: 'php/recipe-container.php',
data: {data:product},
processData: false,
contentType: false,
success: function(response) {
$(".display_recipe").html(response);
}
});
});
});
PHP file: get the posted data in this file use it in a query to fetch the result and return the result to the AJAX success handler as a response.
To fetch the data posted from the ajax in this php file you can use $_POST['data'] as stated below:
$product = $_POST['data'];
Use that variable in your sql query to fetch the result and then change the structure of your response as stated below:
//saving the html response in a variable named "response"
$response = $name.'<br>';
$response .= $description.'<br>';
$response .= $date.'<br>';
//echo response will send the response variable back to the AJAX success handler.
echo $response;

Php updating a span using javascript/ajax is not working properly

I am updating a span using below script but it is working if condition is false and if condition is true it does not update.
What i observed that it executes the same false condition and when i click the second time it updates the quantity but less 1 number than the actual quantity of records in the database.
Like total records are 2 and when i click submit the script runs and if condition is true in the database records are updated = 3 but in the span it shows 2.
When i click 2nd time and in the database records are = 4 and in the span it shows 3.
Button where i click and run the script
<input onclick='updateTitems("1");' type="submit" class="btn-style-2 mg-left-5" value="ADD TO CART">
script
<script>
function updateTitems(id) {
var uid = "<?php echo $ses_mem; ?>";
$.ajax({
type: "GET",
url: 'inc/menu_update_total_items.php',
data: "id=" + id + "&uid=" + uid,
success: function(data) {
$('.summary12').html(data);
}
});
}
</script>
menu_update_total_items.php
$user_id = $_GET['uid'];
$item = "select count(*) as records
from orders_temp
where user_id = '".$user_id."'
";
$itemq = $dba->query($item);
$itemr = $itemq->fetch_assoc();
$count = $itemr['records'];
---------------------------------
$itemx = "select count(*) as records
from orders_temp
where date = now()
and user_id = '".$user_id."'
";
$itemqx = $dba->query($itemx);
$itemrx = $itemqx->fetch_assoc();
$check = $itemrx['records'];
<span class="summary12"><!-- class of javascript -->
<?php
if ($check == 1){
echo $count+1;
}else{
echo $count;
}
?>
Items
</span>
After trying lot of things i came up with the following solution and the issue has been solved.
Please need your opinion on this. Thanks
Button
<input onclick='updateTitems();' type="submit" class="btn-style-2 mg-left-5" value="ADD TO CART">
Script
function updateTitems(){
$.ajax({
url: "menu_update_total_items.php",
cache: false,
success: function(data){
$(".summary12").html(data);
//div or span reload script after success
setInterval(function () {
$('.summary12').load('inc/menu_update_total_items.php');
}, 1000);
}
});
}
menu_update_total_items.php
<?php
#session_start();
include ("inc/db.php");
$ses_mem = session_id();
$items = "select count(*) as trecords
from orders_temp
where user_id = '".$ses_mem."' ";
$item = $dba->query($items);
$count = $toitemszx->fetch_assoc();
?>
<a href="cart/review" class="cart-link">
<i class="fa fa-shopping-basket"></i>
<?php echo $count['trecords']; ?>
Items
</a>

Count every onclick event in php

JS
<script>
function myAjax() {
$.ajax({
type: "POST",
url: 'ajax.php',
data:{action:'call_this'}
});
</script>
HTML
<a href="'. $row['link'] .'"target="_blank" onclick="myAjax()">
PHP
<?php
require ("static/php/inc/betaconfig.inc.php");
if($_POST['action'] == 'call_this') {
$conn->query("UPDATE users SET clicks = (clicks + 1) WHERE id = 13");
}
?>
Normally it should be $uid instead of 13 but I don't know how to do that too...
First of all, why this doesnt work ? 2nd $uid is $id = $_REQUEST['id']; and then
$sql = "SELECT * FROM `link` WHERE id = '$id'";
$result4 = $conn->query($sql);
while($row = $result4->fetch_assoc()) {
$uid = $row['userid'];
}
so the best thing that instead of 13 I could use $uid

Trouble with auto refresh in table

I have this index.php file to show some stuff in tables from loop:
$sql = 'SELECT id FROM usertbl';
$stmt = $hund->runQuery($sql);
$stmt->execute();
$row = $stmt->fetchALL(PDO::FETCH_ASSOC);
<?php foreach ($row as $runloop) { ?>
<table><th> <?php echo $runloop['id']; ?> </th></table>
<?php } ?>
However, I wish to have auto refresh for those tables. So I have this new file data.php and a updated index.php:
data.php:
$sql = 'SELECT id FROM usertbl';
$stmt = $hund->runQuery($sql);
$stmt->execute();
$row = $stmt->fetchALL(PDO::FETCH_ASSOC);
print_r($row);
index.php:
<div id="show"></div>
<script type="text/javascript">
$(document).ready(function() {
setInterval(function () {
$('#show').load('data.php')
}, 3000);
});
</script>
<?php foreach ($row as $runloop) { ?>
<table><th> <?php echo $runloop['id']; </th></table>
<?php } ?>
This will refresh and print the output in the above <div>:
<div class="show"></div>
And it works great, but I don't really have any clue how to put that inside the loop for the tables, just as the first index.php file. Any suggestions of a direction to take in this matter?
You can use ajax to call data.php and return the response in json format for a better approach
Try:
js
function populate(){
var items= [];
$.ajax({
url: 'data.php',
type: 'GET',
dataType: 'json',
success: function(data){
//do something with data here
console.log(data);
//loop through data and push to array
$.each(data, function(i,v){
items.push('< th >'+v+'< /th >');
});
//join array and append to table
$('#sampleTable tbody').html(items.join(','));
},
error: function(err){
console.log(err.responseText);
}
});
}
//call populate every 10 secs (example only , you can change to how many seconds you like)
setTimeout(function(){
populate();
},10000);
data.php
$sql = 'SELECT id FROM usertbl';
$stmt = $hund->runQuery($sql);
$stmt->execute();
$row = $stmt->fetchALL(PDO::FETCH_ASSOC);
echo json_encode($row);
In this line you forgot to close <?php ...
Possibly that's why foreach loop doesn't work correctly
<?php foreach ($row as $runloop) { ?>
<table><th> <?php echo $runloop['id']; ?></th></table>
<?php } ?>
Put these lines in data.php where print_r() is.

Ajax delete data from database function not working

I have created an AJAX that can store and delete data from database. The adding of data is working fine also the delete function is working fine when the page is already refresh but the delete is not working when data is newly added or when the page is not refresh.
This how it works. When a new data is added, the data will display, the user has an option to delete the data or not. The data has a "X" to determine that it is a delete button. Right now, The delete only works when the page is refresh.
This my SAVING script, as you can see if saving is success it displays the data automatically, together with the span that has the delete function.
$("#wordlistsave").click(function()
{
var user = $("#getUser").val();
var title = $("#wordbanktitle").val();
var words = $("#wordbanklist").val();
var postID = $("#getPostID").val();
var ctrtest = 2;
var testBoxDiv = $(document.createElement('div'))
.attr("id", words);
var dataString = 'user='+user+'&title='+title+'&words='+words+'&id='+postID;
<?php if (is_user_logged_in()): ?>
$.ajax({
type: "POST",
url: "<?=plugins_url('wordlistsave.php', __FILE__ )?>",
data: dataString,
cache: false,
success: function(postID)
{
testBoxDiv.css({"margin-bottom":"5px"});
testBoxDiv.after().html('<span id="'+words+'" style="cursor:pointer">x '+postID+'</span>&nbsp&nbsp<input type="checkbox" name="words[]" value="'+ words+ '">'+words );
testBoxDiv.appendTo("#test_container");
ctrtest++;
}
});
<?php else: ?>
alert('Fail.');
<?php endif; ?>
});
This is my delete function , when the user click the "X" span, the data will be deleted, but this only works after the page is refresh.
$("span").click(function()
{
var queryword=$(this).attr('id');
var postIDdel = $("#getPostID").val();
var dataString = 'queryword='+queryword+'&postID1='+postIDdel;
<?php if (is_user_logged_in()): ?>
$.ajax({
type: "POST",
url: "<?=plugins_url('worddelete.php', __FILE__ )?>",
data: dataString,
cache: false,
success: function(html)
{
$('div[id="'+queryword+'"]').remove();
}
});
<?php else: ?>
<?php endif; ?>
});
This is my HTML, the one that holds the querying of data and displaying of data.
<?php
global $wpdb;
$query_wordbanklist = $wpdb->get_results("SELECT meta_value, meta_id FROM wp_postmeta WHERE post_id = '$query_id' AND meta_key = '_wordbanklist'");
if($query_wordbanklist != null)
{
echo "<h3> Wordlist </h3>";
foreach($query_wordbanklist as $gw)
{
?> <div id="<?php echo $gw->meta_value ?>">
<span id="<?php echo $gw->meta_value ?>" style="cursor:pointer">x</span> &nbsp&nbsp<input type="checkbox" name="words[]" value="<?php echo $gw->meta_value ?>"><?php echo $gw->meta_value; ?>
</div>
<?php
}
}
?>
All I wanted to achieve is to make the delete function works right after the data is stored. Right now it only works when the page is refresh. Any idea on this?
Perhaps try this...
$(document).on('click', 'span', function() {
// delete stuff in here
}

Categories

Resources