Access Each JSON Array Element onClick Using AJAX PDO PHP - php

I'm trying to access each element stored as a Base64 image/blob in a JSON array constructed from a MySQL query.
The idea is to click a button that goes through each element and displays the image.
I have gotten it to display the first image however when i click again, the next image doesn't show.
Any help will be much appreciated.
AJAX:
$(function () {
$('#getimg1').on('click', function () {
$.ajax({
type:'GET',
dataType: 'json',
url: 'http://testing/api/getimg',
success:function(getinfo){
$.each(getinfo, function(i, displayimg){
$('#HTMLBox').prop('src','data:image/png;base64,' + displayimg.XXX ---- //Here I'm suspecting something?);
});
}
});
});
});
PHP:
$sql = "SELECT img from artistlocation";
try{
$db = new db();
$db = $db->connect();
$stmt = $db->query($sql);
$data = array();
while($result = $stmt->fetch(PDO::FETCH_OBJ))
{
$data[] = base64_encode($result->img);
}
echo json_encode($data);
}
catch(PDOException $e){
echo '{"error": {"text": '.$e->getMessage().'}';
}
I'm using just 2 images to test this.

Because the ajax call you make will return all of the image records, I think it would be more efficient to store that data in a variable and then just rotate through the images rather than making call to your php code with each click. Here's what I would suggest, if you're using just jQuery:
var images = [],
index = 0,
count = 0,
max = 0;
$.getJSON("http://testing/api/getimg", function(data) {
images = data;
count = images.length;
max = count - 1;
});
$('#getimg1').on('click', function() {
if (count === 0) {
return;
}
if (index === max) {
index = 0;
} else {
index++;
}
$('#HTMLBox').attr('src', 'data:image/png;base64,' + images[index]);
});
I must admit I didn't test it, but I believe it should work - if you could try and see how you get on.

So, if you wanted to do something really dirty, you could track how many images you've loaded via a hidden input. You can increment that upon your ajax success. Then, what you can do is pass to your PHP via your AJAX that value, and run something like:
SELECT * FROM images LIMIT 1 OFFSET $images_already_fetched
By passing an OFFSET declaration, you're telling it to skip that many rows.

Related

How to use ajax to update label from count from mysql database

I know ajax is probably the best method to do this.
So, i have this php file which returns a count:
<?php
include('globals.php');
$query = mysqli_query($con, "SELECT COUNT(*) as total FROM solicitacoes WHERE visualizada = 0");
$resultado = mysqli_fetch_array ($query);
$sem_visualizar = $resultado['total'];
return $sem_visualizar;
And i have this on my main page:
<?php
if($_SESSION['funcao_corrente']=="adm" || $_SESSION['funcao_corrente']=="analista"){
echo '<label onclick="mudaIframe();" id="visu" ';
if ($sem_visualizar == 0)
echo 'style="background-color: darkgray; color: black;"';
else if ($sem_visualizar<=5)
echo 'style="background-color: green;"';
else if ($sem_visualizar>5 && $sem_visualizar <= 15)
echo 'style="background-color: orangered;"';
else if ($sem_visualizar>15)
echo 'style="background-color: red;"';
echo '>'.$sem_visualizar.'</label>';
}
?>
Basically it just changes color based on value, but the thing is:
I want it to auto refresh it's own value via the PHP file which returns count, but I have absolutely no idea how can i do this.
I found this code in another answer, but it's not working.
<script>
function get_msg_count(){
$.ajax ({
data: {}, // not really needed
type: 'POST',
url: 'contar_sem_visualizar.php', // page to return your msg count
success: function(response)
{
$('#visu').html(response);
}
}
}); // End $.ajax
} // End Function
// and on DOM ready
$(function(){
// check for new messages every 3 seconds(3000ms)
setInterval(get_msg_count(), 3000)
});
</script>
You can just use $.load to achieve that:
HTML
<span id="count"></span>
jQuery
$("#count").load("contar_sem_visualizar.php");
You need an element to set the count and use jQuery to put the answer in there. The return from your PHP will be retrieved from the jQuery request and ever after a set interval the client's browser will send a request asking for this value, which will be added again to the counter.
You could do that:
function get_count(){
while()
{
$("#counter").load("contar_sem_visualizar.php");
setInterval(3000);
}
}
get_count();

Unable to navigate Dynamically created pages in DOM

