Dropdown onchange method using PHP and Javascript - javascript

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.

Related

Creating 3 option dynamic dependant dropdown list

I have a small project I'd like to get done concerning the use of a MySQL Database.
I want to create a two option dropdown menu. Each of these will contain a list of all the countries in the world, but based on the combination of options they select, they will be sent to a different page on our website.
Since the number of possibilities is going to be so large (200 x 200 countries = 40,000 potential answers) we decided it would be best to seed a MySQL database with all this information and then have simple code on our website which would pull them to the right place depending on the option they picked. Unfortunately none of us here have any experience with something like this, so we are looking for someone who can help us to:
1) Create the HTML and Javascript that will sit on our website
2) Establish the connection from the MySQL Database to our website to be able to pull in the values
3) Make the values selected point to the URLs we choose
Could anyone point me in the right direction as to how to do this?
Thanks!
You can use this code for the dependent dropdown. In fact, you don't need to do more simply on change event you need to get a value of selected drop-down and make an ajax call on the database in return data from your database on bases of that value then you can append data on success in another dropdown and can continue this process for more dependent dropdown.
<?php
require_once('db.php');
$country_result = $conn->query('select * from countries');
?>
<select name="country" id="countries-list">
<option value="">Select Country</option>
<?php
if ($country_result->num_rows > 0) {
// output data of each row
while($row = $country_result->fetch_assoc()) {
?>
<option value="<?php echo $row["id"]; ?>"><?php echo $row["country_name"]; ?></option>
<?php
}
}
?>
</select>
</br></br></br>
<select name="state" id="states-list">
<option value=''>Select State</option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js">
$('#countries-list').on('change', function(){
var country_id = this.value;
$.ajax({
type: "POST",
url: "get_states.php",
data:'country_id='+country_id,
success: function(result){
$("#states-list").html(result);
}
});
});
</script>

transferring data between my HTML page and python script

I have a very simple HTML page for testing which has a simple dropdown menu:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<select id="mySelect" onchange="copy();">
<option value="">Select a person:</option>
<option value="Value of m1" >m1</option>
<option value="Value of m2" >m2</option>
<option value="Value of m3" >m3</option>
<option value="Value of m4" >m4</option>
</select>
<br>
<br>
<p>The value of your selected choice is: </p>
<div id="label"></div>
function copy()
{
var selected_value = document.getElementById("mySelect").value
document.getElementById("label").innerHTML = selected_value
}
</script>
</body>
</html>
Now I want to transfer the value of the selection into my python script. My python script has a function which uses the passed value as an argument to give a JSON file. I want to pass the value and then run the script to produce my JSON file when I select something. This is just for testing but my final HTML page will have multiple dropdowns similar to this one each one transferring a value to my python which would be used as an argument. Everything is done locally using local host. Any help would be appreciated!
Its a bit tricky.
You have to use a form to send the data to a PHP-Web Server.
Then use shell_exec($command) to run your Python Script with parameters.
Your PHP Script should look like this:
<?php
$input = $_GET['mySelect'];
//sanitize and check the input
$cmd = escapeshellcmd('/usr/custom/test.py -p ' . $input);
//escape the command
$output = shell_exec($cmd);
//run the script
echo $output;
?>
It's very important to sanitize and check your user input otherwise an attacker could easily get acces to your server.
See more: http://php.net/manual/en/function.shell-exec.php
Notes from php.net
This function can return NULL both when an error occurs or the program produces >no output. It is not possible to detect execution failures using this function. >exec() should be used when access to the program exit code is required."
This function is disabled when PHP is running in safe mode.

Dynamic form PHP / Javascript

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);
}

Dynamic Select Field that Repopulates after Changes in Another Select Field - Laravel 5.2 and JS

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.

get data from mysql database to use in javascript

I have a javascript that dynamically builds an html page. In the html page there are textarea boxes for the user to type information in. The information already exists in a database. I would like to populate the textarea boxes with the database in the mysql database.
I have php code that will connect to the database and build an html table with the data, so I know how to do this with php, but I don't know how to do this from the javascrip. I've studied ajax get requests, etc., but I'm still not sure of how to do this.
Probably the easiest way to do it is to have a php file return JSON. So let's say you have a file query.php,
$result = mysql_query("SELECT field_name, field_value
FROM the_table");
$to_encode = array();
while($row = mysql_fetch_assoc($result)) {
$to_encode[] = $row;
}
echo json_encode($to_encode);
If you're constrained to using document.write (as you note in the comments below) then give your fields an id attribute like so: <input type="text" id="field1" />. You can reference that field with this jQuery: $("#field1").val().
Here's a complete example with the HTML. If we're assuming your fields are called field1 and field2, then
<!DOCTYPE html>
<html>
<head>
<title>That's about it</title>
</head>
<body>
<form>
<input type="text" id="field1" />
<input type="text" id="field2" />
</form>
</body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>
$.getJSON('data.php', function(data) {
$.each(data, function(fieldName, fieldValue) {
$("#" + fieldName).val(fieldValue);
});
});
</script>
</html>
That's insertion after the HTML has been constructed, which might be easiest. If you mean to populate data while you're dynamically constructing the HTML, then you'd still want the PHP file to return JSON, you would just add it directly into the value attribute.
To do with javascript you could do something like this:
<script type="Text/javascript">
var text = <?= $text_from_db; ?>
</script>
Then you can use whatever you want in your javascript to put the text var into the textbox.
Do you really need to "build" it from javascript or can you simply return the built HTML from PHP and insert it into the DOM?
Send AJAX request to php script
PHP script processes request and builds table
PHP script sends response back to JS in form of encoded HTML
JS takes response and inserts it into the DOM
You can't do it with only Javascript. You'll need some server-side code (PHP, in your case) that serves as a proxy between the DB and the client-side code.

Categories