简体   繁体   中英

Pass data from one PHP page to another using ajax

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!

Just to mention few things:


  1. As mentioned in the comment Ids must be unique but it wont crash your code.

  2. 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.

  3. On your js change:
    var dataString = 'id='+id; to var dataString = id; and
    url: "./pictures.php" to url: "pictures.php"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM