jquery - change image according to text input - javascript

I have a mysql table with the name of a team in one column (club_name) and an id on another (club_id).
Every team has a logo named with their respective id .png.
Then I have a text input where the user can write the name of a team. There is a jQuery function that shows the possible team names found in the database according to what the user is typing so that it can autocomplete. Once the user selects one of the options the focus moves out of the text input. At this point, I would like the image to change to the logo corresponding to the team. When the text input is empty or the name does not match any team in the database the image should be 0.png
How can I achieve this? My code so far is below:
EDIT:
I have three problems right now:
The method suggested to store the club id in the json object is only
returning the first row of the table.
The method is below (although it only returns one row of the table it does work, the image changes to the appropriate one - I ran a little test by replacing 'thisclub' with the name of the club):
<script>
var clublist = [
<?php
$search_clubs = " SELECT club_id, club_name FROM clubs ORDER BY club_id DESC";
$result_clubs = mysql_query($search_clubs);
echo json_encode(mysql_fetch_assoc($result_clubs)); //only returns one row
?>
];
</script>
Using another method I was able to have all the rows in the json object but this one did not work when I ran the same test by replacing 'thisclub' with the name of one club):
<script>
var clublist = [
<?php
$clubid = array(); $clubname = array();
$search_clubs = mysql_query(" SELECT club_id, club_name FROM clubs ");
while($row = mysql_fetch_array($search_clubs)) {
$clubid[] = $row["club_id"]; // or smth like $row["video_title"] for title
$clubname[] = $row["club_name"];
}
$res = array($clubid, $clubname);
echo json_encode($res);
?>
];
</script>
The second problem is I don't know what to replace 'thisclub' with.
In other words, how to get the value returned by the function.
I am now using two vars - one to store the name of the clubs only, for the original function, the other one for the name of the clubs and respective id, for the function that makes the image change. This is because I don't know what changes to make in the original function so that it searches for the names in the new var (which contains club_id too)
The full code is below.
<img id="team-logo" src="logos/0.png"/>
<input type="text" class="club-name" name="home" autocomplete="off"/>
<script>
var clubs = [
<?php
$search_clubs = " SELECT club_name FROM clubs ";
$result_clubs = mysql_query($search_clubs);
while($clubs = mysql_fetch_array($result_clubs)) {
$club_name = $clubs['club_name'];
echo '"'.$club_name.'",';
}
?>
];
var clublist = [
<?php
$search_clubs = " SELECT club_id, club_name FROM clubs ORDER BY club_id DESC";
$result_clubs = mysql_query($search_clubs);
echo json_encode(mysql_fetch_assoc($result_clubs)); //only returns one row
?>
];
$(".club-name").autocomplete({
source: clubs,
autoFocus: true,
minLength: 2,
delay: 0,
close: function(event, ui){
if (!event.keyCode || event.keyCode === 13){
$(this).parents('form').find('.club-name').filter(function (){
return $(this).val() === '';
}).first().focus();
//
}
clubid = "";
$.each(clublist, function (i, elem) {
if (elem.club_name === thisclub) {
clubid = elem.club_id;
$("#team-logo").attr("src", clubid+".png");
}
});
if(clubid == "") {
// show default image
$("#team-logo").attr("src", "0.png");
}
//$("#team-logo").attr("src", clubs+".png");
}
});
</script>

