Using Ajax to get and show mysqli query results - php

I'm practicing Ajax by making an app that checks the content of a database table and inserts it into my page asynchronously, only the first row of the table is printing and I'm not sure why. This is my code:
index.php - Here is where I create the page with an empty space in #result_table that should get filled by the table fetched by places.php
<div class="row">
<div class="col-xs-3">
<button type="button" class="btn btn-lg btn-default" id="showPlaces" name="showPlaces">Mesas</button>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<table class="table table-striped">
<thead>
<tr>
<th>Nombre</th><th>Piso</th><th>Cliente</th><th>Mesero</th><th>Area</th><th>Estado</th>
</tr>
</thead>
<tbody id="result_table">
</tbody>
</table>
</div>
</div>
places.php - Here I make the query and return(?) the data
<?php
include("con.php");
mysqli_select_db("unicentaopos", $c);
$result = mysqli_query($c,"SELECT * FROM places");
while ($places = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>". $places ['NAME']."</td>";
echo "<td>". $places ['FLOOR']."</td>";
echo "<td>". $places ['CUSTOMER']."</td>";
if (!$places['WAITER']) {
echo "<td>" . "VACIO" . "</td>";
} else {
echo "<td>". $places ['WAITER']."</td>";
}
echo "<td>". $places ['AREA']."</td>";
echo "<td>". $places ['ESTADO']."</td>";
echo "</tr>";
}
mysqli_free_result($result);
?>
script.js - Here I use jQuery to make the Http request
$( document ).ready(function() {
$('#showPlaces').click(function(){
$.ajax({
type:'GET',
url: 'places.php',
dataType: 'html',
success: function(result){
$('#result_table').html(result);
} // End of success function of ajax form
}); // End of ajax call
});
});
con.php - Here I connect to the database
<?php
$c = mysqli_connect("localhost","root","root","unicentaopos");// Check connection
if (mysqli_connect_errno()) { // Si hay error lo menciona en alerta.
echo '<div class="alert alert-danger">';
echo 'Failed to connect to MySQL: ' . mysqli_connect_error();
echo '</div>';
} else { // Si no hay error.
}
?>
I've been stuck on this for a while, could you guys help me pinpoint the problem? I guess it's either the way i'm returning the data from places.php, or I'm making a mistake in the connection, wich would be weird since that very same code worked for a simple example I did a while ago.
Please remember, I'm new to Ajax so anything you can tell me that helps me improve will be very welcome.
Fixed it with help of the comments and edited the post with the working code.

Related

how can i send and get messages from database using AJAX JQUERY

I'm building a website using PHP and AJAX JQUERY. And inside this website, there is texting system, like whatsapp, telegram ...etc.
and I'm wanna get all the messages from the database after the user send a message, using jQuery AJAX. so far I have been able to send the text to the database successfully but I fail when I try to get the messages.
I Have this following code when first the page is loaded:
<div class="messaging-frame">
<div class="Title-in-message">
<h4 class="title-message"><?php echo $index['Title'] ?></h4>
</div>
<div class="messaging-box" id="messages">
<?php
// THE MESSAGE FROM MESSAGE TABLE
foreach ($messages as $key => $value) {
if ($_SESSION['EmployeeNum'] === $value['Sender']) { ?>
<div class="row">
<div class="col" style="margin-bottom:15px">
<div class='sent'>
<p id='send-bubble'> <?php
echo $value['Message'] ?> </p>
</div>
</div>
</div>
<?php
} else { ?>
<div class="row">
<div class="col" style="margin-bottom:15px">
<div class='recived' id="recieved-bubble">
<p id='recived-bubble'><?php echo $value['Message'] ?></p>
</div>
</div>
</div><?php
}
}
?>
</div>\
Than this code in AJAX jQuery get executed when ever the user send a new message in messaging box:
$(document).ready(function() {
$('#sending_text').click(function() {
var report = $('#report_num').val()
var reportInt = parseInt(report);
var text = $('#text_sent').val();
var encodeText = encodeURIComponent(text);
$.ajax({
url: "<?php echo base_url() . 'DisplayTicket/sendNewText' ?> ",
type: "POST",
data: {
text: text,
reportNum: reportInt
},
success: function() {
$('#messages').load("<?php echo base_url() . 'DisplayTicket/getNewMessages' ?>", {reportNum: reportInt}, function() {
var texts = " <?php foreach ($messages as $k => $val) { if ($_SESSION['EmployeeNum'] === $value['Sender']) { ?>";
texts += " <div class='row'> <div class='col' style='margin-bottom:15px'> <div class='sent'>";
texts += "<?php echo $val['Message'] ?>";
texts += "</div> </div> </div>";
texts += "<?php } else { ?>";
texts += " <div class='row'> <div class='col' style='margin-bottom:15px'> <div class='recived' id='recieved-bubble'>"
texts += "<?php echo $val['Message'] ?>";
texts += "</div> </div> </div>"
texts += "<?php }
} ?>";
texts += "</div>";
$('#messages').html(texts);
})
},
});
});
})
Keep in mind that the $('#messages').html(texts);
is actually get executed but the newest messages in not added
I see you are using .load() method to fill the #messages .
Normally the first argument to this method is the response you wanna insert,and the this is just a callback after success, and you are using a php variable $messages instead of using the response from the request.
I see already 2 ways of doing this:
1 - remove the callback from load() and make sure the response is well written in html as youy want
2 - get rid of load() function, and call another ajax inside success of the first ajax to accomplish so.
The second method is just to make you understand what is wrong. So the best way to do it is to fix load() method accordingly

