How can we echo data for Progress bar in PHP? - php

We are working on a ProgressBar using Jquery UI. We are facing some problems, that we aren't getting values from PHP. We are unable to make a numerical loop that can return the value to Ajax based code.
Below is our code:
HTML
<!DOCTYPE html>
<html>
<head>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<style type="text/css">
#bardivs {
width:400px; /* or whatever the of the porgress bar is */
/*
The position of #bardivs must be something other than
static (the default) so that its children will be positioned
relative to it.
*/
position:relative;
}
#progresstext {
position:absolute;
top:0;
left:0;
}
</style>
<script>
var url = "http://localhost/sample/data.php";
$(function() {
var progress = 0;
//alert("some value" + value, value);
$("#progressbar").progressbar({ progress: 0 });
setTimeout(updateProgress, 500);
});
function updateProgress() {
var progress;
$.get(url, function(data) {
// data contains whatever that page returns
if (data < 100) {
$("#progressbar").progressbar("option", "value", data);
$("#progresstext").html("<p> Loading...<p>");
setTimeout(updateProgress, 500);
} else {
$("#progressbar")
.progressbar("option", "value", 100);
}
});
}
</script>
</head>
<div id="bardivs">
<div id="progressbar"></div>
<div id="progresstext"></div>
</div>
</html>
We don't have any idea how can we make the code in PHP use this loading function. It should in a loop.

There is no such progress: 0, the progress is measured by value and you should make the data INT because it comes as string:
$("#progressbar").progressbar({ value: 0 });
setTimeout(updateProgress, 500);
});
function updateProgress() {
var progress;
$.get(url, function(data) {
// data contains whatever that page returns
if (data < 100) {
$("#progressbar").progressbar({value: parseInt(data)});
$("#progresstext").html("<p> Loading...<p>");
setTimeout(updateProgress, 500);
} else {
$("#progressbar").progressbar({value: 100});
}
});
}
In php make sure you update the progress based on your scripts
<?php
$data = get_progress();
echo (int)$data;
?>

Related

Unity simulator disable form inputs - Laravel

I'm making some modifications on my web, in the page were I'm doing the modifications has a Unity render where you can interact with. For some unknown reason the JS files needed for the render to work are like "disabling" the iputs of the form.
But if you inspect the element you can see that there is no attribute in either css or HTML to disable it.
I'm quite lost in this problem.
In the UnityProgress.js:
function UnityProgress(gameInstance, progress) {
if (!gameInstance.Module)
return;
if (!gameInstance.logo) {
gameInstance.logo = document.createElement("div");
gameInstance.logo.className = "logo " + gameInstance.Module.splashScreenStyle;
gameInstance.container.appendChild(gameInstance.logo);
}
if (!gameInstance.progress) {
gameInstance.progress = document.createElement("div");
gameInstance.progress.className = "progress " + gameInstance.Module.splashScreenStyle;
gameInstance.progress.empty = document.createElement("div");
gameInstance.progress.empty.className = "empty";
gameInstance.progress.appendChild(gameInstance.progress.empty);
gameInstance.progress.full = document.createElement("div");
gameInstance.progress.full.className = "full";
gameInstance.progress.appendChild(gameInstance.progress.full);
gameInstance.container.appendChild(gameInstance.progress);
}
gameInstance.progress.full.style.width = (100 * progress) + "%";
gameInstance.progress.empty.style.width = (100 * (1 - progress)) + "%";
if (progress == 1)
gameInstance.logo.style.display = gameInstance.progress.style.display = "none";
setTimeout(function() {
$('.simulator-loading').fadeOut();
}, 5000);
}
function scrollDown() {
window.scrollBy({
top: 200, // could be negative value
left: 0,
behavior: 'smooth'
});
}
function scrollUp() {
window.scrollBy({
top: -200, // could be negative value
left: 0,
behavior: 'smooth'
});
}
Blade (the section where it is used):
#include('includes.questions-form', ['familia'=> $familia]) //this is afected form
#include('includes.ayuda')
</article>
#endsection
#section('pagescript')
<script src="{{ mix('/js/solution-detail.js') }}"></script>
<script src="{{ asset('unity/XXX/TemplateData/UnityProgress.js')}}"></script>
<script src="{{ asset('unity/XXX/Build/UnityLoader.js')}}"></script>
<script>
var gameInstance = UnityLoader.instantiate("simulator", "{{ asset('unity/Marine/Build/GHWebGL.json')}}", { onProgress: UnityProgress});
</script>
#endsection
Thanks for your help

