PHP Image Loading - php

I have a PHP Image that I use like this:
<img src="image.php">
Sometimes it takes up to 10 seconds to render (there are some heavy dataloads coming in from an API). It works great but there's no way of telling whether anything is happening, I was wondering if there was a way I could show a Loading message while its doing its business, either in Javascript or PHP.
Thanks!

<img src="image.php" style="background: url(loading.gif) no-repeat center center;" />
Where loading.gif could be something like an ajax spinner animation.
I use this technique all the time.

Check out this example
HTML
<ul id="portfolio">
<li class="loading"></li>
<li class="loading"></li>
<li class="loading"></li>
</ul>
Javascript
// DOM ready
$(function () {
// image source
var images = new Array();
images[0] = 'http://farm4.static.flickr.com/3293/2805001285_4164179461_m.jpg';
images[1] = 'http://farm4.static.flickr.com/3103/2801920553_656406f2dd_m.jpg';
images[2] = 'http://farm41.static.flickr.com/3248/2802705514_b7a0ba55c9_m.jpg';
// loop through matching element
$("ul#portfolio li").each(function(index,el){
// new image object
var img = new Image();
// image onload
$(img).load(function () {
// hide first
$(this).css('display','none'); // since .hide() failed in safari
//
$(el).removeClass('loading').append(this);
$(this).fadeIn();
}).error(function () {
$(el).remove();
}).attr('src', images[index]);
});
});
CSS
ul#portfolio { margin:0; padding:0; }
ul#portfolio li { float:left; margin:0 5px 0 0; width:250px; height:250px; list-style:none; }
ul#portfolio li.loading { background: url(http://www.codedigest.com/img/loading.gif) no-repeat center center; width:50px;height:50px}

Check out the DEMO
The Code:
/*
overlay function:
-------------------------
Shows fancy ajax loading message. To remove this message box,
simply call this from your code:
$('#overlay').remove();
*/
function overlay()
{
if (!$('#overlay').is(':visible'))
{
$('<div id="overlay">Working, please wait...</div>').css({
width:'300px',
height: '80px',
//position: 'fixed', /* this is not suppported in IE6 :( */
position: 'absolute',
top: '50%',
left: '50%',
background:'url(images/spinner.gif) no-repeat 50% 50px #999999',
textAlign:'center',
padding:'10px',
border:'12px solid #cccccc',
marginLeft: '-150px',
//marginTop: '-40px',
marginTop: -40 + $(window).scrollTop() + "px",
zIndex:'99',
overflow: 'auto',
color:'#ffffff',
fontWeight:'bold',
fontSize:'17px',
opacity:0.8,
MozBorderRadius:'10px',
WebkitBorderRadius:'10px',
borderRadius:'10px'
}).appendTo($('body'));
}
}
You can edit background: property above to specify loading image too. You need to call overlay() function when you want to show the loading message. Later, you can use $('#overlay').remove(); to remove the loading message any time.

Why not try caching the image object? Would reduce the load? Or is this something that is always updating? Your JavaScript approach would simply be a image pre-loader or handler function that would replace the 'img' with a loading indicator. Look # jQuery for a simple way of doing this.

<img src="image.php">loading...</img>

Related

How to insert a sketch box in a web form and be able to save it as image in database and edit later?

