hold off showing image until fully loaded in html result via ajax - php

I know a lot of questions have been asked about this question but i am still not abale to get my head round it.
I have a number of images that when clicked, i get the big image via ajax. The result from ajax a load of html that goes into my chosen div. the reason for this is that i plan on using other information on the page that ajax returns.
The html that gets returned contains the img tag and i am wanting hold off showing the image until it is fully loaded.
here is what i have so far:
function getimage(sent_data){
$("#gallery").hide()
$.ajax({
type: "GET",
url: "gallery/name.php?",
data: "id=" + sent_data,
success: callback
});
}
function callback(data, status){
$("#gallery").html('').hide(); // you need to remove the old image
$("#gallery").removeClass("loading").html(data).fadeIn("slow");
}
and the data returned is:
<a href="test.jpg" class = "cloud-zoom" rel="position: 'inside' , showTitle: false, adjustX:-4, adjustY:-4">
<img src="test.jpg" width="450" height="301" alt="johnboy"/></a>
Thank you.

I haven't tried it but this should work.
when you get your html data from your server place the returned html but not show, then add load handler to your gallery element and when it loads show your html.
$("#gallery").load(function(e) {
$(this).show();
});
function callback(data, status){
//edit: you must place your returned data
$("#gallery").html(data).hide(); // you need to remove the old image
}

Related

Adding PHP to dynamically created div content

I am making a website with a submenu, which renders content to a div. The website is powered by Wordpress, and this part of the site is a plugin I've made. I want the content of the div to fetch info from database, i.e. I want to add PHP code. Can't seem to add any PHP though. If I make the loaded content a PHP file, it doesn't work due to the jQuery('#pageContent').html(msg) in the JS, and if I add PHP code to a HTML file, that code doesn't seem to be recognised. What would be the way to do this? I should perhaps add that the PHP I want to add is to be part of a form and as far as I can see needs to be in the same file as the HTML.
Here is the JS function with Ajax to load content:
function loadPage(url) //the function that loads pages via AJAX
{
url=url.replace('#page',''); //strip the #page part of the hash and leave only the page number
jQuery('#loading').css('visibility','visible'); //show the rotating gif animation
jQuery.ajax({ //create an ajax request to load_page.php
type: "POST",
url: ajax_object.ajax_url,
data: {
action: 'ajax_request2',
page: url //with the page number as a parameter
},
dataType: "html", //expect html to be returned
error: function(xhr, textStatus, textError) {
console.log(textError);
},
success: function(msg) {
window.alert("Working loadPage ajax!");
if(parseInt(msg)!=0) //if no errors
{
jQuery('#pageContent').html(msg); //load the returned html into pageContent
jQuery('#loading').css('visibility','hidden'); //and hide the rotating gif
}
}
});
}
I modified your function a little bit and directed it to a test site for JSON data. This little snippet works. Maybe it is helpful to you?
As the test site only returns JSON the "html" I put into #pageContent is not really html, but I hope you get the point nonetheless.
If you want to know what Ajax returned then you can always insert a console.log(msg) in the right place (see the commented-out line below).
And - just to be clear - if your loaded content is to be generated by a PHP script, then the url in your loadPage function should of course point to a PHP script on the relevant server. This script will look for the data and process it into your desired html format before sending it back as the response to the Ajax request.
function loadPage(url){
url=url.replace('#page',''); //strip the #page part of the hash and leave only the page number
jQuery('#IAmloading').show(); //show the rotating gif animation
jQuery.ajax({ //create an ajax request to load_page.php
type: "GET",
url: url, // the URL of the page to be loaded ...
data: {action: 'ajax_request2', id: 4}, //your further parameters ...
dataType: "json", //expect json to be returned
error: function(xhr, textStatus, textError) { console.log(textError);},
success: function(msg){ console.log("Working loadPage ajax!");
// console.log(msg); // show what the AJAX request returned
if(msg) //if no errors
{
jQuery('#pageContent').html(JSON.stringify(msg)); //put msg into pageContent
jQuery('#IAmloading').hide(); //and hide the rotating gif
}
}
});
}
// call the function with the URL of a test site (returns JSON only ...):
loadPage('https://jsonplaceholder.typicode.com/users');
#IAmloading {visibility: hidden}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="IAmloading">Please wait, page is loading ...</div>
<div id="pageContent"></div>

Using AJAX to generate behind the scenes?

I want to create images using imagejpeg() but they seem to take longer to render than the time it takes to load the page, therefore the images are either not displaying or they are truncated.
I have tried to delay the loading of the page until the images are completely created without resolve so now I am attempting to get the images created prior to page load.
My fail is as follows:
function createimages(x) {
$.post("image-dev.php?curID=" + x, function(rdata) {
console.log(rdata);
});
setTimeout(function() {
window.location = "image-review.php?curID=" + x;
}, 5000);
}
image-dev.php is my image creation file that pulls all necessary data from my DB then uses imagejpeg to create and save my folder.
If I navigate directly to image-dev.php with the proper ID associated. My images are created and saved properly.
My hopes were that I could use AJAX to call image-dev.php sometime before loading the image review page. I hoped that this would 'pre-develop' the images so that they would load properly when reviewed.
My console.log of the rdata shows that the image-dev.php is loading and executing, but the files aren't being created.
Is there an issue with creating images behind the scene?
When image is already created php can return "true".
With ajax you can do that.
function createimages(x){
$.ajax({
url: "image-dev.php?curID="+x,
beforeSend: function( xhr ) {
//here you can hide elements or other DOM manipulations
}
}).done(function( rdata) {
console.log(rdata);
//when php is ready you can show images or other DOM manipulations
}
});
});
kristiyan, Thanks!
I have decided to give up on the idea of predeveloping my images and used your tactic.
Since the images were still truncating when displayed, I now have placeholder images on the image review page and am loading the new images in after they complete.
I'm not yet sure how to see if an image is truncated, so I had to add in a delay before resetting the placeholders src attribute.
$.ajax({
type: 'POST',
url: "image-dev.php?curID="+x,
success: function(rdata) {
console.log(rdata);
setTimeout(function(){
$('#placeholder').attr('src', 'newImage.jpg');
},5000);
}
});
This seems to be working acceptably!