google map multiple marker from database in php

I have working on Core PHP,I have created google maps marker for single static Address, I need pass dynamic multiple name and address from database where will write query getting data from database,single address is working fine but i need multiple address and multiple google markers, how to do this please help me.
Here my code:index.php
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css">
<script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.js"></script>
<meta charset="utf-8">
<style>
#map {
height: 100%;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
</body>
<script type="text/javascript">
var map;
//alert(map);
function getData() {
$.ajax({
url: "map_api.php",
async: true,
dataType: 'json',
success: function (data) {
console.log(data);
init_map(data);
}
});
}
function init_map(data) {
var map_options = {
zoom: 14,
center: new google.maps.LatLng(data['latitude'], data['longitude'])
}
map = new google.maps.Map(document.getElementById("map"), map_options);
marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(data['latitude'], data['longitude'])
});
infowindow = new google.maps.InfoWindow({
content: data['formatted_address']
});
google.maps.event.addListener(marker, "click", function () {
infowindow.open(map, marker);
});
infowindow.open(map, marker);
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyC3cIb3aYyySipxodqNJgRDUpIC17VrnXY&callback=getData" async defer></script>
</html>
Here my map_api.php file:
<?php
function get_geocode($address){
$address = urlencode($address);
$url = "http://maps.google.com/maps/api/geocode/json?address={$address}";
$resp_json = file_get_contents($url);
$resp = json_decode($resp_json, true);
//response status will be 'OK'means if able to geocode given address
if($resp['status']=='OK'){
$data_arr = array();
$data_arr['latitude'] = isset($resp['results'][0]['geometry']['location']['lat']) ? $resp['results'][0]['geometry']['location']['lat'] :'';
$data_arr['longitude'] = isset($resp['results'][0]['geometry']['location']['lng']) ? $resp['results'][0]['geometry']['location']['lng'] : '';
$data_arr['formatted_address'] = isset($resp['results'][0]['formatted_address']) ? $resp['results'][0]['formatted_address'] :'';
if(!empty($data_arr) && !empty($data_arr['latitude']) && !empty($data_arr['longitude'])){
return $data_arr;
}else{
return false;
}
}else{
return false;
}
}
echo json_encode(get_geocode('4102/4C, SRK Arcade, Tavarkere Main Road, BTM 1st Stage,Bengaluru, Karnataka 560029'));
?>

Preload audio and apply css during playback

