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($imageQuery)){
$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/barand in return you receive text. Thereturnstatement of PHP has nothing to do with what’s returned to the client. Only things youechoor 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,echothat string in PHP.