I would get the club_id from the original SELECT that you do.
Then on the focus out you can do something along the lines of:
$("#team-logo").attr("src", club_id+".png");
And that will set the image src to the new image.
Edit:
To expand a bit, storing the results of the sql query in a json object using json_encode() would allow you to use something like:
<script>
var clublist = [
<?php
$search_clubs = " SELECT club_id, club_name FROM clubs ";
$result_clubs = mysql_query($search_clubs);
echo json_encode(mysql_fetch_array($result_clubs));
?>
];
</script>
// Run the following code inside the focus.out section and set thisclub to the returned clubname
clubid = "";
$.each(clublist, function (i, elem) {
if (elem.club_name === thisclub) {
clubid = elem.club_id;
$("#team-logo").attr("src", clubid+".png");
}
});
if(clubid == "") {
// show default image
$("#team-logo").attr("src", "0.png");
}
Second Edit (Complete working example):
I've tested the following and I believe it includes everything you're looking for. The problem seemed to be in the formatting of the php array when passed to json encode. Pay close attention to the HTML changes.
$sql = " SELECT club_id, club_name FROM clubs ORDER BY club_id DESC";
$result_clubs = mysql_query($sql);
if (!$result_clubs) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
$clubs = array();
while($row = mysql_fetch_assoc($result_clubs)){
$clubs[] = array('club_id' => $row['club_id'], 'club_name' => $row['club_name']);
}
?>
<img id="team-logo" src="logos/0.png"/>
<input id="clubname" type="text" class="club-name" name="home" autocomplete="off"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script type="text/javascript">
var clubs = [
<?php
foreach($clubs as $club) {
$club_name = $club['club_name'];
echo '"'.$club_name.'",';
}
?>
];
var clublist = <?php echo json_encode($clubs)?>; //only returns one row
$(".club-name").autocomplete({
source: clubs,
autoFocus: true,
minLength: 2,
delay: 0,
close: function(event, ui){
if (!event.keyCode || event.keyCode === 13){
$(this).parents('form').find('.club-name').filter(function (){
return $(this).val() === '';
}).first().focus();
//
}
clubid = "";
for(var i = 0; i < clublist.length; i++) {
obj = clublist[i];
if(obj.club_name == $("#clubname").val()){
clubid = obj.club_id;
$("#team-logo").attr("src", clubid+".png");
}
}
if(clubid == "") {
// show default image
$("#team-logo").attr("src", "0.png");
}
}
});
</script>

Related

Postgresql database with web access- code correctly updates database but web page takes very long time to reload