I am looking to create sound buttons.
Have used the answer here:
Buttons click Sounds
and implemented it so that the buttons are divs and created dynamically from a MySQL DB.
Does anyone know how to preload that list of sounds on page load?
Also, I want to apply a CSS class to the div when clicked and then when the audio finishes, want it to switch back to the original CSS class.
This is what I have tried. The sounds play correctly but the onended fuction does not fire.
<script type='text/javascript'>
$(window).load(function(){
var baseUrl = "http://[URL HERE]";
var audio = [<?php echo $audiostring; ?>];
$('div.ci').click(function() {
var i = $(this).attr('id').substring(1);
mySound = new Audio(baseUrl + audio[i-1]).play();
mySound.onended = function() {
alert("The audio has ended");};
});
});
</script>
If you are using HTML5 audio you can do something like the following:
mySound.addEventListener("ended", function()
{
alert("The audio has ended");
});
Edit:
Try changing the way you create the audio tag, as referenced here.
$('div.ci').click(function() {
var i = $(this).attr('id').substring(1);
mySound = $(document.createElement('audio'));
mySound.src = baseUrl + audio[i-1];
mySound.play();
mySound.addEventListener("ended", function()
{
alert("The audio has ended");
});
});
<audio> and new Audio() should be the same but it doesn't look
like that is the case in practice. Whenever I need to create an audio
object in JavaScript I actually just create an element like
this:
The ended event is created based on .currentTime attribute. event-media-ended
the canplaythrough event was used to knowing when the browser has finished downloading the audio file and we can play
code complete use closest
<style type="text/css">
body{background: #aaa;color:#fff;}
div
{
width: 100px;
height: 100px;
background: #dda;
}
</style>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div >
</div>
<div >
</div>
<div >
</div>
<script type="text/javascript">
$(window).load(function(){
var audioFiles = [
"http://www.soundjay.com/button/beep-01a.mp3",
"http://www.soundjay.com/button/beep-02.mp3",
"http://www.soundjay.com/button/beep-03.mp3",
"http://www.soundjay.com/button/beep-05.mp3"
];
function Preload(url) {
var audio = new Audio();
// once this file loads, it will call loadedAudio()
// the file will be kept by the browser as cache
audio.addEventListener('canplaythrough', loadedAudio, false);
audio.src = url;
}
var loaded = 0;
function loadedAudio() {
// this will be called every time an audio file is loaded
// we keep track of the loaded files vs the requested files
loaded++;
if (loaded == audioFiles.length){
// all have loaded
init();
}
}
var player = document.createElement('audio');
function playAudio(index) {
player.src = audioFiles[index];
player.play();
}
function init() {
$('div').click(function(event) {
$(this).css('background', 'blue');
playAudio(Math.floor(Math.random()*audioFiles.length));
player.addEventListener("ended", function(){
player.currentTime = 0;
$(event.target).closest('div').css('background', '#dda');
});
});
}
// We begin to upload files array
for (var i in audioFiles) {
Preload(audioFiles[i]);
}
});
</script>

Duplicate photos in instagram pagination

I'm trying to pull photos from specific tag. Found an awesome tutorial and I've managed to pull photos from Instagram with pagination.
The problem I'm facing now is duplicate photos being displayed if it reaches to the end of the photos.
HTML Source
<!DOCTYPE html>
<html>
<head>
<script src='http://code.jquery.com/jquery-1.7.2.min.js' type='text/javascript' charset='utf-8'></script>
<script src='javascripts/application.js' type='text/javascript' charset='utf-8'></script>
<link rel='stylesheet' href='stylesheets/application.css' type='text/css' media='screen'>
<title>Photo Stream </title>
<meta name="description" content="Search for instagram images online.">
<meta name="author" content="Omar Sahyoun">
</head>
<body>
<!--<form id='search'>
<button class="button" type="submit" id="search-button" dir="ltr" tabindex="2">
<span class="button-content">Search</span>
</button>
<div class='search-wrap'>
<input class='search-tag' type='text' tabindex='1' value='cats' />
</div>
</form>-->
<h2 id="search">Photo Stream </h2>
<div id='photos-wrap'>
</div>
<div class='paginate'>
<a class='button' style='display:none;' data-max-tag-id='' href='#'>View More...</a>
</div>
</body>
</html>
Javascript File
// Add trim function support for IE7/IE8
if(typeof String.prototype.trim !== 'function') {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
}
}
// Instantiate an empty object.
var Instagram = {};
// Small object for holding important configuration data.
Instagram.Config = {
clientID: 'xxxx',
apiHost: 'https://api.instagram.com'
};
// Quick and dirty templating solution.
Instagram.Template = {};
Instagram.Template.Views = {
"photo": "<div class='photo'>" +
"<a href='{url}' target='_blank'><img class='main' src='{photo}' width='250' height='250' style='display:none;' onload='Instagram.App.showPhoto(this);' /></a>" +
"<span class='heart'><strong>{count}</strong></span><span class='comment'><strong>{count2}</strong></span>" +
"<span class='avatar'><iframe src='//www.facebook.com/plugins/like.php?href={url}&send=false&layout=button_count&width=40&show_faces=true&action=like&colorscheme=light&font&height=21&' scrolling='no' frameborder='0' style='border:none; overflow:hidden; width:80px; height:21px;' allowTransparency='true'></iframe></span>" +
"</div>"
};
Instagram.Template.generate = function(template, data){
var re, resource;
template = Instagram.Template.Views[template];
for(var attribute in data){
re = new RegExp("{" + attribute + "}","g");
template = template.replace(re, data[attribute]);
}
return template;
};
// ************************
// ** Main Application Code
// ************************
(function(){
function init(){
bindEventHandlers();
}
function toTemplate(photo){
photo = {
count: photo.likes.count,
count2: photo.comments.count,
avatar: photo.user.profile_picture,
photo: photo.images.low_resolution.url,
url: photo.link
};
return Instagram.Template.generate('photo', photo);
}
function toScreen(photos){
var photos_html = '';
$('.paginate a').attr('data-max-tag-id', photos.pagination.next_max_id)
.fadeIn();
$.each(photos.data, function(index, photo){
photos_html += toTemplate(photo);
});
$('div#photos-wrap').append(photos_html);
}
function generateResource(tag){
var config = Instagram.Config, url;
if(typeof tag === 'undefined'){
throw new Error("Resource requires a tag. Try searching for cats!");
} else {
// Make sure tag is a string, trim any trailing/leading whitespace and take only the first
// word, if there are multiple.
tag = String(tag).trim().split(" ")[0];
}
url = config.apiHost + "/v1/tags/" + tag + "/media/recent?callback=?&count=10&client_id=" + config.clientID;
return function(max_id){
var next_page;
if(typeof max_id === 'string' && max_id.trim() !== '') {
next_page = url + "&max_id=" + max_id;
}
return next_page || url;
};
}
function paginate(max_id){
$.getJSON(generateUrl(tag), toScreen);
}
function search(tag){
resource = generateResource(tag);
$('.paginate a').hide();
$('#photos-wrap *').remove();
fetchPhotos();
}
function fetchPhotos(max_id){
$.getJSON(resource(max_id), toScreen);
}
function bindEventHandlers(){
$('body').on('click', '.paginate a.button', function(){
var tagID = $(this).attr('data-max-tag-id');
fetchPhotos(tagID);
return false;
});
// Bind an event handler to the `click` event on the form's button
$('form#search button').click(function(){
// Extract the value of the search input text field.
var tag = $('input.search-tag').val();
// Invoke `search`, passing `tag`.
search(tag);
// Stop event propagation.
return false;
});
}
function showPhoto(p){
$(p).fadeIn();
}
Instagram.App = {
search: search,
showPhoto: showPhoto,
init: init
};
})();
$(function(){
Instagram.App.init();
// Start with a search on cats; we all love cats.
Instagram.App.search('hwplus');
});
Please help me to find a way to disable the 'View More' button if photos have reached the end.
And is there a way to add cache in JSON object and fetch variables from Javascript?
Thanks and appreciate.
Once you reach the end of the photos, the next_max_tag_id won't exist. You'll need to check if next_max_tag_id exists and if not, disable the button. You'll implement your new code on this line, maybe make a variable for photos.pagination.next_max_id and when the user clicks the button, check if the variable is defined.
Untested code:
var next_max = photos.pagination.next_max_id;
if (next_max == 'undefined') {
var next_max = 'end';
$('.paginate a').addClass('disabled');
}
//define .disabled in your CSS
$('.paginate a').attr('data-max-tag-id', next_max).fadeIn();