I tried to implement the code explained in this link. https://zipso.net/a-simple-touchscreen-sketchpad-using-javascript-and-html5/.
Following is the code that I tried. However, I am not getting an idea how to save this the sketch as image and retrieve it later for edits. Also, this looks like a longer approach and there should be a shorter and more efficient way do this.
<html>
<head>
<title>Sketchpad</title>
<script type="text/javascript">
// Variables for referencing the canvas and 2dcanvas context
var canvas,ctx;
// Variables to keep track of the mouse position and left-button status
var mouseX,mouseY,mouseDown=0;
// Variables to keep track of the touch position
var touchX,touchY;
// Draws a dot at a specific position on the supplied canvas name
// Parameters are: A canvas context, the x position, the y position, the size of the dot
function drawDot(ctx,x,y,size) {
// Let's use black by setting RGB values to 0, and 255 alpha (completely opaque)
r=0; g=0; b=0; a=255;
// Select a fill style
ctx.fillStyle = "rgba("+r+","+g+","+b+","+(a/255)+")";
// Draw a filled circle
ctx.beginPath();
ctx.arc(x, y, size, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();
}
// Clear the canvas context using the canvas width and height
function clearCanvas(canvas,ctx) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
// Keep track of the mouse button being pressed and draw a dot at current location
function sketchpad_mouseDown() {
mouseDown=1;
drawDot(ctx,mouseX,mouseY,12);
}
// Keep track of the mouse button being released
function sketchpad_mouseUp() {
mouseDown=0;
}
// Keep track of the mouse position and draw a dot if mouse button is currently pressed
function sketchpad_mouseMove(e) {
// Update the mouse co-ordinates when moved
getMousePos(e);
// Draw a dot if the mouse button is currently being pressed
if (mouseDown==1) {
drawDot(ctx,mouseX,mouseY,12);
}
}
// Get the current mouse position relative to the top-left of the canvas
function getMousePos(e) {
if (!e)
var e = event;
if (e.offsetX) {
mouseX = e.offsetX;
mouseY = e.offsetY;
}
else if (e.layerX) {
mouseX = e.layerX;
mouseY = e.layerY;
}
}
// Draw something when a touch start is detected
function sketchpad_touchStart() {
// Update the touch co-ordinates
getTouchPos();
drawDot(ctx,touchX,touchY,12);
// Prevents an additional mousedown event being triggered
event.preventDefault();
}
// Draw something and prevent the default scrolling when touch movement is detected
function sketchpad_touchMove(e) {
// Update the touch co-ordinates
getTouchPos(e);
// During a touchmove event, unlike a mousemove event, we don't need to check if the touch is engaged, since there will always be contact with the screen by definition.
drawDot(ctx,touchX,touchY,12);
// Prevent a scrolling action as a result of this touchmove triggering.
event.preventDefault();
}
// Get the touch position relative to the top-left of the canvas
// When we get the raw values of pageX and pageY below, they take into account the scrolling on the page
// but not the position relative to our target div. We'll adjust them using "target.offsetLeft" and
// "target.offsetTop" to get the correct values in relation to the top left of the canvas.
function getTouchPos(e) {
if (!e)
var e = event;
if(e.touches) {
if (e.touches.length == 1) { // Only deal with one finger
var touch = e.touches[0]; // Get the information for finger #1
touchX=touch.pageX-touch.target.offsetLeft;
touchY=touch.pageY-touch.target.offsetTop;
}
}
}
// Set-up the canvas and add our event handlers after the page has loaded
function init() {
// Get the specific canvas element from the HTML document
canvas = document.getElementById('sketchpad');
// If the browser supports the canvas tag, get the 2d drawing context for this canvas
if (canvas.getContext)
ctx = canvas.getContext('2d');
// Check that we have a valid context to draw on/with before adding event handlers
if (ctx) {
// React to mouse events on the canvas, and mouseup on the entire document
canvas.addEventListener('mousedown', sketchpad_mouseDown, false);
canvas.addEventListener('mousemove', sketchpad_mouseMove, false);
window.addEventListener('mouseup', sketchpad_mouseUp, false);
// React to touch events on the canvas
canvas.addEventListener('touchstart', sketchpad_touchStart, false);
canvas.addEventListener('touchmove', sketchpad_touchMove, false);
}
}
</script>
<style>
/* Some CSS styling */
#sketchpadapp {
/* Prevent nearby text being highlighted when accidentally dragging mouse outside confines of the canvas */
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.leftside {
float:left;
width:220px;
height:285px;
background-color:#def;
padding:10px;
border-radius:4px;
}
.rightside {
float:left;
margin-left:10px;
}
#sketchpad {
float:left;
height:300px;
width:400px;
border:2px solid #888;
border-radius:4px;
position:relative; /* Necessary for correct mouse co-ords in Firefox */
}
#clearbutton {
font-size: 15px;
padding: 10px;
-webkit-appearance: none;
background: #eee;
border: 1px solid #888;
}
</style>
</head>
<body onload="init()">
<div id="sketchpadapp">
<div class="leftside">
Touchscreen and mouse support HTML5 canvas sketchpad.<br/><br/>
Draw something by tapping or dragging.<br/><br/>
Works on iOS, Android and desktop/laptop touchscreens using Chrome/Firefox/Safari.<br/><br/>
<input type="submit" value="Clear Sketchpad" id="clearbutton" onclick="clearCanvas(canvas,ctx);">
</div>
<div class="rightside">
<canvas id="sketchpad" height="300" width="400">
</canvas>
</div>
</div>
</body>
</html>

Can't retrieve a specific portion of an HTML file (single.php) with AJAX in Wordpress