assign value to php variable using jquery [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 3 years ago.
i am working on website with buttons each button fire up a bootstrap modal contain data from mysql database i pass a variable from the jquery that fire up the model into a mysql query inside the modal the problam is the php variable cannot get the data send it from the jquery any hints please ?!
i am passing data through jquery post to ajax.php file
the modal code
<div class="modal" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<span id="codeElem"></span>
<?php
$resultHead = mysqli_query($con2,"SELECT * FROM coops WHERE Code = $getCode ");// WHERE Code IN ('".$codeArrayStr."')
?>
<?php
$i=0;
$row3 = mysqli_fetch_array($resultHead);
?>
<h4 class="modal-title"><?=$row3['CoopName'];?></h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body">
<?php
$result = mysqli_query($con,"SELECT DISTINCT * FROM reports WHERE host = $getCode GROUP BY host DESC");
?>
<?php
$i=0;
while($row = mysqli_fetch_array($result)) {
?>
<div class="card card-figure has-hoverable">
<figure class="figure">
<img class="img-fluid" src="http://www.iroof.tv/screenshots/<?=$row['screenshot'];?>" alt="Card image cap">
<figcaption class="figure-caption">
<h6 class="figure-title"><?=$row['host'];?></h6>
<p class="text-muted mb-0"> <?=$row['timestamp'];?> </p>
<?php
// Assign JSON encoded string to a PHP variable
$statusJson = $row['status'];
// Decode JSON data into PHP associative array format
$arr = json_decode($statusJson, true);
// Call the function and print all the values
// $result2 = printValues($arr);
echo "<hr>";
echo "<h3> Player </h3>";
// Print a single value
echo "Status: ".$arr["player"]["status"] . "<br>";
echo $arr["player"]["filename"] . "<br>";
echo "<hr>";
echo "<h3> Graphics </h3>";
echo "Display: ".$arr["video"]["display"] . "<br>";
echo "Resolution: ".$arr["video"]["resolution"] . "<br>";
echo "Colors: ".$arr["video"]["colors"] . "<br>";
echo "<hr>";
echo "<h3> System </h3>";
echo "CPU: ".$arr["cpu"] . "<br>";
echo "Ram: ".$arr["ram"] . "<br>";
//echo "Temprature: ".$arr["temperature"] . "<br>";
echo "Fan: ".$arr["fan"] . "<br>";
?>
</figcaption>
</figure>
</div>
<?php $i++;
}
?>
</div>
<!-- Modal footer
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>-->
</div>
the jquery script
<script>
$(document).ready(
function() {
setInterval(function() {
$('.card');
}, 5000); //Delay here = 5 seconds
var gen;
$(".btn").click(function(){
gen = $(this).attr("data-code");
//$.post("ajax.php", {"code": gen},function(data){console.log(data);});
});
$('#myModal').on('shown.bs.modal', function () {
$.post("ajax.php", {"code": gen},function(data){console.log(data);});
//var phpCode = "<? $getCode = $_POST["code"]; ?>";
//$('#codeElem').html(phpCode);
})
});
</script>
ajax.php file
<?php
if(isset($_POST['code']) && isset($_POST['code'])){
//$_SESSION["code"] = $_POST["code"];
$_SESSION['header'] = $_POST['code'];
$getCode = $_POST["code"];
echo $_SESSION['header'];
}
?>
i expect the variable $getCode to get the code from jquery to complete the mysql query inside the modal :
$resultHead = mysqli_query($con2,"SELECT * FROM coops WHERE Code = $getCode");
I dont think its possible to post variables to a modal, I didnt see example like that when I was searching for popup modal login.
guess you need an action page to forvard infos to modal.
This is the solution to post variables:
Change variables to your needs..
$(document).ready(function(){
$("form").submit(function(event){
event.preventDefault();
var post_id =$("#mail-id").val();
var name =$("#mail-name").val();
var email =$("#mail-email").val();
var message =$("#mail-message").val();
var type =$("#mail-type").val();
var captcha_code =$("#captcha_code").val();
var submit =$("#mail-submit").val();
$(".form-message").load("heads/comment.php",{
post_id: post_id,
name: name,
email: email,
message: message,
type: type,
captcha_code: captcha_code,
submit: submit
});
});
});
you probably need some thing like this to show variables in popup
<p class="form-message"></p>
Or you can check Bootstrap modal table :
Here

How to display the page with ajax?

I have a pagination that works correctly even I have added a filter to paginate more rows on the same page is to say that through the filter I can show 10 or 50 rows.
The small defect that I have in my code is that the page is reloaded, changing how many rows show and the same happens in the buttons of the pagination.
This is my code, everything is working on the same page index2.php.
<div id="wrapper">
<div class="container">
<div id="news-header" class="bootgrid-header container-fluid">
<div class="row">
<div class="col-sm-12 actionBar">
<div class="search-bar">
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="What are you looking for?">
</div>
<div class="actions btn-group">
<?php
$select_quantity = '';
if (isset($_POST['amount_show'])) :
$select_quantity = $_POST['amount_show'];
endif;
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<select id="amount_show" name="amount_show" onchange="this.form.submit()">
<option value="10" <?php if ($select_quantity==10) echo "selected"; ?>>10</option>
<option value="25" <?php if ($select_quantity==25) echo "selected"; ?>>25</option>
<option value="50" <?php if ($select_quantity==50) echo "selected"; ?>>50</option>
<option value="100" <?php if ($select_quantity==100) echo "selected"; ?>>100</option>
</select>
</form>
</div>
</div>
</div>
</div>
<?php
if (isset($_GET['page'])) :
$page = $_GET['page'] ?: '';
else :
$page = 1;
endif;
if (isset($_POST['amount_show'])) :
$records_by_page = $_POST['amount_show'];
else :
$records_by_page = 10;
endif;
$localization_sql = ($page-1) * $records_by_page;
$sql = "SELECT id,title,description
FROM news
ORDER BY id DESC LIMIT $localization_sql, $records_by_page";
$stmt = $con->prepare($sql);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows>0) :
echo '<table id="myTable" class="table table-condensed table-hover table-striped bootgrid-table">
<thead>
<tr>
<th>Id</th>
<th>Title</th>
<th>Description</th>
<th>Action</th>
</tr>
</thead>
<tbody>';
$stmt->bind_result($id,$title,$description);
while ($stmt->fetch()) :
echo '<tr>
<td>'.$id.'</td>
<td>'.$title.'</td>
<td>'.$description.'</td>
<td>Edit</td>
</tr>';
endwhile;
echo '</tbody>';
echo '</table>';
$stmt->close();
$sql = "SELECT * FROM news";
$stmt = $con->prepare($sql);
$stmt->execute();
$stmt->store_result();
$BD_records = $stmt->num_rows;
$stmt->close();
$con->close();
$total_page = ceil($BD_records / $records_by_page);
$prev = $page - 1;
$next = $page + 1;
echo '<div class=pagination>
<ul class="pagination">';
if ($prev > 0) :
echo "<li><a href='index2.php?page=1'><i class='icon-angle-double-arrow'></i></a></li>";
echo "<li><a href='index2.php?page=$prev'><i class='icon-angle-left'></i></a></li>";
endif;
for ($i=1; $i<=$total_page; $i++) :
if ($page==$i) :
echo "<li><a class=active>". $page . "</a></li>";
else :
echo "<li><a href='index2.php?page=$i'>$i</a></li>";
endif;
endfor;
if ($page < $total_page ) :
echo "<li><a href='index2.php?page=$next'><i class='icon-angle-right'></i></a></li>";
echo "<li><a href='index2.php?page=$total_page'><i class='icon-angle-double-right'></i></a></li>";
endif;
echo '</ul></div>';
else :
$stmt->close();
endif;
?>
</div>
</div>
While searching the web I found an ajax code, but sincerely, I did not manage the use ajax or javascript / jquery code.
You can explain how to implement this ajax code or how to avoid the small defect of reloading the page.
<script type="text/javascript">
$(document).ready(function() {
$('.pagination li a').on('click', function(){
/*$('.items').html('<div class="loading"><img src="images/loading.gif" width="70px" height="70px"/><br/>Loading...</div>');*/
$('.items').html('<div class="loading">Loading...</div>');
var page = $(this).attr('data');
var dataString = 'page='+page;
$.ajax({
type: "GET",
url: "ajax.php",
data: dataString,
success: function(data) {
$('.items').fadeIn(2000).html(data);
$('.pagination li').removeClass('active');
$('.pagination li a[data="'+page+'"]').parent().addClass('active');
}
});
return false;
});
});
</script>
This is how my code works, as shown in the following image:
Ajax is going to update information on your page without reloading your page. We want to separate the data from the HTML so we can change which data we're seeing. We can't do that if PHP is the tool writing the data into the HTML. So I recommend separating index2.php into several files. This example uses JSON.
Collect the data
ajax.php
<?php
$data_rows = array();
for ($i = 0; $i < 1000; $i++) {
$data_rows[] = array(
"id" => "id_$i",
"title" => "title_$i",
"description" => "description_$i",
);
}
echo json_encode($data_rows, JSON_PRETTY_PRINT);
This is an example of some junk data, I don't know what data you need. The important thing here is to make an associative array of all the information you want, json_encode() the array, and then echo it. It's important that this is the only thing that gets echoed or printed! This won't work if you have anything else printing in this script.
Edit:
ajax.php
if (isset($_GET['page'])) :
$page = $_GET['page'] ?: '';
else :
$page = 1;
endif;
if (isset($_POST['amount_show'])) :
$records_by_page = $_POST['amount_show'];
else :
$records_by_page = 10;
endif;
$sql = "SELECT id, title, description
FROM news
ORDER BY id DESC LIMIT $localization_sql, $records_by_page";
$result = $con->query($sql);
$data_rows = array();
while ($row = $result->fetch_assoc()) {
$data_rows = $row;
}
echo json_encode($data_rows, JSON_PRETTY_PRINT);
Your original code includes this mysqli connection, this is data that I don't have access to so I can't test the efficacy of this script. However, this should present all of the data that you're asking about.
Ajax with jQuery
script.js
$(document).ready(function() {
$.ajax({
type: "GET",
url: "ajax.php",
dataType: "json",
success: function(data) {
tableRows = '';
for (let i = 0; i < data.length; i++) {
tableRows += `
<tr>
<td>${data[i].id}</td>
<td>${data[i].title}</td>
<td>${data[i].description}</td>
<td>Edit<td>
</tr>`;
}
$("#tbody-insert").html(tableRows);
}
});
});
Set the url parameter of your ajax call to the name of the php file that's delivering the data. In the example I'm using JSON, it's important to set dataType: "json". jQuery will automatically parse this for you. You can see in the success parameter, data is the name of the php array we've created. I used a simple for loop to create a bunch of table rows, then inserted them into a table body that I've labeled with id="tbody-insert".
Present the data
index.html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
<table id="myTable" class="table table-condensed table-hover table-striped bootgrid-table">
<thead>
<tr>
<th>Id</th>
<th>Title</th>
<th>Description</th>
<th>Action</th>
</tr>
</thead>
<tbody id="tbody-insert">
</tbody>
</table>
I've taken all the PHP out of your index page, it's not very flexible and it requires reloading the entire page before updating the information. The important points to note are the script tags, you need to include jQuery and you need to include the script.js. You also need to have an id for the table body that we're inserting information into. You can wrap your ajax in a function that gets called every time you want to paginate, and query ajax.php for different pages. I don't know the structure of your data so I can't help any further with that.
Let's start with the reason that causes your page to reload: The default browser actions. Several html elements cause the browser to navigate away from the current page. The ones we are concerned in this case are:
#amount_show form submission (the onchange function) that sends the new value via POST request.
The paginator itself (with a links) that tells the php script which records to retrieve via GET request.
Both values should be passed to the php script for it to be able to return the correct records, otherwise the amount parameter would be the default in the php script even if we have a different value selected. To be able to do that, we have to change the passing of the amount variable to a GET request.
Also, when changing the amount value we'll default to the first page to avoid recalculating the page number.
Since the pagination links can therefore change dinamically, I'm not going to handle them in javascript but in php instead, since we already have a template and the calculations. This will make things easier to change down the line.
Let's tackle the javascript first:
$(document).ready(function() {
// When we change the value of the select...
// evt contains the information about the event:
// element receiving the action, the action itself, etc.
$('#amount_show').change(function(evt) {
// Cancel the default browser action
evt.preventDefault()
// Get the target url of the form (our php script)
url = $(this).parent().attr('action')
// Call the funtion that will be doing the request
ajaxLoad(url)
});
// When we click a pagination link... (Explanation below)
$('.items').on('click', '.pagination li a', function(evt) {
evt.preventDefault()
url = $(this).attr('href')
ajaxLoad(url)
});
// Do the actual request
function ajaxLoad(url) {
// How many records do we want to show ?
query_params = {
amount_show: $('#amount_show').val()
};
// Show an indication that we are working
$('.items').html('<div class="loading">Loading...</div>')
$.ajax({
type: "GET",
url: url, // Call php, it will default to page 1 if there's no parameter set
// When calling a link with a page parameter this will be smart
// enough to append the variable to the query string correctly
data: $.param(query_params),
// Handle the data return. In a perfect world, this is always successful
success: function(data) {
// Insert the data in the document.
$('.items').fadeOut('1000', function() { $(this).html(data) }).fadeIn('1000')
}
});
}
});
The line $('.items').on('click', '.pagination li a', function(evt) { attaches a delegate event listener to the .items element that will respond to the click events received by .pagination li a. The reason to do this instead of attaching directly to the element itself is two-fold:
Reduce the number of elements that we have to loop and attach a listener to.
Handle dynamic insertion of elements. When switching content, we are deleting the elements from the document, and their listeners with them. We would have to attach them again on every page load, otherwise with no listeners attached they would go back to the default action. But since this element doesn't change we won't have to do it.
Now for the php. Since you are interested in using a single file, I'm just going to move things around but it will (mostly) be what you have now.
Note: I may have misunderstood what you mean by having all in a single page. If this is a partial template that you are including from your main index, you'll have to change the link targets and action for the form to point to it, adjust some javascript selectors and you could skip the whole ajax request checking.
Main changes:
Remove your onchange function call.
Change POST parameter to GET parameter.
Add a .items span to insert the elements in since it doesn't exist.
Determine if a page load is an ajax load or a regular one using X-Requested-With header. An alternative to this is returning a full response anyway and filtering it with jQuery.
<?php
if (isset($_GET['page'])) :
$page = $_GET['page'] ?: '';
else :
$page = 1;
endif;
if (isset($_GET['amount_show'])) :
$records_by_page = $_GET['amount_show'];
else :
$records_by_page = 10;
endif;
$localization_sql = ($page-1) * $records_by_page;
$sql = "SELECT id,title,description
FROM news
ORDER BY id DESC LIMIT $localization_sql, $records_by_page";
$stmt = $con->prepare($sql);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows>0) :
// Start capturing the output
ob_start();
?>
<table id="myTable" class="table table-condensed table-hover table-striped bootgrid-table">
<thead>
<tr>
<th>Id</th>
<th>Title</th>
<th>Description</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
$stmt->bind_result($id,$title,$description);
while ($stmt->fetch()) :
echo '<tr>
<td>'.$id.'</td>
<td>'.$title.'</td>
<td>'.$description.'</td>
<td>Edit</td>
</tr>';
endwhile;
$stmt->close();
?>
</tbody>
</table>
<div class=pagination>
<ul class="pagination">
<?php
// When requesting an out-of-bounds page, this won't execute resulting in
// a blank page with no paginator
$sql = "SELECT * FROM news";
$stmt = $con->prepare($sql);
$stmt->execute();
$stmt->store_result();
$BD_records = $stmt->num_rows;
$stmt->close();
$con->close();
$total_page = ceil($BD_records / $records_by_page);
$prev = $page - 1;
$next = $page + 1;
if ($prev > 0) :
echo "<li><a href='" . $_SERVER['PHP_SELF'] . "?page=1'><i class='icon-angle-double-arrow'></i></a></li>";
echo "<li><a href='" . $_SERVER['PHP_SELF'] . "?page=$prev'><i class='icon-angle-left'></i></a></li>";
endif;
for ($i=1; $i<=$total_page; $i++) :
if ($page==$i) :
echo "<li><a class='page-link active' >". $page . "</a></li>";
else :
echo "<li><a class='page-link' href='" . $_SERVER['PHP_SELF'] . "?page=$i'>$i</a></li>";
endif;
endfor;
if ($page < $total_page ) :
echo "<li><a class='page-link' href='index2.php?page=$next'><i class='icon-angle-right'></i></a></li>";
echo "<li><a class='page-link' href='index2.php?page=$total_page'><i class='icon-angle-double-right'></i></a></li>";
endif;
echo '</ul></div>';
// Get the output into a variable
$results_table = ob_get_clean();
else :
$results_table = "<div>No results found</div>";
$stmt->close();
endif;
if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])) :
// If is an ajax request, output just the result table and exit
echo $results_table;
die;
endif;
// Print the whole page if its not an ajax request
?>
<script type='text/javascript' src='//cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js'/>
<script src='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/js/bootstrap.min.js' />
<link rel='stylesheet' href='https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css' type='text/css' />
<div id='wrapper'>
<div class='container'>
<div id='news-header' class='bootgrid-header container-fluid'>
<div class='row'>
<div class='col-sm-12 actionBar'>
<div class='search-bar'>
<input type='text' id='myInput' placeholder='What are you looking for?'>
</div>
<div class='actions btn-group'>
<form action=<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>'>
<select id='amount_show' name='amount_show'>
</select>
</form>
</div>
</div>
</div>
</div>
<span class='items'>
<?php echo $results_table; ?>
</span>
</div>
</div>
For completeness, the alternative method without separating the responses with php, is to filter the response with jQuery by doing the following in the ajax success callback (fades omitted):
results_table = $(data).find('.items').html()
$('.items').html(results_table)
This converts the response from the server into a jQuery object and allows to apply filtering functions as normal. We extract the content we are interested in (content of items: result table and pagination), then we just append it to the items container on our existing page.
UPDATE: I've posted a simplified example without database-related code here. I think there's something weird going on when copy&paste'ng code from/to the editor.
References
DOM events
jQuery ajax and helper functions
PHP output buffering
Not receiving X_REQUESTED_WITH request header
Fade effects in ajax callback
There's no point to start playing with jquery and async calls if even pure html is bit over the limit. In initial code you are mixing POST and GET, use just one.
<div id="wrapper">
<div class="container">
<div id="news-header" class="bootgrid-header container-fluid">
<div class="row">
<div class="col-sm-12 actionBar">
<div class="search-bar">
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="What are you looking for?">
</div>
<div class="actions btn-group">
<?php
//getting both - page and record_by_page from GET
$records_by_page = isset($_GET['amount_show'])?$_GET['amount_show']:10;
$page = isset($_GET['page'])?$_GET['page']:1;
//put page value into form to send it together with amount_show
?>
<form method="get" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<select id="amount_show" name="amount_show" onchange="this.form.submit()">
<option value="10" <?php if ($records_by_page==10) echo "selected"; ?>>10</option>
<option value="25" <?php if ($records_by_page==25) echo "selected"; ?>>25</option>
<option value="50" <?php if ($records_by_page==50) echo "selected"; ?>>50</option>
<option value="100" <?php if ($records_by_page==100) echo "selected"; ?>>100</option>
</select>
<input type="hidden" id="page" name="page" value="<?php echo $page; ?>"></input>
</form>
</div>
</div>
</div>
</div>
<?php
$localization_sql = ($page-1) * $records_by_page;
$sql = "SELECT id,title,description
FROM news
ORDER BY id DESC LIMIT $localization_sql, $records_by_page";
$stmt = $con->prepare($sql);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows>0) :
echo '<table id="myTable" class="table table-condensed table-hover table-striped bootgrid-table">
<thead>
<tr>
<th>Id</th>
<th>Title</th>
<th>Description</th>
<th>Action</th>
</tr>
</thead>
<tbody>';
$stmt->bind_result($id,$title,$description);
while ($stmt->fetch()) :
echo '<tr>
<td>'.$id.'</td>
<td>'.$title.'</td>
<td>'.$description.'</td>
<td>Edit</td>
</tr>';
endwhile;
echo '</tbody>';
echo '</table>';
$stmt->close();
$sql = "SELECT * FROM news";
$stmt = $con->prepare($sql);
$stmt->execute();
$stmt->store_result();
$BD_records = $stmt->num_rows;
$stmt->close();
$con->close();
$total_page = ceil($BD_records / $records_by_page);
$prev = $page - 1;
$next = $page + 1;
echo '<div class=pagination>
<ul class="pagination">';
//add amount_show to each request
if ($prev > 0) :
echo "<li><a href='pagination.php?page=1&amount_show=$records_by_page'><i class='icon-angle-double-arrow'></i></a></li>";
echo "<li><a href='pagination.php?page=$prev&amount_show=$records_by_page'><i class='icon-angle-left'></i></a></li>";
endif;
for ($i=1; $i<=$total_page; $i++) :
if ($page==$i) :
echo "<li><a class=active>". $page . "</a></li>";
else :
echo "<li><a href='pagination.php?page=$i&amount_show=$records_by_page'>$i</a></li>";
endif;
endfor;
if ($page < $total_page ) :
echo "<li><a href='pagination.php?page=$next&amount_show=$records_by_page'><i class='icon-angle-right'></i></a></li>";
echo "<li><a href='pagination.php?page=$total_page&amount_show=$records_by_page'><i class='icon-angle-double-right'></i></a></li>";
endif;
echo '</ul></div>';
else :
$stmt->close();
endif;
?>
</div>
</div>

Updating Database and Page Content at the Same Time

This is a tough one for me. a total of five documents involved in this process. I can't help but feel that I am over complicating this issue. I asked about this previously and THOUGHT I understood the issue, but then I tried to add a simple "loading" modal to the equation, and it broke. What's worse I can't get it working anymore. I have changed too much. Yes I know I should have backed it up, let's get past that. The one language I cannot change at all in this whole element is my DB language, which is MySql.
What I Want to Happen
Page loads all non-archived submissions. The data is structured so that some but not all data is displayed for each row. At least not until the user clicks the "more info" button. NOTE: THIS IS NOT THE PROBLEM BUT ONLY HERE BECAUSE I HAVEN'T BUILT THIS YET, I WILL FOCUS ON THIS LATER.
After the user has finished using the data from one row, I would like the user to be able to archive the data into the database by changing the "archived" field from 0 to 1. After that is accomplished, I would like the row to disappear. If there is a lag and more than a second or two is needed to accomplish this, then a loading modal should appear that will indicate that the page has received the request and prevents the user from pressing the "archive" button multiple times.
What is Happening Now
When the page loads, all non-archived data is displayed in rows that show some but not all information for each record in a table. When the user clicks the "more info" button nothing happens. Note: Again I am not focusing on this issue I know how to fix this. When the user clicks on the "archive" button, it does nothing, but if they click if multiple times it eventually will bring up the "loading" modal and then refresh the page. The row that should have disappeared is still there, and the record still shows a "0" instead of a "1" as it should.
Final Comments Before Code Is Given
I am open to using other languages as I am a fast learner, I just don't know how to integrate them. But if you do respond with that, please also explain why my way is inferior and what I would have to do to make this work. I am still learning AJAX (very much beginner) and PHP (intermediate . . . I think).
The Code
index.php - abridged without head
<div class="container">
<h1><span class="hidden">Locate My Pet</span></h1>
<h2>Administration</h2>
<p class="lead alert alert-info">Hello There! You can review and archive submitted requests here.</p>
<div class="panel panel-default">
<div class="panel-heading">
<h2 class="text-center">Submissions</h2>
</div><!--/.panel-heading-->
<div id="results"></div><!--To be populated by script-->
</div><!--/.panel .panel-default-->
</div><!-- /.container -->
<footer class="footer">
<div class="container">
<p class="text-muted text-center">© 2016 TL Web Development and Design</p>
</div><!--/.container-->
</footer><!--/.footer-->
<div class="modal fade" id="archiveMessage" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Archiving Submission</h4>
</div><!--/.modal-header-->
<div class="modal-body">
<p>Please wait . . .</p>
</div><!--/.modal-body-->
</div><!--/.modal-content-->
</div><!--/.modal-dialog-->
</div><!--/.modal-->
submission.php
<table class="table table-responsive table-striped">
<tr>
<th>Customer Name</th>
<th>Address</th>
<th>Contact</th>
<th>Pet Info</th>
<th>Tools</th>
</tr>
<?php
require "../_php/connect.php";
$get_all = "SELECT request_id, fName, lName, address, city, state, zip, pPhone, cPhone, email, pName, gender, spayedNeutered, howLost, comments, timeEntered, archived FROM requests";
$result = $conn->query($get_all);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
if (!$row['archived']) {
echo "<tr id='" . $row['request_id'] . "' class='fade in'>
<td>
" . $row['fName'] . " " . $row['lName'] . "</br>
<strong>Sent: </strong>" . $row['timeEntered'] . "
</td>
<td>" . $row['address'] . "</br>" . $row['city'] . " " . $row['state'] . ", " . $row['zip'] ."</td>
<td>
<strong>Primary Phone:</strong> <a href='tel:" . $row['pPhone'] . "'>" . $row['pPhone'] ."</a></br>
<strong>Cell Phone:</strong> <a href='tel:" . $row['cPhone'] . "'> " . $row['cPhone'] . "</a></br>
<strong>Email:</strong> <a href='mailto:" . $row['email'] . "'>" . $row['email'] . "</a></td>
<td>
<strong>Pet Name:</strong> " . $row['pName'] . "</br>
<strong>Gender:</strong> " . $row['gender'] . "</br>
<strong>Spayed or Neutered?:</strong> ";
if ($row['spayedNeutered'] = 0) {
echo "No</td>";
} else {
echo "Yes</td>";
}
echo "<td>
<button class='btn btn-info'>More info</button></br>
<form action='../_php/archive.php' method='get'><input type='hidden' value='" . $row['request_id'] . "' id='row_id'><button type='submit' class='btn btn-warning archive'>Archive</button></form>
</td>
</tr>";
}
}
} else if ($conn->connect_error != NULL) {
echo "<tr><td colspan='5'><div class='alert alert-danger' role='alert'>Error: " . $conn->error . "</div></td></tr>";
} else {
echo "<tr><td colspan='5'><div class='alert alert-info' role='alert'>No Records were found.</div></td></tr>";
}
?>
<script type="text/javascript" src="../_js/query.js"></script>
</table>
connect.php - some content no included for security reasons
// Create connection
$conn = new mysqli($servername, $username, $password, $dbName);
// Check connection
if ($conn->connect_error) {
die("<tr><td colspan='5'><div class='alert alert-danger' role='alert'>Error: " . $conn->error . "</div></td></tr>)");
}
query.js
$(document).ready(function() {
"use strict";
$('#results').load('../_php/submission.php');
$(".archive").click(function() {
$('#archiveMessage').modal('show');
var id = $(this).parent().parent().attr('id');
$.ajax({
type: 'POST',
url: '../_php/functions.php',
data: {'archive': id},
});
});
});
functions.php
<?php
require "connect.php"; // Connect to database
function archive($id) {
require "connect.php";
$archive = "UPDATE requests SET archived='1' WHERE request_id='$id'";
if ($conn->query($archive) === TRUE) {
echo "Record " . $id . " has been archived.";
} else {
echo "Error: " . $conn->error;
}
}
if (isset($_POST['callArchive'])) {
archive($_POST['callArchive']);
} else {
archive(1);
}
?>
Since archive button is dynamically loaded, its the best choice to use .on('click') rather than .click() that does not fires on a dynamically loaded element. Try to read the question and answeres here, specially the selected correct answer.
query.js
$(document).ready(function() {
"use strict";
$('#results').load('../_php/submission.php');
$("#results .archive").on("click",function() {
$('#archiveMessage').modal('show');
var id = $(this).parent().parent().attr('id');
$.ajax({
type: 'POST',
url: '../_php/functions.php',
data: {'archive': id},
//If you dont want to change your functions.php file use the commented line below instead of the above code
//data: {'callArchive':id},
});
});
});
When the user clicks on the "archive" button, it does nothing, but if
they click if multiple times it eventually will bring up the "loading"
modal and then refresh the page. The row that should have disappeared
is still there, and the record still shows a "0" instead of a "1" as
it should.
Since your ajax call data contains post 'archive' in which the value is id and you want to update some data of your request table but you are checking the wrong index of the POST data(if (isset($_POST['callArchive'])) ) rather change it to if (isset($_POST['callArchive']))
<?php
function archive($id) {
require "connect.php";// Connect to database
$archive = "UPDATE requests SET archived='1' WHERE request_id='$id'";
if ($conn->query($archive) === TRUE) {
echo "Record " . $id . " has been archived.";
} else {
echo "Error: " . $conn->error;
}
}
if (isset($_POST['archive'])) {
archive($_POST['archive']);
} else {
archive(1);
}
?>
Hope that helps :D

AJAX PHP Array from a SQL Database

*I know MYSQL is depricated. I am just using it as a learning tool for now.
UPDATED QUESTION:
I updated my question to make a lil more sense...
How can I display the output array (json data in PHP file) on my HTML page assuming I wanted to add it to the div id rvotes?
JavaScript
<script>
$(document).ready(function () {
$('.answer').click(function (e) {
var color = $(this).attr("data-color");
$.ajax({
type: 'POST',
url: 'mm.php',
data: { color: color},
dataType: 'json',
cache: false,
success: function(showVotes) {
$('#rvotes').html(row[0]);
},
error: function (jqXHR) {
}
})
})
});
</script>
PHP
function showVotes()
{
$sql = "SELECT * FROM mms";
$result = mysql_query($sql) or die(mysql_error());
$showresult = mysql_query("SELECT * from mms") or die("Invalid query: " . mysql_error());
$response = array();
while($row = mysql_fetch_assoc($showresult))
$results[] = $row;
echo json_encode($results);
}
ADDING my HTML code
<div id="wrapper">
<div id="red" data-color="red" class="answer">
<img src="images/red.jpg" width="100%" />
</div>
<div id="blue" data-color="blue" class="answer">
<img src="images/blue.jpg" width="100%" />
</div>
<div id="green" data-color="green" class="answer">
<img src="images/green.jpg" width="100%" />
</div>
<div id=rvotes>
TEST
</div>
<div id=bvotes>
TEST
</div>
How can I display the output from the array back at my HTML page?
I think this is similar to this question.
Get data from php array - AJAX - jQuery
You cannot access the php array as it is in your ajax. You need to represent it first as JSON by passing your php array to json_encode() function and echo it.
echo json_encode($results);
And it will be passed to your ajax callback as parameter.
In you success ajax callback,
success: function(showVotes) {
$('#rvotes').html(showVotes[0]);
},
Personally, I would have my php spit out pre-rendered html like so:
$sql = "SELECT * FROM mms";
$result = mysql_query($sql) or die(mysql_error());
//I cleaned up redundant queries here...
//echo top border
echo "<table border='1'>
<tr>
<th>Color</th>
<th>Votes</th>
</tr>";
while($row = mysql_fetch_assoc($showresult))
while($row = mysql_fetch_assoc($showresult)
{
echo "<tr>";
echo "<td>" . stripslashes($row['color']) . "</td>";
echo "<td>" . stripslashes($row['votes']) . "</td>";
echo "</tr>";
}
After it spits out html, just do this:
<script>
$(document).ready(function () {
$('.answer').click(function (e) {
var color = $(this).attr("data-color");
$.ajax({
type: 'POST',
url: 'mm.php',
data: { color: color},
success: function (showVotes) {
$("#votes").html(showVotes); //this edits the text inside the div to be whatever your php spits out
},
error: function (jqXHR) {
}
})
})
});
</script>
<div id="votes></div>

Categories