I do want to send an HTTP request using Ajax and receive the response (picture links from the database) when the User click on a link. The parameter I put on my Ajax function call is the value of the class of the clicked link which I get through a loop in PHP. I think that's a little bit confusing.. Here's my code
The Ajax function call in : index.php
<script>
var current = 0;
function showPics(str) {
if (str=="") {
document.getElementById("displayPic").innerHTML="";
return;
}
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("displayPic").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getpics.php?q="+str,true);
xmlhttp.send();
}
</script>
getpics.php
<?php
$q = $_GET["q"];
$host = "127.0.0.1";
$db = "pcqsp";
$user = "root";
$pass = "";
try {
$conn = new PDO("mysql:host=$host; dbname=$db", $user, $pass);
} catch(Exception $e) {
die('Erreur : ' . $e->getMessage());
}
$req = $conn->prepare('SELECT * FROM screenshot WHERE id_work = :id_work');
$req->execute(array('id_work' => $q));
while ($data = $req->fetch())
{
echo "<img class='popup_pics' src='" . $data['link_screenshot'] . "' />";
}
$req->closeCursor();
?>
The Ajax call on index.php
<?php
// Open a database connection
$host = "127.0.0.1";
$db = "pcqsp";
$user = "root";
$pass = "";
try {
$conn = new PDO("mysql:host=$host; dbname=$db", $user, $pass);
} catch(Exception $e) {
die('Erreur : ' . $e->getMessage());
}
$req = $conn -> query('SELECT * FROM work');
$i = 1;
while ($data = $req -> fetch()) { ?>
<div class="image-even">
<img src="<?php echo $data['cover_work'] ?>" width="421" height="590" />
</div>
<div class="more">
// Here's the problem
<a class="<?php echo $i ?>-popup" href="#displayPics">More details</a>
</div>
<?php
$i ++;
}
?>
<script type="text/javascript">
$current = 0;
$('a[class*="popup"]').click(function(){
current = $(this).attr('class').charAt(0);
showPics(current); //Ajax function call
});
</script>
When I was not doing the loop via PHP (I was doing it statically as writing : 1-popup
, 2-popup
, etc.. Everything was working.
Please do you have a solution of this problem ? Thank you.
your jquery call is not built inside the window.ready
event. try including it in the window.ready
event by doing the following.
<script type="text/javascript">
$current = 0;
$(document).ready(function (e) {
$('a[class*="popup"]').click(function(){
current = $(this).attr('class').charAt(0);
showPics(current); //Ajax function call
});
});
</script>
it's possible that your javascript is executed before the dom is ready