I have two containers, the first is a form (select) that contains names of players, the second is for images related to those players.
When a user changes the select value the image also changes to that particular players image.
I have created this in JQuery and everything works wonderful but with the amount of players I decided to look into databases.
To get a better understanding here's a short version of what I have in JQuery.
<select id="clubPlayers" name="clubPlayers"></select>
var PLAYER_NAMES = [
"Player 1",
];
var players = '';
for (var i=0;i<PLAYER_NAMES.length;i++){
players += '<option value="'+ PLAYER_NAMES[i] + '">' + PLAYER_NAMES[i] + '</option>';
PLAYER_NAMES.sort();
}
$('#clubPlayers').append(players);
// Players
$('#clubPlayers').on('change', function() {
$('.player-img>img').remove();
if ( this.value == 'Player 1'){
$(".player-img").append("<img src='players/player_1.png'>");
}
});
Now I want to recreate this but in PHP & Mysql. I have created a database, the database consists of 3 columns, They are "id" "player_name" & "player_image".
(player_image will be input as links to images)
I got as far as being able to query the db and loop the player_name's field as select elements.
<?php
$conn = new mysqli('localhost', 'root', '', 'players')
or die ('Cannot connect to db');
$result = $conn->query("SELECT id, player_name, player_image FROM player_info");
echo "<select id='clubPlayers' name='clubPlayers'>";
while ($row = $result->fetch_assoc()) {
unset($id, $player_name, $player_image);
$id = $row['id'];
$player_name = $row['player_name'];
$player_image = $row['player_image'];
echo '<option value="'.$player_name.'">'.$player_name.'</option>';
}
echo "</select>";
?>
That works great but I still need to get the players image link from the db and create an img tag with the link.
My question is, Can this (JQUERY)
$('#clubPlayers').on('change', function() {
$('.player-img>img').remove();
if ( this.value == 'Player 1'){
$(".player-img").append("<img src='players/player_1.png'>");
}
});
be recreated and added onto my existing PHP above.
You need to store the data of the image on the element.
$player_image = $row['player_image'];
echo '<option value="'.$player_name.'" data-image="'. $player_image .'">'.$player_name.'</option>';
and in your jQuery you access it from the selected option...
$('#clubPlayers').on('change', function() {
var image = $(this).data('image');
$('.player-img>img').remove();
$(".player-img").append("<img src='players/"+ image +"'>");
});
The selected option should be available in $(this) in context. If not, you'll need to add a .find(selectedValue)into the data line.
Related
I have a form that dynamically adds and removes elements.
I also have a drop down that is populated dynamically.
How can I put the two together?
Here is the code that I use to dynamically add and remove elements:
$(document).ready(function(e) {
var maxRows = 100;
var x = 1;
var phpcode = '<?php $stmt=$author_of_book->read_author_of_section(); $num=$stmt->rowCount(); if($num>0){ echo '<select name="author_of_book[]" id="author_of_book-list">'; echo '<option value="" disabled selected>Select</option>'; while($row = $stmt->fetch(PDO::FETCH_ASSOC)){ extract($row); echo '<option value="' .$row["author_of_book"]. '"data-author_of_book_id="' .$row["author_of_book_id"]. '">' .$row["author_of_book"]. '</option>'; } echo "</select>"; } ?>';
$("#add").click(function(e) {
if (x <= maxRows) {
$("#book_table").append("<tr><td>" + phpcode + "</td><td><select name='book_title[]' id='book_title-list'><option value='0' disabled selected>Select</option></select></td><td><button type='button' id='remove' class='btn btn-danger'>Remove</span></button></td></tr>");
}
});
$("#book_table").on('click', '#remove', function(e) {
$(this).closest('tr').remove();
});
});
The idea is that a user can add as many books as they wish.
When a user selects a particular author the next drop down will list the titles of all of the author's books.
Using this PHP code I dynamically populate a drop down list based on the previous drop down selection:
I have created two class files.
class author_of_book{
// database connection and table name
private $conn;
private $table_name = "author_of_book";
// object properties
public $author_of_book_id;
public $author_of_book;
public function __construct($db){
$this->conn = $db;
}
public function read_author_of_book(){
$query = "SELECT author_of_book_id, author_of_book
FROM " . $this->table_name . "
ORDER BY author_of_book";
// prepare query statement
$stmt = $this->conn->prepare($query);
// execute query
$stmt->execute();
return $stmt;
}
}
Here is the other class file:
class book_title{
// database connection and table name
private $conn;
private $table_name = "book_title";
// object properties
public $book_title_id;
public $author_of_book_id;
public $book_title;
public function __construct($db){
$this->conn = $db;
}
public function read_book_title(){
$query = "SELECT book_title_id, author_of_book_id, book_title
FROM " . $this->table_name . "
WHERE author_of_book_id = :author_of_book_id
ORDER BY book_title";
// prepare query statement
$stmt = $this->conn->prepare($query);
// santize
$this->author_of_book_id=strtoupper(htmlspecialchars(strip_tags($this->author_of_book_id)));
// bind value
$stmt->bindParam(":author_of_book_id", $this->author_of_book_id);
// execute query
$stmt->execute();
return $stmt;
}
}
I also have this php code for json file
// set json headers
header("Access-Control-Allow-Methods: GET");
header('Content-Type: application/json');
$author_of_book_id=isset($_GET['author_of_book_id']) ? $_GET['author_of_book_id'] : die('Author ID not found.');
// include database and object files
include_once 'config/database.php';
include_once 'objects/book_title.php';
// instantiate database and object
$database = new Database();
$db = $database->getConnection();
$book_title = new book_title($db);
$book_title->author_of_book_id = $author_of_book_id;
$stmt = $book_title->book_title();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($results);
Then in the form I use this code to render the drop down list with the help of javascript
// include database and object files
include_once 'config/database.php';
include_once "objects/author_of_book.php";
// instantiate database and objects
$database = new Database();
$db = $database->getConnection();
$qfs_section = new author_of_book($db);
$page_title = "Book Form";
include_once "layout_head.php";
?>
<table id="book_table">
<tr>
<th>Author</th>
<th>Title</th>
<th><button type="button" id="add">Add</button></th>
</tr>
</table>
<?php
include_once "layout_foot.php";
And last is is JavaScript code to make the dynamic drop down work
//Author
$(document).ready(function() {
// detect change of dropdown
$("#author_of_book-list").change(function() {
// get id of selected author
var author_of_book_id = $(this).find(':selected').data('author_of_book_id');
// set json url
var json_url = "book_title_type_json.php?author_of_book_id=" + author_of_book_id;
// get json data
jQuery.getJSON(json_url, function(data) {
// empty contents of book_title dropdown
$("#book_title-list").html("");
$("#book_title-list").append("<option value='0' disabled selected>Select</option>");
// put new dropdown values to book_title dropdown
jQuery.each(data, function(key, val) {
$("#book_title-list").append('<option value="' + val.book_title + '"data-book_title_id="' + val.book_title_id + ' ">' + val.book_title + '</option>')
});
});
});
});
My problem is that every time I incorporate my drop down code into the dynamic add-remove code something goes wrong. I was able to make the first drop down to work but not the second one.
You will need to use AJAX for that. See, what PHP interpreter does is to produce HTML and JavaScript as a string and send it that way to the browser. Therefore, in order for JavaScript to get values stored in PHP, it needs to communicate back with the server. That's what the XMLHttpRequest object is there in Vanilla JavaScript, or the JQuery AJAX is there for.
Or, if you just want the PHP code embedded into JavaScript to be executed before the JavaScript is sent to the browser, you can put it without the quotation marks. Like I've done here:
var highscore=<?php echo "\"".$highscore."\";"; ?>
In my DB i have created a table named "coursePlaces" in which i have 7 columns and a number of rows.
Loading the php-file course.php I connects to the db and selects data from the table "coursePlaces" using it to echo a number of buttons with different id and value each:
<?php
/* CONNECTION TO DB */
require 'includes/dbh.inc.php';
/* ACCESS COURSE AND GRADE VAR FROM URL WITH GET */
$course = $_GET['course'];
$grade = $_GET['grade'];
/* SELECTS DATA FROM TABLE AND ECHOES BUTTONS WITH DIFFERENT ID AND VALUE DEPENDING ON TABLE CONTENT */
$sql = "SELECT * FROM coursePlaces WHERE grade='$grade' AND course='$course'";
$result = mysqli_query($con, $sql);
while ($row = mysqli_fetch_array($result)) {
echo '<input type="submit" id="place-' . $row['placeName'] . '" value="' . $row['placeName'] . '">';
}
/* CONVERTS VAR TO USE IN JQUERY SCRIPT */
echo '<script>';
echo 'var grade = ' . json_encode($grade) . ';';
echo 'var course = ' . json_encode($course) . ';';
echo '</script>';
?>
<script src="includes/global.inc.js"></script>
<!-- DIV TO ECHO OUTPUT FROM PLACE.INC.PHP -->
<div class="selectedPlace" id="selectedPlace"></div>
When clicking one of the buttons the value should be send to the file "global.inc.js" In which i have placed a script used to listen for clicks:
$('input#$row['placeName']').on('click', function() {
var place = $('input#place-$row['placeName']').val();
if (place !='') {
$.post('includes/place.inc.php', {place: place, grade: grade, course: course }, function(data) {
$('div#selectedPlace').text(data);
});
}
});
My problem is, that I don't know what the name of the button id is - since it is created from a varchar in a database table. How do i bring this information over into my .js file, so the script posts individual value from button no matter what button the user presses on the courses.php.
Use jQuery to set your variable with Ajax ( method POST ).
Try to change code as below:
$('input[type="submit"]').on('click', function() {
var place = $(this).val();
if (place !='') {
$.post('includes/place.inc.php', {place: place, grade: grade, course: course }, function(data) {
$('div#selectedPlace').text(data);
});
}
});
set on click attribute when you echo your inputs:
echo sprintf('<input type="submit" id="place-%s" value="%s" onclick="yourfunction("%s", "%s", "%s") >', $row['placeName'], $row['placeName'], $grade, $course);
and separate this yourfunction function:
function yourfunction(place, grade, course){
$.post('includes/place.inc.php', {place: place, grade: grade, course: course }, function(data) {
$('div#selectedPlace').text(data);
});
}
You should use a generic click handler instead of the one you are using.
If all button have one common class you can listen to the click of all.
Add class inputBtn to following:
echo '<input type="submit" id="place-' . $row['placeName'] . '" value="' . $row['placeName'] . '" class="inputBtn">';
Change
$('input#$row['placeName']').on('click', function() {
to
$('.inputBtn').on('click', function() {
var btnID = $(this).prop('id');
var spltID = btnID.split('-'); //split from the - & spltID[1] will contain the part that you required.
}
This code is written like just for the sake of clarity. It is possible to make it more optimal like split() function can be called on btnID to reduce code line.
I have a jQuery drop down list that uses first CARS then secondly, the models from that car. Then, when the second choice is made - hit a submit button and search for the tire that the car uses. It works great the first time, but the second time, it stops and I have to reload the page to get it to work again. Any ideas of why this is happening would be helpful. My code example is here:
Accessing a variable from inside a jquery drop down list?
Here is the code that searches:
function findtire() {
global $db;
if (isset($_POST['car'])) {
$_SESSION['car'] = $_POST['car'];
$car = $_SESSION['car'];
}
if (isset($car)) {
$query = $db->prepare("SELECT idtires FROM vehicle WHERE idcarmodel = '$car'");
$query->execute();
$tire = $query->fetchAll();
}
if (isset($tire)) {
echo "<ul>";
foreach ($tire as $name) {
echo "<li id='tiresearch'>";
echo "Tire Size is Available: " . $name['idtires'];
echo "</li>";
}
echo "</ul>";
}
else {
}
}
I want to use AJAX/Javascript with PHP to carry out this following function and not have it all done by PHP itself. I have created a function which deletes an item from the MySQL database. It gives a validation to the user if they want to remove it by selecting Yes or No.
However, how would i change this so that it does the same function but the validation appears as a popupbox, and when Yes or OK is pressed it deletes the item from the database and reloads the page to show it has been removed.
I have provided the PHP code which relates to this function, but i want to specifically change this to using AJAX/Javascript as well in accordance with PHP.
<?php
// Delete Item Question to Admin, and Delete Product if they choose
if (isset($_GET['deleteid'])) {
echo 'Do you really want to delete product with ID of ' . $_GET['deleteid'] . '? Yes | No';
exit();
}
if (isset($_GET['yesdelete'])) {
// remove item from system and delete its picture
// delete from database
$id_to_delete = $_GET['yesdelete'];
$sql = mysqli_query($link,"DELETE FROM products WHERE id='$id_to_delete' LIMIT 1") or die (mysql_error());
// unlink the image from server
// Remove The Pic -------------------------------------------
$pictodelete = ("../inventory_images/$id_to_delete.jpg");
if (file_exists($pictodelete)) {
unlink($pictodelete);
}
header("location: inventory_list.php");
exit();
}
?>
<?php
// This block grabs the whole list for viewing
$product_list = "";
$sql = mysqli_query($link,"SELECT * FROM products ORDER BY date_added DESC");
$productCount = mysqli_num_rows($sql); // count the output amount
if ($productCount > 0) {
while($row = mysqli_fetch_array($sql)){
$id = $row["id"];
$product_name = $row["product_name"];
$price = $row["price"];
$stock = $row["stock"];
$date_added = strftime("%b %d, %Y", strtotime($row["date_added"]));
$product_list .= "Product ID: $id - <strong>$product_name</strong> - £$price - Stock: $stock - <em>Added $date_added</em> <a href='inventory_edit.php?pid=$id'>edit</a> • <a href='inventory_list.php?deleteid=$id'>delete</a><br />";
}
} else {
$product_list = "You have no products listed in your store yet";
}
?>
Your JS-File
$(document).ready(function() {
$('.delete').click(function() {
event.preventDefault();
var deleteId = $(this).parent().attr('id').val();
$.get('path/to/you/phpfile', {deleteId: deleteid}, function(data) {
var confirm = confirm(data);
if (confirm==true) {
$.get('path/to/you/phpfile', {yesdelete: 1});
}
});
});
});
In your PHP-File you have to remove header('Location: ...') and the block which grabs the list, wrap it in a function or etract it to another php file to call it with the a simliar ajax-command I used above. And you have to change th $product_list in the while-loop.
Product ID: <div id="$id">$id - <strong>$product_name</strong> - £$price - Stock: $stock - <em>Added $date_added</em> <a href='inventory_edit.php?pid=$id'>edit</a> • <div class="delete">Delete</div></div><br />
jQuery get the id-value of his parent-div. It´s actually not the best way, but something like this should work.
I have a multiple drop down that goes from Country/State/city/destination.
What I want this plugin to do next, is once the destination menu is selected, the page will automatically display some general information about that destination on the same page without reloading.
The general info is in the same table as my destination drop down menu is, but under different columns.
So how can I get this information to display its self possibly in a text box or something similar only when the final distention menu is selected.
Here are some parts of my code thus far, I don't believe posting everything is necessary and might be a little confusing. PS-I am a beginner.
This is an example of my javascript which calls from my ajax.php file for the array to populate the drop down menu...
jQuery(".wrap").on('change', '#city', function() {
var querystr2 = 'cityid=' +jQuery('#city :selected').val();
jQuery.post("<?php echo plugins_url(); ?>/Destination_Drop_Down_Menu/ajax.php", querystr2, function(data) {
if(data.errorcode ==0){
jQuery('#descbo').html(data.chtml)
}else{
jQuery('#descbo').html(data.chtml)
}
}, "json");
});
This is part of my ajax.php file that previous example of jQuery is pulling information from.
$city_id = isset($_POST['cityid']) ? $_POST['cityid'] : 0;
if ($city_id <> 0) {
$errorcodeD = 0;
$strmsg = "";
$sqlD="SELECT * from destination WHERE IDCity = ". $city_id . " ORDER BY name;";
$resultD=mysql_query($sqlD);
$contD=mysql_num_rows($resultD);
if(mysql_num_rows($resultD)){
$chtmlD = '<select name="destination" id="destination"><option value="0">--Select Destination--</option>';
while($row = mysql_fetch_array($resultD)){
$chtmlD .= '<option value="'.$row['IDDestination'].'">'.$row['name'].'</option>';
}
$chtmlD .= '</select>';
echo json_encode(array("errorcode"=>$errorcodeD,"chtml"=>$chtmlD));
}else{
$errorcodeD = 1;
$strmsg = '<font style="color:#F00;">No Destination available</font>';
echo json_encode(array("errorcode"=>$errorcodeD,"chtml"=>$strmsg));
}
And MY html section that would display everything.
<h2>Destination</h2>
<div class="wrap" id="descbo">
</div>
So basically what ever destination the user chooses, the specific information for that destination will render its self on the screen in separate boxes or text areas.
Thank you!
So, if I understand correctly, you want your php script to return data from your destination table when a particular destination is selected. You said you don't want the page to reload, but I'll assume you're OK with issuing another AJAX request to the server. If that's the case, you can simply create another delegated jQuery handler for the destination <select>:
jQuery(".wrap").on('change', '#destination', function() {
var data = {destinationid: this.value};
jQuery.post("url/to/script.php", data)
.done(function(response) {
jQuery('#descbo').html(response.html);
});
Then, in your PHP, you could have something like this:
$destination_id = isset($_POST['destinationid']) ? $_POST['destinationid'] : 0;
...
$sqlD="SELECT * from destination WHERE ID = ". $destination_id . " ORDER BY name;";
$resultD=mysql_query($sqlD);
if(mysql_num_rows($resultD)){
$chtmlD = '<div class="destination">';
while($row = mysql_fetch_array($resultD)){
$chtmlD .= '<p>' . $row['whatever'] . '</p>';
}
$chtmlD .= '</div>';
echo json_encode(array("errorcode"=>$errorcodeD,"chtml"=>$chtmlD));
} else {
...
}
That will replace your original destination <select> with a div containing the destination description (or whatever the content is). If you don't want to replace the select, you could simply have the JS update a different element on the page, e.g.
jQuery('#some_other_element').html(response.html);