After so many trials, I have finally managed to create pages dynamically using PHP, JSON and AJAX and load them into DOM. But the problem now is I'm unable to call/navigate those pages dynamically, but manually i.e gallery.html#page1 ...etc.
I seek guidance rather than burdening you, as I'm here to learn.
**PHP - photos.php **
$photos = array();
$i=0;
while ($row = mysqli_fetch_array($query)){
$img = $row["fn"];
$photos[] = $img;
$i++;
}
$count = count($photos);
echo json_encode(array('status' => 'success', 'count' => $count, 'items' => $photos));
JSON array
{
"status":"success",
"count":3,
"items":
[
"img1.jpg",
"img2.jpg",
"img3.jpg"
]
}
I use the below method to fetch and store ID of the desired gallery,
<input type="hidden" value="<?php echo $id; ?>" id="displayid" />
and then I call it back to use it in AJAX.
var ID = $('#displayid').val();
AJAX and JQM
$.ajax({
Type: "GET",
url: 'photos.php',
data: { display: ID }, // = $('#displayid').val();
dataType: "json",
contentType: "application/json",
success: function(data) {
var count = data.count;
var number = 0;
$.each(data.items, function(i,item) {
var newPage = $("<div data-role=page data-url=page" + number + "><div data-role=header><h1>Photo " + number + "</h1></div><div data-role=content><img src=" + item + " /></div></div");
newPage.appendTo( $.mobile.pageContainer );
number++;
if (number == count) { $.mobile.changePage( newPage ); }; // it goes to last page
I got this code from here thanks Gajotres to dynamically navigate between pages. It's within the same code.
$(document).on('pagebeforeshow', '[data-role="page"]', function(){
var nextpage = $(this).next('div[data-role="page"]');
if (nextpage.length > 0) {
$.mobile.activePage.find('[data-role="header"]').append($('<a>').attr({'href':'#'+nextpage.attr('id'),'data-theme':'b'}).addClass('ui-btn-right').html('Next').button());
}
}); // next button
}); // each loop
} // success
}); //ajax
I found your problem.
This part of code can't be used here like this:
$(document).on('pagebeforeshow', '[data-role="page"]', function(){
var nextpage = $(this).next('div[data-role="page"]');
if (nextpage.length > 0) {
$.mobile.activePage.find('[data-role="header"]').append($('<a>').attr({'href':'#'+nextpage.attr('id'),'data-theme':'b'}).addClass('ui-btn-right').html('Next').button());
}
});
This is the problem. First remove pagebeforeshow event binding, it can't be used here like that. Rest of the code is not going to do anything because currently there are any next page (next page is going to be generated during then next loop iteration), so remove this whole block.
Now, after the each block ends and all pages are generated (that is the main thing, all pages should exist at this point), add this code:
$('[data-role="page"]').each(function(){
var nextpage = $(this).next('div[data-role="page"]');
if (nextpage.length > 0) {
$(this).find('[data-role="header"]').append($('<a>').attr({'href':'#'+nextpage.attr('id'),'data-theme':'a'}).addClass('ui-btn-right').html('Next').button());
}
});
This is what will happen. Each loop will loop through every available page (we have them all by now) and in case it is not the last one it will add next button.
Here's a live example: http://jsfiddle.net/Gajotres/Xjkvq/
Ok in this example pages are already there, but point is the same. They need to exist (no matter if you add them dynamically or if they are preexisting) before you can add next buttons.
I hope this helps.

I'd like to detect the value chosen from a drop down, and then pass that to the page url and reload

I have some javascript sorting my ul, alphabetically a-z or z-a. It works fine on page one, but if there is more than one page it ignores the list on page 2 etc.
So, instead of using javascript to sort the li's, I want to pass the selection back to the page's query and reload
here's my script, most of which is redundant now.
var select = document.getElementById('organise');
$('#organise').change(function() {
if(select.value === 'A') {
$('.recipeTable li').sortElements(function(a,b){
var aText = $.text([a]);
var bText = $.text([b]);
return aText.toLowerCase() > bText.toLowerCase() ? 1 : -1;
});
} else {
$('.recipeTable li').sortElements(function(a,b){
var aText = $.text([a]);
var bText = $.text([b]);
return aText.toLowerCase() > bText.toLowerCase() ? -1 : 1;
});
}
});
So I want to detect the selected dropdown value (either A or Z) and pass that into the url and reload. I'm stuck ;-?
Rich :)
I am not sure this is the best way to approach the problem, and maybe you should elaborate what doesn't work with your pagination. In any case, you can achieve what you need to do by doing something like this (explaination in the code comments):
var queryString = {};
// Get the previous query string with a little help from PHP
// this shouldn't be a problem since you are already using PHP
// for your project.
queryString = <?php json_encode( $_GET ); ?>;
$('#organise').change( function() {
// Set the sort property of the object to the value of the select.
queryString.sort = $(this).val();
// jQuery will help you serialise the JSON object back to
// a perfectly valid query string (you may want to escape
// characters)
newQueryString = $.param( queryString );
// Append the new query string
window.location = newQueryString;
});
This function will properly check if you already have any query string and preserve that; also, if the user changes the select multiple times, it will not add up several query strings.
you can change the url and pass the param with
document.location.href = document.location.href + "?arg=" + document.getElementById("organise").value;
You can use localstorage for this if you don't want to show in url
For example:
function Ascending()
{
$('.recipeTable li').sortElements(function(a,b){
var aText = $.text([a]);
var bText = $.text([b]);
return aText.toLowerCase() > bText.toLowerCase() ? 1 : -1;
});
}
function Descending()
{
$('.recipeTable li').sortElements(function(a,b){
var aText = $.text([a]);
var bText = $.text([b]);
return aText.toLowerCase() > bText.toLowerCase() ? -1 : 1;
});
}
if(localStorage.order=='A')
{
return Ascending();
}
else
{
return Descending();
}
var select=document.getElementById('organise');
$('#organise').change(function() {
if(select.value === 'A') {
localStorage.order=='A';
return Ascending();
} else {
localStorage.order=='Z';
return Descending();
}
});
Refer more for localStorage on http://www.w3schools.com/html/html5_webstorage.asp