Get the Width of Div and LIMIT the mySQL query according to no of elements?

I needed to display number of images in
<li><img class='1'><img class='1'><img class='1'></li>
<li><img class='1'><img class='1'><img class='1'></li>
but as my div is auto increasing according to screen width. I needed to calculate number of images to display according to the width of div , suppose width is 1200px and each image will be of 150px . so the number of image to display are 8 .
<script type='text/javascript'>
var screen_width = document.getElementById('div_1').offsetWidth();
var no_of_images =Math.round(screen_width/100);
</script>
I am getting the images from mysql database, using LIMIT query .. I want to LIMIT it to no of images i got using var no_of_images. But as their is no direct rule of integrating javascript variable into mysql query. i want to pass it to PHP variable and then use it in Mysql. But unfortunately i dont know how to do it.
You can use the document.ready event handler to make sure the DOM is ready to be manipulated and then make an AJAX request to your server-side script that could output the HTML for the correct number of images to place in the container:
//wait for the `document.ready` event to fire
$(function () {
//cache the container element since it will be used later more than once
//also get the width of the container and figure out how many 150px wide images can fit without being clipped
//note that this does not take into consideration any padding/margin/border for the images
var $container = $('#div_1'),
screen_width = $container.width(),
no_of_images = Math.floor(screen_width / 150);
//create an AJAX call to your server-side script to get the image HTML
$.ajax({
url : '<URL>',
type : 'get',//or 'post'
data : { 'no_of_images' : no_of_images },//jQuery will handle data encoding if you pass it an object
success : function (serverResponse) {
//now the AJAX request has returned successfully so this fades the container out, replaces it's HTML with the server response and then fades back in
$container.fadeOut(500, function () {
$container.html(serverResponse).fadeIn(500);
});
},
//if an error occurs with the AJAX call this is how you handle it, you may just try to re-send the AJAX call
error : function () {
alert('an error occured');
}
});
});
you can pass it as a get param when loading the page. e.g. when creating the link to load the next page just add it as param. on initial page load you get all the images bu display only the ones you need for the available resolution
You have to use AJAX.
<script type='text/javascript'>
var screen_width = document.getElementById('div_1').offsetWidth();
var no_of_images =Math.round(width/100);
$.ajax({
type: "post",
url: "script.php",
data: "no_of_images="+no_of_images,
success: function(){
// do something
}
});
</script>
You have to use jQuery to get my code working, cause i used the jQuery method $.ajax().

jQuery load raw image from .php file, how to include

I have a page with some pictures drawn in php. I load a file with the reference-ids. Then the page is done loading, each of the image-elements will be loaded using ajax. (for example ajax_image.php?url=http://www.opti.com/1). Ajax_image then draws a image and outputs it using header jpeg.
The problem is that when I try to "include" or show this picture in my reference-file the output is not a picture, it's text saying:
�JPEG
My jQuery looks like this:
$.ajax({
url: "ajax_picture.php?url="+escape($('#bilde1').attr('rel')),
cache: false,
success: function(html){
$('#bilde1').html(html);
alert('Picture 1 loaded');
sizeChangeCallback();
}
});
I assume I get this problem because I use html to include the picture in the reference-file. But I have no idea what function to use, in order for it to understand that it's a raw picturefile.
You don't need to use ajax for this. Instead, simply output an <img> tag like this:
var imgTag = '<img src="ajax_picture.php?url=' + escape($('#bilde1').attr('rel')) + '" />';
$('#bilde1').html(imgTag);

load content via jquery ajax after php output is complete

I am currently using jquery ajax to POST data to a php file which uses that data to build and output a jQuery-based gallery.
the "links" that are clicked on to trigger the ajax are:
<li class="portfolioLink" id="identity">identity</li>
<li class="portfolioLink" id="mobile">mobile</li>
<li class="portfolioLink" id="web">web</li>
and a sample of the jQuery ajax is:
$("#identity").click(function(){
$.ajax({
url: 'portfolio.php',
type: "POST",
data: ({data: 'portfolio/design/identityDesign/*'}),
success: function(data){
$("#content_middle").html(data);
}
});
$("#identity").addClass('active');
$(".portfolioLink:not(#identity)").removeClass('active')
});
(this jquery is basically iterated 2 more times with different data:)
This is working fine, except that the output of portfolio.php (the gallery builder) is loaded into #content_middle as the output's JavaScript is being processed (so it looks like the gallery is being built live in #content_middle). Seeing it happen will probably make more sense: www.frende.me/design.php
What I want to happen is for the gallery to load fully built.
How about you hide the element, add the new html to it and show it again? Like this:
$("#identity").click(function(){
$.ajax({
url: 'portfolio.php',
type: "POST",
data: ({data: 'portfolio/design/identityDesign/*'}),
success: function(data){
$("#content_middle").hide();
$("#content_middle").html(data);
$("#content_middle").show();
}
});
$("#identity").addClass('active');
$(".portfolioLink:not(#identity)").removeClass('active') });
If I understand correctly, you would like to have the content appear completely once the page loads. Unfortunately the page is returned as soon as the DOM is created. So images will be considered constructed, but that does not mean that their src has been loaded.
Try using a image preloader like this one
Hope this helps, otherwise comment if you need more details.

Categories