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!
Related
Ok this is very spooky....
I'm trying to reload a CAPTCHA Image which is generated on the server side and I don't want to reload the whole page for that, hence I have to use AJAX.
So what I do is to first trigger a php file on server side (with AJAX), which updates all needed stuff so I can have a new CAPTCHA Image.
Then when this is done I simply update the image src="", to load the new image from that php file.
Here the code:
File 1
HTML:
<tr id="rowWithCaptcha">
<td><p><img id="captchaImg" src="./?<?php echo session_name() ?>=<?php echo session_id() ?>"/></p></td>
</tr>
JQuery-Skript:
$("#reloadImg").click(function(){
$.ajax({
url: 'getNewKCAPTCHA.php',
cache: false,
type: 'POST',
async: false,
success: function(){
$("#captchaImg").attr("src","http://localhost/Captcha2/TestPages/TestPage3Q/getNewKCAPTCHA.php?");
}
});
});
File two:
PHP:
kcaptcha.php is where all the captcha magic happends :)
so if you just open this php file in your browser, you'll get the captcha image itself.
And if you reload the page the image changes every time.....
<?php include('kcaptcha.php'); session_start(); $captcha = new KCAPTCHA(); $_SESSION['captcha_keystring'] = $captcha-getKeyString(); echo TRUE; ?>
So the weird thing now is that this whole thing (AJAX call and update of picture) is working just fine with the new chrome browser, but when I try it with FFOX or IE it works only one time and any further click doesnt change anything.....I think it has something to do with the JQuery part, but I just cant get it to work :///
Every help is appreciated!!!
Thanx in advance!
Assuming that
url: 'getNewKCAPTCHA.php',
and
http://localhost/Captcha2/TestPages/TestPage3Q/getNewKCAPTCHA.php?
are actually the same script, there is no need to call them twice.
Consider this simple method (it's working method I use in real projects):
$("#reloadImg").click(function(){
var d = new Date ();
var captcha = "http://localhost/Captcha2/TestPages/TestPage3Q/getNewKCAPTCHA.php?r=" + d.getTime ();
$("#captchaImg").attr ("src", captcha);
});
http://jsfiddle.net/hGfgn/
Regards
this might be corellating to the HTML5 support. i had the same problem not long ago and it seems that neither FF nor IE support
$('whatever').click(function(){});
but it could work if you call it with onclick="function()" in the html-tag, but i do not know if it works
I'm not a big fan of editing src attributes.
I would usually remove the image (or replace with a loading image) and then append the new image (and remove the loading image). The code below should remove the image and append a new image - I missed out all of the buffering image replacement stuff
$("#reloadImg").click(function(){
$.ajax({
url: 'getNewKCAPTCHA.php',
cache: false,
type: 'POST',
async: false,
success: function(){
$("#captchaImg").remove();
$("#rowWithCaptcha td p").append('<img id="captchaImg" src="http://localhost/Captcha2/TestPages/TestPage3Q/getNewKCAPTCHA.php?" />');
}
});
});
hope it helps
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().
Interested in building my own drag'n'drop file uploader using JQuery/AJAX/PHP.
Basically I want a file-uploader that users of my site can just drag the file from their computer into a div I created, and it will then upload the file for them to the selected destination.
I would like to build this from scratch, and not use any plugins so that I can better manipulate the restrictions (file types, size, destination folders, etc.)
Have scoured google with no luck, only plugins. Can anyway steer me in the right direction?
UPDATE
Ok, so I figured out how to do what I want. Just set the file input field opacity to 1 so it is hidden, and you can still drag a file into that general area and if you hit the text field it will catch it. HOWEVER, I would like to know how to increase the height/width on the file input field (tried basic css on the file, but it only increases the 'browse' button size and not the actual field where you can drop the file into. Any ideas how to do this?
I basically want a big square div that says 'Drop file here'. So I need to resize the input field.
Just to chime in here, as I've been doing this as well the last couple of days. From what I understand if you're binding the drop event through jQuery you need to access that event.dataTransfer object by going through the event.originalEvent object in the event provided by jQuery.
Example:
In this I bind to both the dragover as well as drop events, as this was necessary to prevent it from performing the default action (found that solution here: Prevent the default action. Working only in chrome )
$('#dropzone').bind('dragover drop', function(event) {
event.stopPropagation();
event.preventDefault();
if (event.type == 'drop') {
console.log(event.originalEvent.dataTransfer.files);
}
});
Also there seems to be a bug where if you console.log() the event.dataTransfer (or event.originalEvent.dataTransfer) it's files array is empty, it's pointed out here: event.dataTransfer.files is empty when ondrop is fired?
To better answer the OPs question (I just noticed the rest of it, and I know it's old but some one might find this helpful):
My implementation is in jQuery, so I hope that's alright:
var files = [];
// Attaches to the dropzone to pickup the files dropped on it. In mine this is a div.
$("#dropzone").bind('dragover drop', function(event) {
// Stop default actions - if you don't it will open the files in the browser
event.stopPropagation();
event.preventDefault();
if (e.type == 'drop') {
files.push(event.originalEvent.dataTransfer.files);
}
});
// Attach this to a an input type file so it can grab files selected by the input
$("#file-input").bind('change', function(event) {
files.push(event.target.files);
});
// This is a link or button which when clicked will do the ajax request
// and upload the files
$("#upload-button").bind('click', function(event) {
// Stop the default actions
event.stopPropagation();
event.preventDefault();
if (files.length == 0) {
// Handle what you want to happen if no files were in the "queue" on clicking upload
return;
}
var formData = new FormData();
$.each(files, function(key, value) {
formData.append(key, value);
});
$.ajax({
url: 'upload-ajax',
type: 'POST',
data: formData,
cache: false,
dataType: 'json',
processData: false, // Don't process the files - I actually got this and the next from an SO post but I don't remember where
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function(data, textStatus, jqXHR) { /* Handle success */ },
error: function(jqXHR, textStatus, errorThrown) { /* Handle error */ }
});
});
You could also bind to the other events in the accepted answer for doing effects like making the dropzone fade in so you can see it (that's on my todo list for my library). This is the core of the actual ajax file uploading I use, however.
I don't really have a convenient way to test that, but that's in essence how I did it (I essentially took all that code from the library I've been making and adapted it to fit a general code block on here in an easy to understand way). Hopefully this helps some people out. Starting from here it was actually really easy to go ahead and add in a file queue list, with the ability to delete files from the queue, so this should be a pretty good starting point.
You can use the HTML5 dragenter and dragleave events to create a dropzone.
Then by placing a file input inside the dropzone, and hiding it with CSS, you can upload the file when the change event for the input fires, like this
var dropzone = $("#dropzone"),
input = dropzone.find('input');
dropzone.on({
dragenter : dragin,
dragleave : dragout
});
input.on('change', drop);
function dragin(e) { //function for drag into element, just turns the bix X white
$(dropzone).addClass('hover');
}
function dragout(e) { //function for dragging out of element
$(dropzone).removeClass('hover');
}
function drop(e) {
var file = this.files[0];
$('#dropzone').removeClass('hover').addClass('dropped').find('img').remove();
// upload file here
}
FIDDLE
For those interested, I found this tutorial/demo to be helpful: http://www.viget.com/inspire/custom-file-inputs-with-a-bit-of-jquery/
Basically uses a <span> to cover the default input field.
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
}
I am making a page that when you click on a "story" it loads the text and the media for that story, I have a seperate PHP script for the story text and the media (video or image) loading. both scripts work and actually it all works.
My problem is that when you click the story it is supposed to load the text, and then slide the media down when it's loaded However, it slides down even when the text is still loading.
newspaper.nmyster.co.uk/ is the site in question. click on the vimeo story on the left and see what I mean.
The code for the AJAX that loads the story and media is:
$.ajax({
url: './scripts/storyLoader.php?storyid='+storyId,
success: function(result){
$('#storycontainer').hide();
$('#loading').remove();
$('#storycontainer').hide(0).html(result).fadeIn(1000);
}
});
$.ajax({
url: './scripts/mediaLoader.php?storyid='+storyId,
success: function(result){
$('.martefact').hide();
$('#loading').remove();
$('.martefact').html(result).slideDown(1000);
}
});
Basically, I only want the media div to slide down once the video or image has finished loading.
Thanks
I would use something like this:
var requestHandle;
function loadPage(url, vars) {
//cancel pending
if (requestHandle!=null)
requestHandle.abort();
//load page..
requestHandle = $.get(url, vars, function(data) {
$('#storycontainer').hide();
$('#loading').remove();
$('#storycontainer').hide(0).html(data).fadeIn(1000);
});
}
Your request is asynchronous. It means that the script won't wait for data to load before executing the aesthetics bit.
You need to add async: false to your $.ajax call (look up other options over at jQuery documentation). That way, browser will wait for data to arrive first before executing the rest of JS.
What does your mediaLoader.php script do? Does it just check the database whether there are any media entries for the given story and if so format them properly and output them? Because currently I don't think you can slide down after the video is completely loaded, since you are embedding a vimeo video container, which handles the loading of the video itself and you have no access to it...
You need to use an 'on complete' callback function on the first animation.
Have a look jQuery api documentation for .fadeIn()
It should look something like:
$('#book').fadeIn('slow', function() {
// Code to run after animation completed...
});