I have a postgresql database for a hypothetical zoo. I am creating web access for my database using php and some javascript. I have successfully gotten the majority of the web pages to work, but am now working on a page that allows the client to add and remove animals from current exhibits. I have a dropdown that is populated with the exhibit names from the database, the second dropdown is populated from the database with animal names and their IDs that are assigned to the current exhibit selected(exhibit_id is foreign key in animal table referencing exhibit_id in exhibit table). This is dynamically changed when the exhibit name is selected. I have a third dropdown that is populated from the database with animal names and their ID that are not assigned to an exhibit. This all works upon initial loading of the page. Upon clicking the add or remove button my database is updated correctly, but the page just keeps loading. I was expecting it to give the success message and then the client could pick another exhibit and it would show the updates, but it doesn't get there. I've been teaching myself HTML, PHP, and JS so the code is pretty sloppy. I'm using some mix of examples I found on the web to get the dynamic dropdowns and ability to select multiple options from the dropdown lists so this is probably where the issue lies since I can exit the page and go back and then it will have the dropdowns with the values they should have. I would appreciate any help on why this is happening and if there are any fixes. Thanks!
<?php
//Read database info from file and assgin to variables
$myfile = fopen("../pg_connection_info.txt", "r") or die("Unable to open \"../pg_connection_info.txt\" file!");
$my_host = fgets($myfile);
$my_dbname = fgets($myfile);
$my_user = fgets($myfile);
$my_password = fgets($myfile);
fclose($myfile);
// Make a connection to the database
$dbhost = pg_connect("host=$my_host dbname=$my_dbname user=$my_user password=$my_password");
// If the $dbhost variable is not defined, there was an error
if(!$dbhost)
{
die("Error: ".pg_last_error());
}
//Get exhibits from database
$query = "SELECT exhibit_id, name FROM exhibit";
$result = pg_query($dbhost, $query);
while($row = pg_fetch_row($result))
{
$categories[] = array("id" => $row[0], "val" => $row[1]);
}
//Get animals assigned to exhibits
$query2 = "SELECT animal_id, exhibit_id, name FROM animal";
$result2 = pg_query($dbhost, $query2);
while($row = pg_fetch_row($result2))
{
$subcats[$row[1]][] = array("id" => $row[0], "val" => $row[2]);
}
$jsonCats = json_encode($categories);
$jsonSubCats = json_encode($subcats);
?>
<html lang="en-us">
<head>
<title>Manage Animals/Exhibits</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type='text/javascript'>
<?php
echo "var categories = $jsonCats; \n";
echo "var subcats = $jsonSubCats; \n";
?>
//exhibit dropdown options
function loadCategories(){
var select = document.getElementById("exhibit");
select.onchange = updateSubCats;
var j = 0;
select.options[0] = new Option("--Select an option--");
for(var i = 0; i < categories.length; i++){
select.options[j + 1] = new Option(categories[i].val,categories[i].id);
j++;
}
}
//animals assigned to exhibits dropdown options
function updateSubCats(){
var catSelect = this;
var catid = this.value;
var subcatSelect = document.getElementById("animal");
subcatSelect.options.length = 0; //delete all options if any present
for(var i = 0; i < subcats[catid].length; i++){
subcatSelect.options[i] = new Option(subcats[catid][i].val + " - " + subcats[catid][i].id ,subcats[catid][i].id);
}
}
//Allows multiple selecting of dropdown items
window.onmousedown = function(e)
{
var el = e.target;
if(el.tagName.toLowerCase() == 'option' && el.parentNode.hasAttribute('multiple'))
{
e.preventDefault();
if(el.hasAttribute('selected')) el.removeAttribute('selected');
else el.setAttribute('selected', '');
}
}
</script>
</head>
<body onload='loadCategories()'>
<h1>Add and Remove Animals from Exhibits</h1>
<form action="Manage_Animal_Exhibit.php" method="post">
<p>Select an exhibit to add or remove animal(s) from</p>
</select>
Exhibit: <select name="exhibit" id="exhibit">
</select><br><br>
<p>Current animals in exhibit:</p>
<select name="animal[]" id='animal' multiple>
</select><br><br>
<input type="submit" name="Remove" value="Remove"/><br><br>
<p>Current animals not assigned to an exhibit:</p>
<select name="animalAvail[]" id='animalAvail' multiple>
<?php
//get animals not in exhibit
$query3 = "SELECT name, animal_id FROM animal WHERE exhibit_id is NULL";
$result3 = pg_query($dbhost, $query3);
while($row = pg_fetch_row($result3)){
$name = $row[0];
$id = $row[1];
//Display animal's name and id in dropwdown. Assign id to the option so no need for an associative array
echo "<option value='$id'>$name - $id </option>";
}
?>
</select><br><br>
<input type="submit" name="Add" value="Add"/><br><br>
</form>
<!--Exits the Manage_Animal_Exhibit page and returns to the Home Page-->
<form action="Home_Page.php" method="post">
<input type="submit" name="Exit" value="Exit"/>
</form>
<?php
//When add button is pressed assign animals to exhibit
if(isset($_POST["Add"]))
{
//If exhibit isn't selected display message
if($_POST["exhibit"] == "--Select an option--")
{
echo "<script type='text/javascript'>alert('Select an exhibit')</script>";
}
else
{
$arr = array();
//Get each animal selected from dropdown and add their ID to an array
foreach($_POST["animalAvail"] as $animalID)
{
array_push($arr, "$animalID");
}
//Get id of exhibit selected and then add animals to exhibit
$exhibitID = $_POST["exhibit"];
$query4 = "UPDATE Animal SET exhibit_id = $1 WHERE animal_id = $2";
pg_prepare($dbhost, "prepare1", $query4);
for($i = 0; i < count($arr); $i++)
{
$idToUpdate = $arr[$i];
pg_execute($dbhost, "prepare1", array($exhibitID, $idToUpdate));
}
echo "<script type='text/javascript'>alert('The animals were added to the exhibit')</script>";
}
}
if(isset($_POST["Remove"]))
{
//If exhibit isn't selected display message
if($_POST["exhibit"] == "--Select an option--")
{
echo "<script type='text/javascript'>alert('Select an exhibit')</script>";
}
else
{
$arr2 = array();
//Get each animal selected from dropdown and add their ID to an array
foreach($_POST["animal"] as $aID)
{
array_push($arr2, "$aID");
}
$query5 = "UPDATE Animal SET exhibit_id = NULL WHERE animal_id = $1";
pg_prepare($dbhost, "prepare2", $query5);
for($i = 0; i < count($arr2); $i++)
{
$idUpdate = $arr2[$i];
pg_execute($dbhost, "prepare2", array($idUpdate));
}
echo "<script type='text/javascript'>alert('The animals were removed from the exhibit')</script>";
}
}
// Free the result from memory
pg_free_result($result);
// Close the database connection
pg_close($dbhost);
?>
</body>
</html>
I condensed my code and was able to get the web page to load immediately. The issue was within the code for updating the database when the add and also the remove button was pressed. I had an enhanced for loop to get the selected values and add them to an array and then a for loop to update the records in the database. I condensed it to just one enhanced for loop that would get the values selected and also update the database. Here is an example of what I did for the add. The remove is the same format.
//When add button is pressed assign animals to exhibit
if(isset($_POST["Add"]))
{
//If exhibit isn't selected display message
if($_POST["exhibit"] == "--Select an option--")
{
echo "<script type='text/javascript'>alert('Select an exhibit')</script>";
}
else
{
//Get id of exhibit selected and then add animals to exhibit
$exhibitID = $_POST["exhibit"];
$query4 = "UPDATE Animal SET exhibit_id = $1 WHERE animal_id = $2";
pg_prepare($dbhost, "prepare1", $query4);
foreach($_POST["animalAvail"] as $animalID)
{
pg_execute($dbhost, "prepare1", array($exhibitID, $animalID));
}
echo "<script type='text/javascript'>alert('The animals were added to the exhibit'
</script>";
}
}

