I'm a total noob when it comes to jQuery. This time I would like to populate a select box when a user clicks it. I managed to do that, but each time the user selects an option the select box instantly changes it's value back to default, so the user can't select the one he wants. Below you can view the code from Joomla that loads the database and the HTML file with the select box. I know I'm doing something wrong but I'm not sure what this is...
widget.php - Joomla Database file with query
<?php
// Set flag that this is a parent file.
define('_JEXEC', 1);
define('DS', DIRECTORY_SEPARATOR);
if (file_exists(dirname(__FILE__) . '/defines.php')) {
include_once dirname(__FILE__) . '/defines.php';
}
if (!defined('_JDEFINES')) {
define('JPATH_BASE', dirname(__FILE__));
require_once JPATH_BASE.'/includes/defines.php';
}
require_once JPATH_BASE.'/includes/framework.php';
$db = JFactory::getDbo();
$db2 = JFactory::getDbo();
$sql = "SELECT id, type, name FROM #__widgetkit_widget WHERE type = 'gallery'";
$db->setQuery($sql);
$rows = $db->loadObjectList();
$query = "SELECT id, b_name, w_id FROM #__yachts WHERE id = ".JRequest::getInt('id')."";
$db2->setQuery($query);
$rows2 = $db2->loadObjectList();
$my_yacht = $rows2[0]->w_id;
echo '<option value="">-- Please Select --</option>';
foreach($rows as $row) {
echo '<option value="'.$row->id.'"';
if($row->id == $my_yacht) { echo ' selected'; }
echo '>'.$row->name.'</option>'."\n";
}
?>
And the HTML file with the JavaScript:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html prefix="og: http://ogp.me/ns#" xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-gb" lang="en-gb" dir="ltr" >
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
var j = jQuery.noConflict();
j(document).ready(function () {
j("#jform_w_id").click(function () {
j("#jform_w_id").load('widget.php');
});
});
</script>
</head>
<body>
<select class="" id="jform_w_id" name="jform[w_id]">
<option value="">-- Please Select --</option>
<option value="59">Bavaria 50 Cruiser</option>
<option value="60">Bavaria 49</option>
</select>
</body>
</html>
The problem is that you're reloading the select box from widget.php every time a user clicks on the #jform_w_id select box. Since you aren't first grabbing the previously selected item, the previous selection is lost.
One solution is to store off the previously selected value before loading, then reassign the selection after loading, like so:
<script type="text/javascript">
var j = jQuery.noConflict();
j(document).ready(function () {
var selectBox = j('#jform_w_id');
selectBox.click(function () {
var oldValue = selectBox.val();
selectBox.load('widget.php');
selectBox.val(oldValue);
});
});
</script>
With that said, I'm not convinced this is a good pattern, for a few reasons:
1) You're reloading from the server every time the user clicks that select. If the list is long, you're going to have a noticeable lag between the time the user clicks and the time the select box pops up. Make sure you understand why you are loading the data from the server every time there's a click, and make sure your use case really requires that. You may be able to have a process that caches the values and repopulates the dropdown asynchronously.
2) I haven't tested this, but it's possible that reloading the options box after clicking could cause the control to flicker, lose focus, or other unexpected behavior.
3) If you need to support mobile users, the above issues will be exacerbated by UI and bandwidth constraints.
Since I don't know your particular use case, these may be concerns you've already thought of, but if not, please consider them as you craft your page.
Finally, please consider replacing this line
$query = "SELECT id, b_name, w_id FROM #__yachts WHERE id = ".JRequest::getInt('id')."";
with a prepared statement. While the fact that you're currently parsing an int from the request object protects you from SQL injection attacks for this one use case, you'll glad you used prepared statements if you copy this chunk of code for use elsewhere where the WHERE clause parameter is a string. The semantics of prepared statements will depend on the DB you're using and Joomla's database API, but it's usually something like:
$query = "SELECT id, b_name, w_id FROM #__yachts WHERE id = :id";
$stmt = $dbh->prepare($query);
$stmt->bindParam(':id', JRequest::getInt('id'));
if ($stmt->execute()) {
while ($row = $stmt->fetch()) {
...
}
}
See: http://us1.php.net/pdo.prepared-statements
Related
Code is below.... I have dropdown menu - that is using PHP to query SQL, in order to populate the dropdown menu options, which is working fine.
You will see below - the sql query is statically configured, I would like to make this more dynamic.
Ideally id like another drop down menu on the same page with statically configured country options, and then when the customer selects which country my PHP script updates with the country in the sql query that php is using....
So for example where in my script below it says;
WHERE country ='SE'
I want it to populate with which ever country the user has selected in the pull down menu, so it could be 'FR', 'DE' or whatever country code has been selected.
I suspect this may be javascript? or maybe php can do this...?
I'm very much a novice level - so if you can be of assistance as much detail, or script as possible please :)
<html>
<body>
<form name="search" action="\cgi-bin\eu.py" method="get">
<?php
require_once 'db.inc.php';
$mysqli = new mysqli(DB_HOST,DB_USER,DB_PASS,DB_NAME);
$sqlSelect="SELECT * FROM clnts WHERE country ='SE' ORDER BY clnt_name";
$result = $mysqli -> query ($sqlSelect);
if(mysqli_num_rows($result)){
$select= '<select name="select">';
while($rs=mysqli_fetch_array($result)){
$select.='<option value="'.$rs['mgmt_ip'].'">'.$rs['clnt_name'].'</option>';
}
}
$select.='</select>';
echo $select;
?>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
You can POST the selected dropdown value to the same page. You can do this automatically by using an 'onChange()' event on the dropdown menu.
Use this to POST to the same page and then get the value for the selected option and use that in your query...
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
add this at the top of you PHP....
if(isset($_POST['select']))
{
$selected_country_var = " country = '" . $_POST['select'] . "' ";
}else
{
$selected_country_var = " ";
}
edit your query to ...
$sqlSelect="SELECT * FROM clnts WHERE" . $selected_country_var . " ORDER BY clnt_name";
now edit your option/dropdown to have the onChnange event...
<select name="select" onchange="this.form.submit()">';
Let me know if I should clarify or if you need additional functionality.
It's usually not a "clean" solution to put together both server and client side code on the same page.
It's actually a better practice to put the server code on a seprate file for example 'handler.php' or 'api.php' and then call it using XMLHttpRequest (more commonly known as AJAX) ...
then, when using ajax you can pass data to the server using POST or GET variables and have it process the data.
that way you can create client side which is more fluent, and communication between the server and the client will be more "tidy"
in your case if you have say 'handler.php' on the server and use jquery ajax you could do something like :
client.html
$.ajax({
url : 'path_to_handler.php',
method : 'POST',
data : { countryCode : 'IL', otherVar : 1 },
onSuccess : function(result){
// do whatever with the data
}
});
and on the server
handler.php
if( isset($_POST['contryCode']) ){
// query the db and have the result returned as json
echo json_encode($result_query);
}
I am developing a web app using Laravel 5 and trying to integrate some JS to help out a form. I want users to be able to select a category in one select field, at which point a second select field should populate with options within that category. (E.g., Select a profession: programmer, artist. If 'programmer' is selected, second select field populates with: C++, Java, Python. If 'artist' is selected, second select populates with: Photoshop, Illustrator, MS Paint.)
Note that I need to populate these fields from my database. I've found examples of what I am trying to do on the web that I have tried to adapt to my case. The one I'm using is here: http://www.9lessons.info/2010/08/dynamic-dependent-select-box-using.html but I can't get it to work (it's fairly old--from 2010).
Here's my HTML and JS:
<!-- JS -->
<script type="text/javascript">
$(document).ready(function()
{
$("#field_main").change(function()
{
var id = $(this).val();
var fields="";
$.ajax
({
type: "POST",
url: "ajax_field.php",
data: {id: id},
cache: false,
success: function(data)
{
$.each(data,function(index,field)
{
fields+="<option value='"+field.id+"'>"+field.field+"</option>";
});
$("#field").html(fields);
}
});
});
});
</script>
<!-- Create the first select field, this part of the code works fine -->
<label>Area :</label>
<select name="field_main" id="field_main">
<option selected="selected">--Select Area--</option>
<?php
$areas = App\Area::all();
foreach($areas as $area){
echo "<option value=\"" . $area->id . "\">" . $area->area . "</option>";
}
?>
</select>
<!-- Create the second select field; this part is not working -->
<label>Field :</label>
<select name="field" id="field">
<!--<option selected="selected">--Select Field--</option>-->
</select>
Here's what ajax_field.php looks like:
<?php
namespace App\Http\Controllers;
use DB;
if($_POST['id'])
{
$id = $_POST['id'];
$fields = DB::table('fields')->where('area_ref', $id)->get();
return response()->json(['data' => ['fields' => $fields]]);
}
?>
As far as I can tell, nothing runs from ajax_skill.php. I tried echoing something out in that function, it didn't appear on my page, and the skills field never populates. The profession select field, however, populates fine.
Any thoughts on where this code is going wrong?
You need to return JSON when hitting that URL with AJAX. You don't need the HTML. Return only the skills data with return response()->json(['data' => ['skills' => $skills]]); and add the select element on the page populated with all of the skills.
Oh and, the ajax data property takes an object so it should be: data: {id: id}
Since you are using Laravel, half of your code looks like old school PHP which is useless when Laravel has a cleaner way for these things.
If you are new to PHP and Object Oriented Programming, I'd advice you to learn that before using Laravel. It will help you in the future.
Also, I'd advice you to read up the Laravel documentation, follow the tutorials there and even go to Laracasts and watch the Laravel 5 Fundamentals and Laravel From Scratch series to get up to speed with Laravel.
I have been trying to figure out a way to populate second dropdown from database, based on user's selection in the first dropdown.
So far, CSS Tricks (Dynamic-Dropdowns) this is the best and most clear answer for my question. Although I am not able to make mine work. (There are 3 examples to populate dropdown, you should check the database one, which is on the bottom of the page.)
I have 2 dropdowns in my settings.php and as tutorial showed I created another php file to print out second dropdown.
This is get-dropdown.php:
<script>alert("Here")</script>
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
$dbConnection = open_connection();
if(isset($_GET['School'])){ $school = mysqli_real_escape_string($dbConnection, $_GET['School']); }
/* This code will print program options from database.
*
* If user's program matches with any of the school from database,
* mark it as "selected" otherwise, use "Select Your Program" as selected.
*
* So, "selected" attribute of user's program will overwrite the "selected"
* attribute of "Select Your Program".
* */
$query_programs = "SELECT * FROM PROGRAMS WHERE PROGRAM_SCHOOL='$school' ORDER BY PROGRAM_CODE ASC";
$query_users = "SELECT USER_PROGRAM FROM USERS WHERE USER_ID = $user1_id";
$programs_result = mysqli_query($dbConnection, $query_programs) or die(mysqli_error($dbConnection));
$users_result = mysqli_query($dbConnection, $query_users) or die(mysqli_error($dbConnection));
while($data = mysqli_fetch_assoc($users_result)){ $user_program = $data['USER_PROGRAM']; }
foreach($programs_result as $program_result){
if($user_program == $program_result['PROGRAM_CODE']){
echo "<option value='$program_result[PROGRAM_CODE]' selected>$program_result[PROGRAM_CODE]</option>";
}else{
echo "<option value='$program_result[PROGRAM_CODE]'>$program_result[PROGRAM_CODE]</option>";
}
}
close_connection($dbConnection);
Even the alert on the top doesn't work. I putted there to see if it goes this page. When I selected another option from first dropdown, second dropdown gets empty. Nothing appears inside. Looks like I am making a mistake in settings.php because alert doesn't work on top.
This is some part of my settings.php:
<label>
<span>School:</span>
<select class="settings-input" name="school" id="school">
<option value="Select Your School" disabled selected>Select Your School</option>
<?php
/* This code will print school options from database.
*
* If user's school matches with any of the school from database,
* mark it as "selected" otherwise, use "Select Your School" as selected.
*
* So, "selected" attribute of user's school will overwrite the "selected"
* attribute of "Select Your School".
* */
$query_schools = "SELECT * FROM SCHOOLS ORDER BY SCHOOL_TYPE ASC";
$query_users = "SELECT USER_SCHOOL FROM USERS WHERE USER_ID = $user1_id";
$schools_result = mysqli_query($dbConnection, $query_schools);
$users_result = mysqli_query($dbConnection, $query_users);
while($data = mysqli_fetch_assoc($users_result)){ $user_school = $data['USER_SCHOOL']; }
foreach($schools_result as $school_result){
if($user_school == $school_result['SCHOOL_NAME']){
echo "<option value='$school_result[SCHOOL_NAME]' selected>$school_result[SCHOOL_NAME]</option>";
}else{
echo "<option value='$school_result[SCHOOL_NAME]'>$school_result[SCHOOL_NAME]</option>";
}
}
?>
<option value="Other">Other</option>
</select>
</label>
<label>
<span>Program:</span>
<select class="settings-input" name="program" id="program">
<option value="Select Your Program" disabled selected>Select Your Program</option>
<script>
$("#school").change(function(){
$("#program").load("./lib/get-dropdown.php?school=" + $("#school").val());
});
</script>
</select>
</label>
Thank you very much.
FINALLY FIXED (MY SOLUTION)
1. I have $dbConnection = open_connection(); to connect database but this function is defined in another file and the necessary information to connect database is stored in another file. So, to my get-dropdown.php I had to require both files. So this is how I fixed the db connection.
2. Other problem is I pass the school name to get-dropdown.php but the problem is school names contain spaces and this is a problem when you tried to pass in get. So this is what I used to pass get value. I added encodeURIComponent.
<script>
$(document).ready(function(){
$("#school").change(function(){
$("#program").load("lib/get-dropdown.php?School=" + encodeURIComponent($("#school").val()));
});
});
</script>
These were the problems. If you are trying to populate dropdown and no idea about javascript, this is the most easy way. With a little bit jquery, you can achieve it.
FINALLY FIXED (MY SOLUTION)
1. I have $dbConnection = open_connection(); to connect database but this function is defined in another file and the necessary information to connect database is stored in another file. So, to my get-dropdown.php I had to require both files. So this is how I fixed the db connection.
2. Other problem is I pass the school name to get-dropdown.php but the problem is school names contain spaces and this is a problem when you tried to pass in get. So this is what I used to pass get value. I added encodeURIComponent.
<script>
$(document).ready(function(){
$("#school").change(function(){
$("#program").load("lib/get-dropdown.php?School=" + encodeURIComponent($("#school").val()));
});
});
</script>
These were the problems. If you are trying to populate dropdown and no idea about javascript, this is the most easy way. With a little bit jquery, you can achieve it.
Thanks for taking the time to look at this post.
So I have managed to do my task to a point.
I am pulling data from a database called posts with the following fields: id, account_name, data, heading, subheading, videos, voice_notes, music, images, post_date, date_for_post.
So This is the process:
1 - Pull data from db and put into array
2 - Make unordered list from array with links
3 - when link is clicked, fill content div with that posts data.
Now it will load the specific posts data on odd numbered links, but on even numbered links it wont load the data into the container? using the same method? I have re-ordered the lists and still, even numbered list items just wont work. Am I doing something wrong?
I have also tried putting in a blank list item in between the posts to see if it were the list items themselves that were not calling the function, but it seems that it is only the even links.
I don't know how else to explain it, here is my code:
<?php
$connection=mysql_connect('localhost', 'username', 'password');
if (!$connection) { die('Not connected : ' . mysql_error());}
// Set the active MySQL database
$db_selected = mysql_select_db('dbname', $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
$query = "SELECT * FROM posts";
$result = mysql_query($query);
if(!$result){
die('Invalid query' . mysql_error());
}
$posts = array();
while($line = mysql_fetch_array($result, MYSQL_ASSOC)){
$posts[] = $line;
}
?>
<!doctype html>
<html>
<head>
<script type="text/javascript" src="js/ajax.js"></script>
<script type="text/javascript" src="js/content.js"></script>
</head>
<body>
<div id="content">some data</div>
<div id="links">
<ul>
<?php
foreach ($posts as $post) {
$data = "'".$post['data']."'";
echo '<li>'. $post['date_for_post'] .'</li>';
}
?>
</ul>
</div>
</body>
and the getContent function:
function getContent(element, data){
$(element).text(data);
}
I cannot figure out why. here is a graphical representation of whats happening:
I have tried inserting black list items to see if it was the actual even list items not calling the function, but it is the even list items with the content inside that wont work, if that makes sense?
Please help as I have no clue what is going on and how to fix it.
Thanks in advance!
UPDATE
it seems to be that the longer posts dont display, the shorter do. I have the data type in the database set to text, not varchar. So where is the issue with size? Is there a maximum size I am allowed to put through the JQuery function? Or in the database? Because it shows in the database, but not on the post
I think the problem is with quotes and double quotes here in your code:
$data = "'".$post['data']."'";
echo '<li>'.$post['date_for_post'] .'</li>';
Check the source of generated HTML page. There should be incorrect 'li' tags. I suggest change your code to this:
$data = $post['data'];
echo '<li>'.$post['date_for_post'] .'</li>';
Hope it helps.
Also, check if the quotes in text from database are causing this problem.
It's hard to see what's going on, try to provide a jsfiddle. Even though you are using php, you can create a manual feed of json data and test out the javascript. To make it less confusing, have the data stored in a ...
<script>
$(document).ready(function () {
var dbObj = <?php $post ?> // $post object to be formatted in json
var render;
for (obj in dbObj) {
render = render + '<li><a href="#" onclick=getContent("#content", ' + obj.data + '");>' +obj.date+ '</a></li>'
$('#links ul').append(render);
});
</script>
If that works and you really want to have the php print out the list, then you can replace it with the php foreach; these days, developers are allowing the client-side to render templates/html and at least you'll know the js works this way! :-)
<?php
foreach ($posts as $post) {
echo '<li><a href="#" onclick=getContent("#content", "'. $post["data"] .'");>'. $post['date_for_post'] .'</a></li>';
}
?>
I have two dropdown menus that read their data from a MySQL database. I use PHP for connecting to database. The second dropdowns should get populated based on the selection on the first dropdown. The process seems as below to me (correct me if I'm wrong):
PHP section connects to MySQL database and populates dropdown1.
user selects a value on dropdown1 and onchange event is called.
within the onchange function (which is Javascript), a query is sent to MySQL database to fetch values of dropdown2 based on the dropdown1 selection (here is PHP again, right?).
dropdown2 gets populated.
I don't know how to use Javascript and PHP together in order to do this task (number 3 above); or maybe this is not the way to do it at all. Please advise!
Here is my code. As you see below, I'm putting a Javascript function within a PHP code which I suppose is wrong. That's where I got stuck!
<php
$sql="SELECT distinct category FROM table1";
$result=mysql_query($sql);
$optionsCat="";
while($row = mysql_fetch_row($result)){
$optionsCat.="<option value=\"$row[0]\">$row[0]</option>";
}
function genSubCat($catID){
$sql="SELECT distinct subcategory FROM table1 where category=".$catID;
$result=mysql_query($sql);
$optionsSubCat="";
while($row = mysql_fetch_row($result)){
$optionsSubCat.="<option value=\"$row[0]\">$row[0]</option>";
}
}
?>
<select name="catDropDown" onChange="genSubCat(this)">
<option value="0">Select category</option>
<?php echo $optionsCat?>
</select>
<select name="subcategoryDropDown">
<option value="0">Select subcategory</option>
<?php echo $optionsSubCat?>
</select>
Here we have a simple page with input on it. Type a word into it and then click off of the input. Ajax will call the myphp.php script and return the same word you typed in below the original division.
test.html:
<!DOCTYPE html>
<html lang="en">
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#faq_search_input").blur(function(){
var faq_search_input = $(this).val();
var dataString = 'keyword='+ faq_search_input;
if(faq_search_input.length>1){
$.ajax({type: "GET", url: "myphp.php", data: dataString,
success: function(server_response) {
document.getElementById("searchresultdata").style.display = "block";
$('#searchresultdata').html(server_response).show();
}
});
}
return false;
});
});
</script>
</head>
<body>
<div class="searchholder">
<input name="query" class="quicksearch" type="text" id="faq_search_input" />
<div id="searchresultdata" class="searchresults" style="display:none;"> </div>
</div>
</body>
</html>
myphp.php:
<?PHP
echo $_GET['keyword'];
?>
I think you should first study yourself about using web based languages. The code that you've provided is completely wrong. You're trying to access PHP code through HTML? I mean come on!
First rule: Server based languages can't communicate with Client based languages.
You have to send requests and get responses and the way you want to do that dropdown thing is to send a request to a PHP code and get relevant data from it. As Trufa said in the comment, you may want to look at jQuery library, but before that I think you need to check AJAX.