简体   繁体   中英

pass sql query result to another php page (that is contained in a div) to run another sql query - all on the same page, with ajax

Objective: Pass sql query result to separate php file that uses that result to run another sql query.

I have an sql query that lists a few rows of data. I want one data piece of the row as a link. When that link is clicked, that data is passed to another php page that runs an sql from that passed data.

Currently have an ajax script that updates content in a separate div on the same page as the original sql query. Basically my sql lists basketball players info. Name, height, weight, position. I want to click the players name and have a separate php file pull up more data based on the players name.

What I have to create the column with the players name:

echo
"<td><a href=javascript:void(0); onClick=getdata('/players/player1.php,'content');>".$players['first_name']." ".$players['last_name']."</a></td>";

How do I pass the name to a separate php file? Thank you!

A couple of errors in your HTML: the attribute data needs to be wrapped in quotes, and you have a missing single quote:

echo
"<td><a href='javascript:void(0);' onClick='getdata(\'/players/player1.php\',\'content\');'>".$players['first_name']." ".$players['last_name']."</a></td>";

So, knowing that, you've obviously not written the getData function?

Assuming that you haven't, and assuming you're a beginner, I'd encourage you to look at jQuery as this will simplify a lot of what you are doing. (It can be done in JavaScript without jQuery if that's what you prefer, but this is simpler.)

Your HTML will be

echo
"<td><a href='#' class='js-load-more' data-playername='" . htmlspecialchars($players['first_name']) . "'>".htmlspecialchars($players['first_name'])." ".htmlspecialchars($players['last_name'])."</a></td>";

Than include jQuery in your HTML (see http://jquery.com/ )

Then include the event handlers: and right on the front page of jQuery are the two examples you need to adapt. You'll end up with something like this (where #info is a div on your page where you display the data):

$( ".js-load-more" ).on( "click", function( event ) {
    $.ajax({
       url: 'http://YourUrl/page.php?name=' + $(this).data('playername'),
       error: function() {
          $('#info').html('<p>An error has occurred</p>');
       },
       dataType: 'json',
       success: function(data) {
          var $title = $('<h1>').text(data.talks[0].talk_title);
          var $description = $('<p>').text(data.talks[0].talk_description);
          $('#info')
             .append($title)
             .append($description);
       },
       type: 'GET'
    });
});

have a play from there, this should get you going.

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