I have a small problem with a feature that I'm trying to implement on my site. I want when I click on an excerpt from a blog post on my homepage that the content of the article (single.php) opens in a modal window.
I use jQuery and Ajax to do that and it works really well except that Ajax fetches me the entire contents of single.php file (ie the header with scripts, styles, doctype, footer, etc.). I would just like to get the div (#PostContainer) that includes the title of the article and the content.
You will probably tell me to just delete my header and footer of the single.php file, but this is not possible because it is important to keep intact my file to be able to access from the address of the blog post (www.mydomainname.com/blog-post1).
It turns out that I am not at all familiar with WordPress :/ This is the first time I build a theme. The codes I shared with you run like a charm on WordPress but recovers me all of my single.php file (header + content in my div #postContainer + footer). I would like to recover only the contents of my div #postContainer.
I'm stuck :/
Someone would help me please ?
Thank you so so much for your time !
Here are my codes :
HTML :
<a class="hs-inner-click modal" data-content="<?php the_permalink(); ?>" rel="<?php the_ID(); ?>" href="<?php the_permalink(); ?>">
CSS :
.modal-window {
position: fixed;
left: 50%;
top: 50px;
width: 720px;
background-color: #fff;
transform: translate(-50%, 0);
z-index: 11;
}
.modal-shade {
position: fixed;
height: 100%;
width: 100%;
background-color: rgba(0, 0, 0, .7);
z-index: 10;
}
.modal-close {
position: absolute;
top: 10px;
right: 10px;
}
JQUERY & AJAX in a JS file :
(function($) {
$.fn.modal = function (opt) {
var settings, createModal, closeModal, body;
settings = $.extend({
'modal': 'jquery-modal',
'close': 'jquery-modal-close',
'closeText':'',
'shade': 'jquery-modal-shade'
}, opt);
body = $('body');
closeModal = function(modal, shade) {
modal.remove();
shade.remove();
};
createModal = function(data) {
var shade, close, modal;
shade =$('<div />', {
class: settings.shade
}).on('click', function() {
closeModal(modal, shade);
});
close =$('<a />', {
text: settings.closeText,
class: settings.close,
href: '#'
}).on('click', function(e) {
closeModal(modal, shade);
e.preventDefault();
});
modal =$('<div />', {
html: data,
class: settings.modal
}).append(close);
body.prepend(shade, modal);
};
this.on('click', function(e) {
var self =$(this);
$.ajax({
url:self.data('content'),
type: 'get',
cache: false,
}).done(function(data) {
createModal(data);
}).error(function() {
createModal('There is a mistake');
});
e.preventDefault();
});
};
})(jQuery);
I would suggest to use WordPress REST API V2 for the request without the need of selecting a div or loading single.php without header & footer.
This will allow you to load post content by just calling an endpoint similar to this: /wp-json/wp/v2/posts/<id>
Full API reference here.
Alternatively I am not sure if it will work but jquery code might help you (execute onload of modal): $("#jquery-modal").load("www.mydomainname.com/blog-post1 #postContainer");
ADDITIONALLY: On ajax success append content on a dummy div and use it to find only the part of the page you need and return it.
That's the way jquery load() actually works if you check the source.
jQuery( "<div>" ).append( jQuery.parseHTML(data) ).find("#postContainer");

Loading another image with data-rel inside a div tag

I am trying to change from a loading image to display a chart. I've never used the data-rel attribute before, so I am confused on how to word this question properly, perhaps the code I have will explain it:
<div id="chk_all" style="width: 320px; height: 260px; background: url(/inquire/images/wait.gif) 50% 50% no-repeat;" data-rel="/inquire/?action=gchd&prj=1119&tp=chk&stp=0&cht=pie"></div>
This is what I have to make the chart:
<?php
'<div id="iss_part" class="ov_chart_iss" style="width: 320px; height: 260px;" data-rel="' . Helpers::buildURL(array('action' => SiteMap::CHART_GET_DATA, Defaults::PROJECT => $prj['id'],
Defaults::TYPEOFDATA => Defaults::ISSUE, Defaults::SUBTYPEOFDATA => 1,
Defaults::CHART_TYPE => Defaults::CHART_TYPE_COLUMN)) .'"></div>; ?>'
This code displays the previous div tag I posted, if it helps, here is an image of what I am trying to accomplish:
http://imgur.com/phjNuAJ,SQHV45S#0 and this is what I have currently: http://imgur.com/phjNuAJ,SQHV45S#1
Basically, I am trying to load what is in the data-rel attribute instead of it staying on the wait.gif image. Does this make any sense, and if so, how would I change this?
Thanks
new way
<div id="chk_all" style="width: 320px; height: 260px; background: url(/inquire/images/wait.gif) 50% 50% no-repeat;" data-rel='http://path.pointing.to.chart.com/inquire ...'></div>
// JS
var chkDiv = document.getElementById('#chk_all'),
data = chkDiv.dataset;
var req = new XMLHttpRequest();
req.open("GET", "path/to/thing"+data.rel, true);
req.send("");
req.onreadystatechange = function () {
if (req.readyState != 4 || req.status != 200) return;
chkDiv.style.background = '';
chkDiv.innerHTML = x.responseText;
};
does this work for you? Haven't tested but in theory, should work.
Hope it helps.

open a popup when a condition true

I want to open a popup when 'if' condition true
otherwise it opens normally.
But the code that I used, open the popup whether the condition is true or false.
so, help me guys and give ur views
script that I use.
<script>
$(document).ready(function() {
var id = '#dialog';
//Get the screen height and width
var maskHeight = $(document).height();
var maskWidth = $(window).width();
//Set heigth and width to mask to fill up the whole screen
$('#mask').css({'width':maskWidth,'height':maskHeight});
//transition effect
$('#mask').fadeIn(1000);
$('#mask').fadeTo("slow",0.8);
//Get the window height and width
var winH = $(window).height();
var winW = $(window).width();
//Set the popup window to center
$(id).css('top', winH/2-$(id).height()/2);
$(id).css('left', winW/2-$(id).width()/2);
//transition effect
$(id).fadeIn(2000);
//if close button is clicked
$('.window .close').click(function (e) {
//Cancel the link behavior
e.preventDefault();
$('#mask').hide();
$('.window').hide();
});
//if mask is clicked
$('#mask').click(function () {
$(this).hide();
$('.window').hide();
});
});
</script>
and the css is here.
<style>
#mask {
position:absolute;
left:0;
top:0;
z-index:9000;
background-color:#000;
display:none;
}
#boxes .window {
position:absolute;
left:0;
top:0;
width:440px;
display:none;
z-index:9999;
padding:20px;
padding-top:0px;
}
#boxes #dialog {
width:975px;
padding-top:0px;
background-color:#ffffff;
background-image: url(../Images/form_bg.png);
background-repeat: no-repeat;
}
</style>
and the div with condition.
<?php
$check_crm=mysql_num_rows(mysql_query("select * from crm where party_id='$_GET[party_id]'"));
if($check_crm>0)
{
?>
<div id="boxes">
<div id="dialog" class="window">
<!-- content-->
</div>
</div>
<?php
}
?>
According to PHP doc, mysql_query() will return a reference to a result, not the result itself.
You will have to use additional methods like mysql_num_rows() or mysql_fetch_assoc() on the result reference returned by mysql_query().
For example:
$check_crm = mysql_query("select * from crm where party_id='".mysql_real_escape_string($_GET['party_id'])."' limit 1");
if (mysql_num_rows($check_crm) > 0)
BTW:
Be careful with potential SQL injection. Use at least mysql_real_escape_string() on user input, or better bind your variables to your queries.
Use of old mysql_* PHP functions is discouraged. Use of PDO library is preferred. Check ORMs like Propel or Doctine as well.
You can add LIMIT 1 to your query to avoid useless processing, if your goal is to check only if at least one match is found in table crm given the party_id.
The above code will open the popup when the document is loaded because the it is included in the $(document).ready function. Try to include that in one function and call when the condition is true