Get data through xhr from PHP

I'm trying to get some data from a PHP file which only gives a number after executing:
<?php
include '../assets/class/login/loginsys.php';
$extension = new extension;
$count = $extension->userCount();
echo $count;
?>
So the $count variable will be just a number. And I'm trying to retrieve that number and put it in a js variable for further use ( I need it a few times, if it were only once I would have used $.get() and applied it to the container I need ):
var oXHR = new XMLHttpRequest();
oXHR.open("GET", "admin/user-count.php", true);
oXHR.onreadystatechange = function (oEvent) {
if (oXHR.readyState === 4) {
if (oXHR.status === 200) {
console.log(oXHR.responseText)
} else {
console.log("Error", oXHR.statusText);
}
}
};
oXHR.send();
I have tried the method above with little success, but I also tried it like this:
var users = $.get('admin/user-count.php', function(data) {
console.log('There are '+data+' users found');
return data;
});
The same result, nothing. So what am I doing wrong or how should I do it right ?
EDIT I have made a little mistake that I fixed now, the first method works as well as the second one. but now I need to store the data I get with the first method into a variable so I can use it later on. How do I do that and also which of the two methods is better ?
I would use the second code if you already have jQuery included:
$.get('admin/user-count.php', function(data)
{
// Don't use "var" here, otherwise the variable won't be global!
myGlobalVar = parseInt(data, 10);
// Also possible: window["myGlobalVar"] = parseInt(data, 10);
});
If you want to use pure JavaScript:
var oXHR = new XMLHttpRequest();
oXHR.open("GET", "admin/user-count.php", true);
oXHR.onload = function(evt)
{
myGlobalVar = parseInt(oXHR.responseText,10);
}
oXHR.onerror = function(evt)
{
alert("Error!");
}
oXHR.send();

show loading png in the short delay whilst data is loading using jquery

I am trying to display a loading.png graphic in the very short time it takes to do my query e.t.c Everything below works perfectly currently. I just need to get the graphic loading in the td.available only when the productcode has been entered and is being checked.
Any ideas?
Here is my JS
$("#prodcodecheck").blur(function() {
var $this = $(this);
$this
.closest('tr') // find the parent tr
.find('td.available') // find the imgsample in the row
.html( $(this).attr('id')) // update the contents
//.animate({'opacity':1},200);
var available = $this.closest('tr').find('td.available')
$.post('checkstock.php', //this page reads the image code and gives you the image location
{ action: 'searchimage', productcode: $(this).val() },
function(data) {available.html(data);}
);
});
And here is checkstock.php
//Find Stock Value
function checkstock($prodCode) {
$prodCode = strtoupper($prodCode);
require '../../../../config.php';
$dbh = new PDO(DB_DSN, DB_USER, DB_PASS);
$sql = "SELECT * FROM isproducts WHERE prodCode = '".$prodCode."'";
$stmt = $dbh->query($sql);
$obj = $stmt->fetch(PDO::FETCH_OBJ);
$count = $stmt->rowCount();
echo ($count == 1 ? 'The current stock value of item '.$obj->prodCode.' is '.ROUND($obj->FreeStockQuantity, 0).'' : 'Invalid product code');
}
//Call Stock Function
checkstock($_POST['productcode']);
A simple way to do it would be:
...
// reveal a 'loading' div/span or whatever right before the request
$("#loading").show();
$.post('checkstock.php', { action: 'searchimage', productcode: $(this).val() },
function(data) {
available.html(data);
// hide it again once the request has completed
$("#loading").hide();
}
);
You create a jQuery selector that contains the loading img and append it to the td before the ajax code.
var loadingImg = $('<img src="/assets/images/loading.gif">');
available.append(loadingImg);
Why don't you use Jquery load or ajax?
And before launching the load function place the loading image inside.

Categories