Reputation: 53
Ok so I have one page, called albums.php, with the following code:
<?php
require_once('./config.php');
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$album = $mysqli->query("SELECT * FROM Albums");
print('<div id="grid">');
print('<ul>');
while ($row = $album->fetch_assoc()) {
$cover = $row['Album_Cover'];
$name = $row['Album_Name'];
$id = $row['Album_ID'];
print ('<li>');
print('<form method="POST" action="">');
print("<input type='image' src=$cover name='image' id='image' class=$id>");
print("</form>");
print('<br/>');
print ("$name");
print ('</li>');
}
print('</ul>');
print('</div>');
print('<br/>');
print('<br/>');
print('<br/>');
print('<br/>');
$mysqli->close();
?>
DB_HOST, DB_USER, DB_PASSWORD, and DB_NAME come from config.php. albums.php (again, the code above) is linked to the script button.js, the code for which is below:
$("#image").click(function(e) {
e.preventDefault();
var id = $(this).attr('class');
var dataString = 'id='+id;
$.ajax({
type: "POST",
data: dataString,
url: "./pictures.php",
success: function(data) {
alert(data);
}
});
});
My goal is to pass the id of the clicked image to pictures.php using ajax. My code for pictures.php is as follows:
<?php
require_once('./config.php');
require_once('./albums.php');
$id = $_POST['id'];
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$pictures = $mysqli->query("SELECT * FROM Pictures WHERE Album_ID = $id");
print('<div id="grid">');
print('<ul>');
while ($row = $pictures->fetch_assoc()) {
$picture = $row['Picture'];
print("<li><img src=$picture class='thumbnail'></li>");
}
print('</ul>');
print('</div>');
$mysqli->close();
?>
Do I also have to link the button.js script in pictures.php? Other than that, I can't think of a possible issue with this code. By the way, all three of these files are stored in the same folder on my server, so I believe I am accessing them correctly. Any help would be much appreciated!
Upvotes: 2
Views: 1078
Reputation: 10665
Just to mention few things:
As mentioned in the comment Ids must be unique but it wont crash your code.
You must have put your js code before the php code that constructs image elements or you have to use jquery's $(document).ready(function(){//your code})
; to make sure that you are registering the click event listener for the images.
On your js change:
var dataString = 'id='+id;
to var dataString = id;
and
url: "./pictures.php"
to url: "pictures.php"
Upvotes: 2