I'm looking for a php script server side that load an image in a div on client side.
first shot:
ajax.php
if((isset($_POST['id'])) && ($_POST['id']=="loadphoto") && (ctype_digit($_POST['idp']))) {
$query=mysql_query("SELECT articleid, photoid FROM articles_photos WHERE id='".$_POST['idp']."'", $mydb);
if(mysql_num_rows($query)!=0){
while($row=mysql_fetch_array($query, MYSQL_NUM)) {
$path="./articles/photos/".$row[0]."/".$row[1];
}
echo $path;
}
}
myjs.js
function loadPhoto(mexid) {
$.ajax({
type: 'POST',
cache: false,
url: './auth/ajax.php',
data: 'idp='+escape(mexid)+'&id=loadphoto',
success: function(msg) {
$('.articleviewphoto1').find("img").each(function(){
$(this).removeClass().addClass('photoarts');
});
$('#'+mexid).removeClass().addClass('photoartsb');
$('#visualizator').html('<img src="'+msg+'" class="photoartb" />');
}
});
return false;
}
Are you looking to host a list of possible images in the PHP file and load different images based on the id you send? If so, you can set:
$Img = $_POST['idp'];
And use a switch statement to pass back the image file path:
switch ($Img){
case (some_value):
echo 'images/some_file.jpg';
break;
case (another_value):
echo 'images/another_file.jpg';
break;
}
Then place the file path in an tag and load that into $('#visualizator').html();
Am I on track at least with what you want? If so, I can flesh the answer out a bit.
I'm assuming the image already exists somewhere and isn't being generated on the fly. In the PHP script, you can access the variables with $_POST['idp'] and $_POST['id']. Do whatever processing you need, and then simply echo the URL. The variable msg in the javascript will be everything echo'd by the PHP script. Then, you could just do this:
$('#visualizator').html('<img src="' + msg + '" />');
Related
I'm creating a link which appends a $_GET variable to the end of it for use of deleting files / other PHP tasks.
Delete file
Part of my PHP code looks for the variable and if it exists, it runs the unset function to remove the file, but when I reload the webpage, it obviously tries to remove the file again. Is there any way to remove the $_GET after it has been run once to stop the processing after a refresh?
<?php
if (isset($_GET['delete_file'])) {
if (file_exists($full_path.$_GET['delete_file'])) {
unlink($_GET['delete_file']);
} else {
echo "File ".$full_path.$_GET['delete_file']." doesn't exist";
}
}
?>
Delete file
You can use ajax to remove files so it won't refresh.
Delete file
<script>
function deletefile(filename){
var data = {delete_file:filename };
$.ajax({
url: 'delete.php',
type: 'post',
data: data,
success: function(response) {
// .. do something with response ..
// you can use window.location to refresh page
// or if you have js method to refresh page. you can call it here
}
});
}
</script>
In php file you can retrive with post
<?php
if (isset($_POST['delete_file'])) {
if (file_exists($full_path.$_POST['delete_file'])) {
unlink($_POST['delete_file']);
} else {
echo "File ".$full_path.$_POST['delete_file']." doesn't exist";
}
}
?>
But as the commenters say this is open to potential security issues. You need to take care of security if you use this approach in production.
I have a javascript that needs to pass data to a php variable. I already searched on how to implement this but I cant make it work properly. Here is what I've done:
Javascript:
$(document).ready(function() {
$(".filter").click(function() {
var val = $(this).attr('data-rel');
//check value
alert($(this).attr('data-rel'));
$.ajax({
type: "POST",
url: 'signage.php',
data: "subDir=" + val,
success: function(data)
{
alert("success!");
}
});
});
});
Then on my php tag:
<?php
if(isset($_GET['subDir']))
{
$subDir = $_GET['subDir'];
echo($subDir);
}
else
{
echo('fail');
}?>
I always get the fail text so there must be something wrong. I just started on php and jquery, I dont know what is wrong. Please I need your help. By the way, they are on the same file which is signage.php .Thanks in advance!
When you answer to a POST call that way, you need three things - read the data from _POST, put it there properly, and answer in JSON.
$.ajax({
type: "POST",
url: 'signage.php',
data: {
subDir: val,
}
success: function(answer)
{
alert("server said: " + answer.data);
}
});
or also:
$.post(
'signage.php',
{
subDir: val
},
function(answer){
alert("server said: " + answer.data);
}
}
Then in the response:
<?php
if (array_key_exists('subDir', $_POST)) {
$subDir = $_POST['subDir'];
$answer = array(
'data' => "You said, '{$subDir}'",
);
header("Content-Type: application/json;charset=utf-8");
print json_encode($answer);
exit();
}
Note that in the response, you have to set the Content-Type and you must send valid JSON, which normally means you have to exit immediately after sending the JSON packet in order to be sure not to send anything else. Also, the response must come as soon as possible and must not contain anything else before (not even some invisible BOM character before the
Note also that using isset is risky, because you cannot send some values that are equivalent to unset (for example the boolean false, or an empty string). If you want to check that _POST actually contains a subDir key, then use explicitly array_key_exists (for the same reason in Javascript you will sometimes use hasOwnProperty).
Finally, since you use a single file, you must consider that when opening the file the first time, _POST will be empty, so you will start with "fail" displayed! You had already begun remediating this by using _POST:
_POST means that this is an AJAX call
_GET means that this is the normal opening of signage.php
So you would do something like:
<?php // NO HTML BEFORE THIS POINT. NO OUTPUT AT ALL, ACTUALLY,
// OR $.post() WILL FAIL.
if (!empty($_POST)) {
// AJAX call. Do whatever you want, but the script must not
// get out of this if() alive.
exit(); // Ensure it doesn't.
}
// Normal _GET opening of the page (i.e. we display HTML here).
A surer way to check is verifying the XHR status of the request with an ancillary function such as:
/**
* isXHR. Answers the question, "Was I called through AJAX?".
* #return boolean
*/
function isXHR() {
$key = 'HTTP_X_REQUESTED_WITH';
return array_key_exists($key, $_SERVER)
&& ('xmlhttprequest'
== strtolower($_SERVER[$key])
)
;
}
Now you would have:
if (isXHR()) {
// Now you can use both $.post() or $.get()
exit();
}
and actually you could offload your AJAX code into another file:
if (isXHR()) {
include('signage-ajax.php');
exit();
}
You are send data using POST method and getting is using GET
<?php
if(isset($_POST['subDir']))
{
$subDir = $_POST['subDir'];
echo($subDir);
}
else
{
echo('fail');
}?>
You have used method POST in ajax so you must change to POST in php as well.
<?php
if(isset($_POST['subDir']))
{
$subDir = $_POST['subDir'];
echo($subDir);
}
else
{
echo('fail');
}?>
Edit your javascript code change POST to GET in ajax type
$(document).ready(function() {
$(".filter").click(function() {
var val = $(this).attr('data-rel');
//check value
alert($(this).attr('data-rel'));
$.ajax({
type: "GET",
url: 'signage.php',
data: "subDir=" + val,
success: function(data)
{
alert("success!");
}
});
});
});
when you use $_GET you have to set you data value in your url, I mean
$.ajax({
type: "POST",
url: 'signage.php?subDir=' + val,
data: "subDir=" + val,
success: function(data)
{
alert("success!");
}
});
or change your server side code from $_GET to $_POST
please help to resolve the following issues:
There is a page which loads the image.
50 pictures.
How to make, that images would be displayed gradually (example google photo)?
$(document).ready(function(){
$.ajax({
type: 'POST',
url: document.location.href,
dataType: 'html',
data: {'ajax-query': 'true'}
success: function(data){
$('#divgallery').append(data);
}
});
})
Here comes the server code
if($i=0; $i<50;$i++){ echo '<img src="/img/' . $img . '">'; }
They are displayed all at once, after the server-side code is done.
How display images on each iteration?
Any tips, link or code example would be useful.
Firstly, on the server site return the image links in such way that they can be retrieved individually. I recommend JSON fromat.
$res = array();
if($i=0; $i<50;$i++){ $res[] = '<img src="/img/' . $img . '">'; }
echo json_encode($res);
Secondly, after you get the data you have to add the images one by one, but with a delay between the additions.
success: function(data){
delayAppend($("#divgallery"), data, 0);
}
And the delayAppend function would be something like:
function delayAppend($div, data, index){
if(index >= data.length)
return;
$div.append(data[index]);
setTimeout(function(){ delayAppend($div, data, index+1); }, 500);
}
Here is a demo of the delayAppend function: http://jsfiddle.net/s7Q8W/
Note: Code not fully tested.
So I'm making a website for a client, and the client has tons of photos from tons of different bands they photographed in the 80s and 90s that they would like to try and sell.
Instead of making a page for each band (theres over 100) like the previous site did, I am trying to make one page that uses Javascript/PHP to change the image directory to that band when the text for that band is clicked.
So far, I am able to use a PHP function to find photos in the slideshow folder, but I have been unable to update this function to search through a sub directory in the slideshow folder. (For example, when 'Metallica' is clicked, I empty #imageGal, and then I would like to append all the new metallica images from the metallica folder to the gallery).
My PHP code is:
<?php
$imagesDir = '';
$images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
echo json_encode($images);
?>
This PHP code seems to work great.
I get the images using this JQuery code:
$('#imageGal').empty();
$.ajax({
url: "slideshow/getimages.php",
dataType: 'json',
success: function(json){
for(var i=0;i<json.length;i++){
$('#imageGal').append('<img src="slideshow/' + json[i] + '">');
}
}, failure: function(json){
alert('Something went wrong. Please try again.');
}
});
When a user clicks on a band (ie Metallica), this code is executed.
$('.options').mousedown(function() {
var name = $(this).attr('id');
//$('#output').html(name);
$.ajax({
type: "POST",
url: "slideshow/getimages.php",
data: {
imageDir: name
}, success: function(msg){
alert( "Data Saved: " + msg );
}
});
$('#imageGal').empty();
$.ajax({
url: "slideshow/getimages.php",
dataType: 'json',
success: function(json){
for(var i=0;i<json.length;i++){
$('#imageGal').append('<img src="slideshow/' + json[i] + '">');
}
}, failure: function(json){
alert('Something went wrong. Please try again.');
}
});
});
I am unable to get the $imagesDir variable to change, but if I were to manually enter "Metallica" in $imagesDir = "Metallica" variable, it loads those images perfectly.
Can anyone offer any help/advice? I've been at this for a many hours now. Thanks for anything!
Unless you have register_globals on then you need to reference the variable through the global $_POST array. $_POST['imagesDir'] instead of $imagesDir.
However I would state in it's current form it would be a very bad idea to simply replace it as someone could attempt to exploit your code to list any directory on the server.
You should append the parent directory to prevent an exploit. Something like this:
EDIT you have to chdir() to the path before glob will work. I've updated my code below.
<?php
$imagesDir = $_SERVER['DOCUMENT_ROOT']; // this is the root of your web directory
$images = array();
// and this line ensures that the variable is set and no one can backtrack to some other
// directory
if( isset($_POST['imagesDir']) && strpos($_POST['imagesDir'], "..") === false) {
$imagesDir .= "/" . $_POST['imagesDir'];
chdir($imagesDir);
$images = glob('*.{jpg,jpeg,png,gif}', GLOB_BRACE);
}
echo json_encode($images);
?>
I'm not an ajax expert but you seem to be posting imageDir.
So your PHP code should be looking for $_POST['imageDir'].
<?php
$imagesDir = $_POST['imageDir'];
$images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
echo json_encode($images);
?>
Does this solve it?
I have a simple checkbox, on click it sends XHR to PHP page , php processes correctly and I use json_encode($response) to return. But instead of a simple true or false I get the source code for the page and it is causing a "parsererror" of course.
ajax call as follows
$.ajax({
type: "post",
url: "myprocessor.php",
dataType: 'json',
data: { "id" : idnumber, "action": "makeLive", "isLive" : "1" },
beforeSend: function(data) {
$("#ajaxInProgress").addClass('progress');
},
success: function(data) {
$("#status").removeClass().addClass((data.error === true) ? 'error' : 'success').text('Success! Appraiser is NO LONGER Live ').slideDown('slow');
},
error: function(data) {
$("#status").removeClass().addClass('error').text(' - Changing the Live status for this appraiser to "Not Live" has failed - APPRAISER IS STILL LIVE IN SYSTEM, please try again').slideDown('slow');
},
complete: function(data) {
$("#ajaxInProgress").removeClass('progress');
setTimeout(function() {
$("#status").slideUp('slow').removeClass();
},2000);
}
});
The php I post to is as follows:
if (isset($_POST['action'])) {
if($_POST['action']=='makeLive') {
$checkappraiser=mysql_query("SELECT * FROM table WHERE id='".mysql_real_escape_string($_POST['id'])."'");
if (mysql_numrows($checkappraiser)>0) {
$livesetting=mysql_result($checkappraiser,0,"live");
$livesetting=!$livesetting;
$runSql = mysql_query("UPDATE table SET live='$livesetting' WHERE id='".mysql_real_escape_string($_POST['id'])."'");
if(!$runSql) {
$return['error'] = true;
} else {
$return['error'] = false;
}
}
}
echo json_encode($return);
}
Any suggestions would be great.
I am getting the proper data passed
I am getting the correct data updated in DB
My response is coming back as a parser error because it is trying to parse the source code as a json array.
Just a quick check, do you put <?php at the beginning of your php file?
That, or you're doing something wrong in your webserver, not passing files through to php correctly. Does hitting the php file directly load the source or the result?
If you hit page.php, does it load the same thing as if you hit page.phP or pHP, etc? It matters to web server filters, depending on the web server...
If you use tomcat for java, for example... you can turn off case sensitivity for finding files, but it does not turn off case sensitivity for mapping files to filters or servlets, so .jsp would load the jsp servlet, but .jsP would not.