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);
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 have a php script that randomly generates an image. Something like this:
<?php
$image = imagecreatetruecolor(400,200);
// process image
// rendering image
header("Content-type: image/jpeg");
imagejpeg($image);
?>
My html looks like this:
<img id="image" src="/models/plugins/image.php"/>
<button id="button">Get new image</button></body>
Then I have a jquery file that handles the click to the button, so that a new random image is loaded when the button is clicked:
$(function(){
$('#button').click(function(){
$.ajax({
url: 'models/plugins/image.php',
success: function(data){
$('#image').html('<img src="' + data + '">')
}
})
})
})
I use firebug, I can see that request is actually sent and that the response is received successfully, but the image does not change.
What am I doing wrong and how can I fix this?
I added another answer because I think that none of the previous answers solved the problem. I think, the only thing the OP wanted was to update(!) the image when the button is clicked. So there is no need for an Ajax request, just reload the image. And you can enforce that by appending a random query string to the image's src attribute.
$('#button').click(function() {
var $image = $('#image');
var plainSrc = $image.attr('src').split("?")[0]; // disregard previous query string
$image.attr('src', plainSrc + "?" + (new Date().getTime()));
});
The src attribute of an image tag actually expects an URL not actual JPEG data.
Try this:
$(function(){
$('#button').click(function(){
$('#image').attr('src', 'models/plugins/image.php?rand=' + Math.floor(Math.random()*1000) );
});
});
To use the image inside the src attribute you need to provide a valid URI, for example a data-URI:
<?php
$image = imagecreatetruecolor(400,200);
// process image
// create image URI
ob_start();
imagejpeg($image);
echo "data:image/jpeg;base64,", base64_encode(ob_get_clean());
?>
I once compiled a more detailed answer for a similar question.
The resulting image has to be base64 encoded to be included like that.
So you need to do the following:
Edit the image
Get resulting image in data string.
To get image string, you either store it to filesystem and read it through file_get_contents() (useful for cache) or use imagejpeg() without location, which places the image in output buffer. To get the value from output buffer use ob_start() and ob_get_contents().
Convert data string of the image to base64 (using base64_encode())
Return this string to browser
Set image "src" field to "data:image/png;base64,[BASE64]" where [BASE64] is the string returned from PHP.
The image you are calling is being cached by browser, use a query string at the end of your image url to let the browser thing its a new image and it should not use cached version.
Something like this:
$(function(){
$('#button').click(function(){
$.ajax({
url: 'models/plugins/image.php?t='+((new Date).getTime()),
success: function(data){
$('#image').html('<img src="' + data + '">')
}
})
})
})
Instead of $('#image').html('<img src="' + data + '">'), try $('#image').attr('src', data);
Use jquery + php. Doing custom AJAX captcha. i.e user clicks on image, it automatically updates.
<script src="/js/jquery.js"></script>
<script>
$(document).ready(function(){
$.post('/captcha.php', {}, function(resp){
$("div").html(resp);
});
});
</script>
<div></div>
in PHP header already sent, so if it includes into <img src="/captcha.php" /> it prints captcha in jpeg. The problem seem to be is header that need to be sent. So, how can i do this? The header is sent in PHP. It doesnt work in js.
If you want to change an image in an HTML document, then change the src attribute of the image (or replace the image element with a new one). Don't use XMLHttpRequest at all.
Add header function in Your captcha.php file:
header('Content-Type: image/jpeg');
If you are loading the source from a different script then you can simply send the src of the file through a string value. In that way your captcha.php code becomes something like this
$source="/path/to/the/file.jpg";
header("Content-type:text/plain");
print $source;
When you receive it you can do the following to change the source
$("#changeCaptchaButton").click(function() {
$.ajax({
url: "captcha.php",
cache: false,
success: function(data) {
alert("changing source of image");
var source=data;
$("#captchaImg").attr("src", source);
}
});
});
If you are doing the change in the current script then don't use the ajax but use the latter jQuery method
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 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.