jQuery loads the data from PHP but then it disappears, why?

I have searched to see if there is a post similar here and if someone finds it sorry for the duplicate.
So my dilemma is this:
Given the code below, why it my returned data loading and then disappearing?
CSS
#contentbg{
background-image: url(../images/jp_01.jpg);
background-repeat: no-repeat;
background-position: top;
position: absolute;
width: 755px;
height: 629px;
}
#content{
position: relative;
}
JS
function getHome(){
$.post("php/functions.php?s=home",
function(data) {
$('#content').html(data);
});
};
HTML
<div id="contentbg">
<div id="content"></div>
</div>
<ul id="navlist">
<li id="home"></li>
</ul>
PHP
function displayHome($home){
if(isset($home)){
$home = '<img src="images/home.jpg" alt="Home" width="755" height="630" />';
return $home;
}
}
if (isset($_GET['s'])) {
switch ($_GET['s']) {
case "home":
echo displayHome($_GET['s']);
break;
}
}
I know that the data gets loaded if I alter the JS as seen below:
function getHome(){
$.post("php/functions.php?s=home",
function(html) {
alert("Data Loaded: " + html);
});
};
The problem is that you are not cancelling the standard action when you click on the link so what is happening is that you click, the javascript gets executed and then index.php gets loaded.
You need to return false from your getHome function to solve this.
function getHome(){
$.post("php/functions.php?s=home",
function(data) {
$('#content').html(data);
});
return false;
}
As you are using jquery already, you can also get rid of the inline javascript and use a function like:
$("#home a").click(function(event) {
event.preventDefault();
$.post("php/functions.php?s=home",
function(data) {
$('#content').html(data);
});
);
That assures as well that the standard event (the click on the link) gets cancelled with the first line.
I don't see any item with the id #content in your HTML, are you sure it exists?
I assume #content is defined in your HTML structure:
$('#content').load('php/functions.php?s=home');
Also try removing #content { position: relative; } for now, just incase the content is "jumping" once loaded into the document
There seems to be no "content" div in your html.
Also, use
$("#content").load("url");
as theres no need to use $.post because no post data is being sent.

Categories