Show the count of Displayed results

we are using below code to filter rows based on selected From & To date.
we can able to filter successfully & displaying results.
php
/* to show selected date */
if (isset($_POST['post_at']) && $_POST['post_at'] != '')
{
$orderFromDate = $_POST['post_at'] . " 00:00:00 ";
}
else
{
$orderFromDate = '';
}
if (isset($_POST['post_at_to_date']) && $_POST['post_at_to_date'] != '')
{
$orderToDate = $_POST['post_at_to_date'] . " 23:59:59 ";
}
else
{
$orderToDate = '';
}
/* to show selected date end*/
function getDesignerCollection()
{
/* date search */
if (isset($_POST['post_at']) && $_POST['post_at'] != '')
{
$orderFromDate = $_POST['post_at'] . " 00:00:00 ";
}
else
{
$orderFromDate = '';
}
if (isset($_POST['post_at_to_date']) && $_POST['post_at_to_date'] != '')
{
$orderToDate = $_POST['post_at_to_date'] . " 23:59:59 ";
}
else
{
$orderToDate = '';
}
/* date search end*/
$accountType = $rows['type'];
if ($accountType == "admin")
{
if ($orderFromDate != '') $order->addFieldToFilter('created_at', array(
'gteq' => $orderFromDate
));
if ($orderToDate != '') $order->addFieldToFilter('created_at', array(
'lteq' => $orderToDate
));
}
form
<form name="frmSearch" method="post" action="">
<input type="text" placeholder="From Date" id="post_at"
value="<?php
if ($orderFromDate != '')
{
$newPostStartDate = date('Y-m-d', strtotime($_POST['post_at']));
echo $newPostStartDate;
} ?>" name="post_at" />
<input type="text" placeholder="To Date" id="post_at_to_date"
value="<?php
if ($orderToDate != '')
{
$newPostEndDate = date('Y-m-d', strtotime($_POST['post_at_to_date']));
echo $newPostEndDate;
} ?>"name="post_at_to_date" />
<input type="submit" name="search" value="search" id="searchButton">
<input type="button" value="Reset" id="clear-dates">
</form>
jquery
jQuery.datepicker.setDefaults({
showOn: "button",
buttonImage: "assets/img/datepicker.png",
buttonText: "Date Picker",
buttonImageOnly: true,
dateFormat: 'yy-mm-dd'
});
$(function() {
$("#post_at").datepicker();
$("#post_at_to_date").datepicker();
});
now we want to display how many rows are selected. if result is as above image we want to display "rows : 1". i am very new to php & i tried below code , but its not displaying anything:
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if ($result = mysqli_query($link, "SELECT entity_id , created_at FROM sales_flat_order ORDER BY Name")) {
/* determine number of rows result set */
$row_cnt = mysqli_num_rows($result);
printf("Result set has %d rows.\n", $row_cnt);
/* close result set */
mysqli_free_result($result);
}
edit
now we want to display count of how many rows are displayed. so we tried below code. its displaying like below image. its displaying "rows = 3". because its considering "entity_id" column of "sales_flat_order" table. but i want "rows : 9" as you can see 9 rows in image.
require_once '../../app/Mage.php';
Mage::app();
// specify the date picker date-format
$format = 'Y-m-d';
// if posted data are not empty
if(!empty($_POST['post_at']) && !empty($_POST['post_at_to_date']))
{
if (!empty($_POST['post_at'])) {
$dateFrom = DateTime::createFromFormat($format, $_POST['post_at']);
}
if (!empty($_POST['post_at_to_date'])) {
$dateTo = DateTime::createFromFormat($format, $_POST['post_at_to_date']);
}
// Get the resource model
$resource = Mage::getSingleton('core/resource');
// Retrieve the read connection
$read = $resource->getConnection('core_read');
// MySQL query
$query = 'SELECT entity_id, created_at, dproduct_id FROM sales_flat_order WHERE created_at BETWEEN :fromdate AND :todate ;';
// Bind MySQL parameters
$binds = array(
'fromdate' => $dateFrom->format('Y-m-d H:i:s'),
'todate' => $dateTo->format('Y-m-d H:i:s')
);
// Execute the query and store the results in $results
$results = $read->fetchAll($query,$binds);
echo "rows : ".count($results);
echo "<br>";
print_r($results);
}
else {
echo "error you have not specified any dates";
}
complete code : http://pastebin.com/hMUEusvb
You can count the selected id from your mysqli query itsel.. Try this in your mysqli query
if ($result = mysqli_query($link, "SELECT count(entity_id) as Total_count,entity_id , created_at FROM sales_flat_order ORDER BY Name")) {
// Your process
}
You can count number of rows by using js. Add following code at the end of your code. Replace selector1 with class name which is used only for rows. Inspect your page in browser and find a class which is present only in rows and used once at a time in a row.
Then replace selector2 with class or id where you want to display number of rows.
<script>
$(document).ready(function () {
var count = 0;
//use class unique in each row.
$("selector1").each(function () {
count++;
});
//use class or id where you want to display count
$("selector2").prepend("Number of rows "+count);
});
If you want to handle it done through PHP. Please paste the code where it renders the search result.
Your current code is not working because your code send response back on line 293 of file http://pastebin.com/QKMj0k2p
You can find that in network tab of browser and see on search submit where it send request and what comes in response from there. If you can find where it is sending response back it will be easy to know which code is rendering rows. It will be more help full to solve your problem.
I think you have an error which is not present in your question. If you only want to fix this Issue. You can use JavaScript. You only have to know the exact selector.
$(document).ready( function (){
//your selector would direct li or td if there is no other li td then it works other wise you have select parent then li or td like below comment
//$(".class li").length
var count = $("li").length;
$("yourCounter").html(count);
} );
your PHP code should be like this
// if posted data are not empty
if(!empty($_POST['post_at']) && !empty($_POST['post_at_to_date'])) {
// specify the date picker date-format
$format = 'Y-m-d';
// create dates
$dateFrom = DateTime::createFromFormat($format, $_POST['post_at']);
$dateTo = DateTime::createFromFormat($format, $_POST['post_at_to_date']);
// if equal dates are applied to form
if($_POST['post_at']==$_POST['post_at_to_date']) {
$dateTo->add(new DateInterval('T23H59M59S'));
}
// Get the resource model
$resource = Mage::getSingleton('core/resource');
// Retrieve the read connection
$read = $resource->getConnection('core_read');
// MySQL query
$query = 'SELECT `entity_id`, `created_at` FROM `sales_flat_order` WHERE `created_at` BETWEEN :fromdate AND :todate ;';
// Bind MySQL parameters
$binds = array(
'fromdate' => $dateFrom->format('Y-m-d H:i:s'),
'todate' => $dateTo->format('Y-m-d H:i:s')
);
// Execute the query and store the results in $results
$results = $read->fetchAll($query,$binds);
echo "Orders count: ".count($results);
} else {
echo "error you have not specified any dates";
}

Get the value of the click number in order to update the clicked data

we have a form that we can click on a number at the top of the form in order to load the according data, to be more specific i can have 4 inputs in my table in the database and when I click on number 2 which is the id of the data then it loads the data. We did that but now we want to update the clicked data and until now we cant find a way to GET the correct number(id) and place it in the UPDATE statement.
Below is the code of the clicked functions and of the UPDATE statement.
//Education Scripts
$("#updateEdu").click(function () {
$("#idE").css("display", "none");
var r = parseInt($("#idE").val(), 10) + 1;
$("#idE").val(r);
});
$('[data-row-ide]').click(function (e) {
e.preventDefault();
var fileName = 'addCV.php?idEdu='; //"addCV.php" the name of this file in your project, the "?" starts the GET parameters, idWork= sets the key for the GET parameter
var id = $(this).data('row-ide'); // this gets the id that we stored in the link's data attribute
var url = fileName + id; // then we add that id as the value for the "idWork" key
window.location = url; // esentially refresh this page with the id set as a GET parameter and make use of the logic we already have to load the info
});
<?php
$username = $_SESSION["username"];
if(isset($_POST['updateEdu'])){
$parts = parse_url($url);
parse_str($parts['query'], $query);
$id = $query['idEdu'];
$username = $_SESSION['username'];
$school = mysql_real_escape_string($_POST["school"]);
$degree = mysql_real_escape_string($_POST["degree"]);
$website = mysql_real_escape_string($_POST["website"]);
$start_date = mysql_real_escape_string($_POST["start_date"]);
$end_date = mysql_real_escape_string($_POST["end_date"]);
$start_year = mysql_real_escape_string($_POST["start_year"]);
$end_year = mysql_real_escape_string($_POST["end_year"]);
$degree_description = mysql_real_escape_string($_POST["degree_description"]);
if($start_year > $end_year){
echo 'The Start Year must be smaller than the End Year!';
$id=$id-1;
$good = false;
}
else{
$good = true;
}
if($good == true){
$query="UPDATE education
SET school = '$school', degree = '$degree', website = '$website', start_date='$start_date', end_date='$end_date', start_year='$start_year', end_year='$end_year', degree_description='$degree_description'
WHERE id='$id' AND username='$username'";
mysql_query($query)or die(mysql_error());
if(mysql_affected_rows()>0){
echo "<p>Record Updated<p>";
echo "<script type='text/javascript'>;
/window.location='addCV.php';
</script>";
}
else{
echo "<p>Error Updating Record<p>";
echo "<script type='text/javascript'>;
</script>";
}
}
}
else if(isset($_GET['idEdu'])){
// user clicked on one of oue id links to get here
// set the id the the value of the GET parameter for key "idWork"
$id = $_GET['idEdu'];
}
else{
// Formulate Query
// This is the best way to perform an SQL query
// For more examples, see mysql_real_escape_string()
$query = sprintf("SELECT school,degree,website,start_date,end_date,start_year,end_year,degree_description,id FROM education
WHERE username='%s' ORDER BY id LIMIT 1",
mysql_real_escape_string($username));
// Perform Query
$result = mysql_query($query);
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
// Use result
// Attempting to print $result won't allow access to information in the resource
// One of the mysql result functions must be used
// See also mysql_result(), mysql_fetch_array(), mysql_fetch_row(), etc.
while ($row = mysql_fetch_assoc($result)) {
$id = $row['id'];
}
}
To get the value of an elements attribute in jquery you use the attr() function like so:
$(element).attr('attributeName')
So you should change:
var id = $(this).data('row-ide');
into
var id = $(this).attr('row-ide');
in your function $('[data-row-ide]').click(function (e) {};

Array of drop down list in html

How to change the value of dropdown dinamically.
here the case:
for example i have an array of dropdown and has 2 names on it, like name1 and name2,
the name 1 has grade and also the name2.
what i want to do is change the first dropdown which has the value of name and
i want the second dropdown change automatically according to his grade.
Like:
John -> 90
Paul -> 80
please help me to find the index of array and the selected value of dropdown using javascript. thanks in advance.
<script>
function Change2(a){
var options1= document.getElementById('stuname[]').options;
var options2= document.getElementById('stugrade[]').options;
for(i = 0; options1.length;i++){
if(options1[i].selected == true){
options2[i].selected = true;
}
}
} // what I want is, if I change the first dropdown in row 1, the 2nd dropdown should change too, and same in row 2.
</script>
<?php
$getlist= mysql_query("SELECT * FROM STUDENTS");
while($row = mysql_fetch_assoc($getlist)){
print "<select id = 'stuname[]' name = 'stuname[]' class = 'text4' onchange = 'Change2(this.value);'>";
$getname = mysql_query("SELECT * FROM NAME");
while($row = mysql_fetch_assoc($getname)){
$name = $row['name'];
print "<option value = '$name'>$name</option>";
}
print "</select>";
print"<select id = 'stugrade[]' name = 'stugrade[]' onchange = 'Change2(this.value);'>";?>
<?php
$getgrade = mysql_query("SELECT * FROM GRADE");
while($row = mysql_fetch_assoc($getgrade)){
$grade = $row['grade'];
print "<option value = '$grade'>$grade</option>";
}
print "</select><br>";
}
?> // heres my code.. edited
This is a common approach to solve this kind of issues, differently you need change querys and names accordingly
JS file
$(document).ready(function(){
getfirstSelect();
})
function getSecondSelect() {
var firstDropDownSelectedID = $('#firstSelect option:selected').val();
$.ajax({
type: "POST",
url: "getSecondDropDownOptions.php",
data: "firstDropDownSelectedID="+firstDropDownSelectedID
}).done(function (result) {
//alert(result)
$("#secondSeect").html(result);
});
}
function getfirstSelect() {
$.ajax({
type: "POST",
url: "getFirstDropDownOptions.php",
data: {}
}).done(function (result) {
//alert(result)
$("#secondSeect").html(result);
});
}
getSecondDropDownOptions.php
<?
$firstDropDownSelectedID = isset($_POST['firstDropDownSelectedID']) ? (int)$_POST['firstDropDownSelectedID'] : 0;
$list2 = mysql_query("SELECT * FROM LIST2 WHERE relatedid=".$firstDropDownSelectedID);
$returnString = "";
while($row = mysql_fetch_assoc($list2)){
$returnString.= "<option value = '".$row['grade']."' >".$row['grade']."</option>";
}
print $returnString;
?>
getFirstDropDownOptions.php
<?
$list1 = mysql_query("SELECT * FROM LIST1 ");
$returnString = "";
while($row = mysql_fetch_assoc($list1)){
$returnString.= "<option value = '".$row['grade']."' >".$row['grade']."</option>";
}
print $returnString;
?>
HTML
<form name="formName">
<select name="firstSelect" id="firstSelect" onchange="updateSecondSelect()"></select>
<select name="secondSeect id="secondSeect" ></select>
</form>

Changing PHP function to Javascript/AJAX validation

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.

Categories