JQuery KeyUp Live Search. How to?

I am trying to find out why is it that I can get my live search to work but it returns all results from mysql table no matter what I type. Perhaps you could help?
I am trying to get the previous request and initiate a new one on each keyup.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Help Tool 2.0</title>
<link type="text/css" rel="stylesheet" href="assets/css/index.css" />
<script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(function(){
$('#search-box').keyup(function() {
$("#results").html('');
var xhr;
var keywords = $(this).val();
if(xhr != null) xhr.abort();
xhr = $.get("search.php", {q: keywords}, function() {
//alert("success");
})
.success(function(data) {
xhr = null;
//alert("second success");
$("#results").html(data);
})
});
});
</script>
<input id="search-box" name="q" type="text" />
<div id="results"></div>
</body>
</html>
And the PHP:
<?php
include_once ('database_connection.php');
if(isset($_GET['q'])){
$keyword = trim($_GET['q']) ;
$keyword = mysqli_real_escape_string($dbc, $keyword);
$query = "select topictitle,topicdescription from topics where topictitle like '%$q%' or topicdescription like '%$q%'";
//echo $query;
$result = mysqli_query($dbc,$query);
if($result){
if(mysqli_affected_rows($dbc)!=0){
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){
echo '<p> <b>'.$row['topictitle'].'</b> '.$row['topicdescription'].'</p>';
}
}else {
echo 'No Results for :"'.$_GET['q'].'"';
}
}
}else {
echo 'Parameter Missing';
}
?>
Try this js code in place of what you have. I added the delay function so that the script waits a specified amount of time after the user stops typing before sending the request. This prevents a large amount of requests getting sent to the server.
<script type="text/javascript">
var delay = (function() {
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
$("#search-box").keyup(
function () {
delay(function () {
var keyword = $("#search-box").val();
var URL = encodeURI("search.php?q=" + keyword);
$.ajax({
url: URL,
cache: false,
type: "GET",
success: function(response) {
$("#results").html(response);
}
});
}, 500);
}
);
</script>

Categories