EDIT: Check at the end of this for the solution
I am new to php, ajax and all other things :)
My question is: is there a way for a php file to return a value?
I have:
- a file "loadImages.php" containing the script to get the paths to images from the database.
- an image gallery where I want to load images via ajax.
- a database containing the path to the images (/images/image1.jpg, /images/image2.jpg).
- 4 categories of images.
What i'm trying to do is :
When clicking on a link (example, first category), I want to call via jquery's ajax(), loadImages.php with the category passed via POST (cat0, cat1, cat2, ...)
I want to return the value from this php file for example : <img src="image/image1.jpg" />
, so via javascript, I can retrieve this string. Using only return
in my php file returns XMLHttpRequest
when i'm putting the ajax()
function in a variable instead of the string <img>
.
Is there a way to do it? Or maybe a better way, as I don't fully understand ajax.
Thank you! Sorry for my bad grammar.
Below is a more precise map of what i'm trying to do.
JavaScript:
var test = $.ajax({
type: "POST",
url: "loadImages12.php",
data: "category=0",
complete: function() {
alert("COMPLETE");
},
error: function (){
alert("NOT LOADED");
}
});
PHP (loadImages.php)
function createThumb() {
if(isset($_POST['category'])) {
$imageQuery = mysql_query("SELECT * FROM t_pictures WHERE p_category = 0");
$thumbHtml = '';
while ($tempImageQueryFetch = mysql_fetch_assoc($im开发者_如何学CageQuery)){
$thumbHtml .= '<a href="#" class="thumbnail"><img src="ressources/images/' . $tempImageQueryFetch["p_fileName"] . 'Small.jpg" /></a>';
}
return $thumbHtml;
}
else {
$noCategory = "NO CATEGORY TEST";
return $noCategory ;
}
}
createThumb();
SOLVED
Php File
function createThumb(){
//Mysql request $someVar = //Result of request return $someVar }echo createThumb()
Javascript
$("#someDiv").load("loadImages.php", {category:0});
An AJAX request to PHP is exactly the same as a normal request for a website. You request data from example.com/foo/bar
and in return you receive text. The return
statement of PHP has nothing to do with what's returned to the client. Only things you echo
or otherwise output will be received by the client. That's the same for normal pages and AJAX requests.
So, to "return" <img src="image/image1.jpg" />
to your Javascript AJAX call, echo
that string in PHP.
if you want to use the php file that you already have (loadImages.php) just echo the result of the function:
echo createThumb();
Just make the php script to return the path to thumbnail.
and then do something like this in js
somediv.html('<a href="#" class="thumbnail"><img src="">');
and just use the path returned by the php file for the img src ..
精彩评论