Problems with dynamic dropdown lists using JQuery and PHP - javascript

On my path of slowly learning PHP I've decided to work on a dynamic drop down box to create a little find-a-product application for the small company I work for. I took a day to read examples others have put out of their dynamic drop down boxes and decided the method posted on CSS-Tricks was clean and efficient enough.
The problem I'm having is that the Javascript I'm using doesn't seem to be parsing and returning what I want it to. The MySQL query its supposed to build works as expected when I query my database directly (through Heidi) as well as when I load the script directly (explained at the bottom), but using JQuery to pass options through the script doesn't seem to work.
This is the main page with dropdown I'm using to test/build the script
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$("#type").change(function() {
$("#range").load("dynoptions.php?type=" + $("#type").val());
}).trigger("change");
</script>
</head>
<body>
<select id="type">
<option selected value="base">Please Select</option>
<option value="FM800">FM800</option>
<option value="FS100">FS100</option>
</select>
<br>
<select id="range">
<option>Please choose from above</option>
</select>
</body>
When the state of my first dropdown changes the javascript should be sending information to my PHP and receiving html to inject into the second dropdown.
And this is the PHP:
<?php
//creates DB connection
$dbHost = 'localhost';
$dbUser = 'foxmeter';
$dbPass = 'foxmeter';
$dbDatabase = 'foxmeter';
$con = mysql_connect($dbHost, $dbUser, $dbPass) or trigger_error("Failed to connect to MySQL Server. Error: " . mysql_error());
$result = array;
mysql_select_db($dbDatabase) or trigger_error("Failed to connect to database {$dbDatabase}. Error: " . mysql_error());
//prevents injections
$choice = mysql_real_escape_string($_GET['type']);
//forms the query
$query = "SELECT DISTINCT sio FROM meters WHERE series='$choice' ORDER BY sio";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
echo "<option>" . $row{'sio'} . "</option>";
}
?>
You can test it live at new.foxmeter.com/dynamic.php
Also, new.foxmeter.com/dynoptionswithselect.php?type=FM800 is a version of the PHP script with
<select> and </select>
added before and after the script to test that the script is working (which it is).
Thanks!

The change() listener is never being called, probably because you're trying to register it before the DOM is ready.
What you need to do (and what is generally good practise with javascript) is make sure that the DOM is ready before you execute any script that relies on it.
There are a couple of ways of doing this - one is putting the script at the bottom of the page, but a better (safer) option is to use jQuery's document ready event handler:
$(document).ready(function(){
//your code here
});
The shorthand for which is:
$(
function(){
//your code here
}
);
So in your case:
<script>
$(function(){
$("#type").change(function() {
$("#range").load("dynoptions.php?type=" + $("#type").val());
}).trigger("change");
});
</script>

Related

PHP code in innerHTML

I'm trying to have my code add this 2 fields to a form (quantities and products) on a click of a button.
How do I format my script so the innerHTML can include php code?
Or is there another way to add a select element via JS?
newdiv.innerHTML = "<input type='text' name='quantities[]'> <select name='products[]'>
<?php
$sql = mysqli_query($link, "SELECT name FROM inventory");
while ($row = $sql->fetch_assoc()){
echo "<option value=\"".$row['name']."\">" . $row['name'] . "</option>";
}
?>
</select>";
PHP code is interpreted by your server before the page is even sent to the browser. The server then sends a completed html page (no PHP code) across the internet to your browser, which then loads it and then executes the JavaScript in the browser. The PHP interpreter would have no way of reading what the JavaScript changes on the finished page.
You might want to look into making an Ajax call to a PHP page, your PHP page can then contain the sql query and return data the JavaScript can use to add the options.

Populating second dropdown on the same page

I am trying to populate a second dropdown based on first on the same page without having to call any external PHP script. I have been testing ajax but it is not working, it has to call another PHP script externally.
I have states, so when a state is clicked it populates the second dropdown with the locality for that state from the db the first dropdown is working properly but the second isn't working. This is my code, been trying ajax nothing works.
I want to echo the value from the db on the same page without calling any external PHP script. How can I pass the first dropdown value to the second dropdown PHP code below for query to the db? Not calling another PHP file externally, all on the same page?
//first dropdown//
<select name="state" class="select" >
<option selected>State</option>
<?php
$u = "SELECT * FROM state_id";
$sql = mysqli_query($con, $u);
while ( $row = mysqli_fetch_assoc($sql))
{
echo '<option>'.$row['name'].'</option>';
}
?>
</select>
</div>
</div>
<div class="col-md-2">
<div class="aa-single-advance-search">
<!-- second dropdown on the same page -->
<select name="locality" class="select2">
<option selected>Location</option>
<?php
//local area is the table i am getting localities based on state value in the first select menu//
$u = "SELECT name FROM local_area WHERE state_id='$id'";
$sql = mysqli_query($con, $u);
while ( $row = mysqli_fetch_assoc($sql))
{
echo '<option>'.$row['name'].'</option>';
}
?>
</select>
A common mistake (perhaps not one you are encountering, but fwiw) is to think the PHP code can somehow run the AJAX. Not true. Once the page is rendered, PHP cannot run. That's where javascript comes in, and that's why AJAX is started in js/jQuery.
Note that jQuery is a library that you reference/load on your page. Not only is it 30% less typing (that fact alone is a good enough reason to use it), but it is also automatically cross-browser. More importantly, jQuery makes AJAX easy.
Study this (working) example. Perhaps even reproduce the example on your server and monkey around with it a bit. Turn the example into your own solution.
Populate dropdown B based on selection in dropdown A
I did little work and it worked but what confused me was the relationship between the external php script and the second dropdown.

PHP Inside JavaScript - Quotes Issue?

Good afternoon,
I've been looking around for info on this and have come up dry. The idea is to have a form that uses select boxes to display info from a mysql database. This is mainly done with html/php, but I have added JavaScript functionality that allows a user to press a button to create an additional array of selects to indicate additional products. The problem I am currently facing is that I cannot seem to get the php to work inside of the JS innerHTML.
order-add.php
<script src="/js/addProduct.js" language="Javascript" type="text/javascript"></script>
<tr>
<td>Product(s)</td>
<td><div id="dynamicInput">
<select name="orders_product[]">
<option value="">Select One</option>
<?php
$orders_product_query = $conn->prepare("SELECT product_name FROM product");
$orders_product_query->execute();
$orders_product_query->bind_result($orders_product_result);
while ($orders_product_query->fetch()) {
echo "<option value = '$orders_product_result'>$orders_product_result</option>";
}
$orders_product_query->close();
?>
</select>
</div>
<input type="button" value="Add product" onClick="addInput('dynamicInput');">
</td>
</tr>
addProduct.js
var counter = 1;
var limit = 10;
function addInput(divName) {
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " products.");
} else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "
<select name='orders_product[]'>
<option value=''>Select One</option>
<?php
$orders_product_query = $conn->prepare('SELECT product_name FROM product');
$orders_product_query->execute();
$orders_product_query->bind_result($orders_product_result);
while ($orders_product_query->fetch()) {
echo 'test';
}
$orders_product_query->close();
?>
</select>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
With all of the testing I've been trying to run on this, it appears that the issue is with the newdiv.innerHTML portion of the addProduct.js. I'm thinking that it is not accepting php, but it also could be that I have the inner quotes somehow messed up.
Thanks in advance for your help!
I think you are not understanding how this works. PHP code is executed when the client requests the page on the server side. JS is executed on the client side. There is no PHP interpreter on the web browser. What you could do is putting the PHP code in a separate file (Example: fragment.php) and calling it through AJAX. In that case your code will be executed in the server.
I hope this helps!
Is addProduct.js included as a tag? If so, take a look in your developer tools. This is probably showing exactly as you have it posted here, with the php tag as part of the text. You'll need to change the extension of this file to .php and change it in the script tag as well to get php to parse the file.
Alternatively, you can try somethign like what #NMO suggested, and retrieve this via AJAX.

JQuery populating select box but after post options disappear

I have an SVG map. When someone clicks on a state say, "Kansas" it displays a form and populates the state select box with the state that was clicked on say, it's Kansas. Code - This is working fine. This code is in the head.
var itemval= '<option value="'+data.name+'">'+ stateData[data.name].fullName+'</option>';
$("#SelItem").html(itemval);
When the form is submitted and it posts back to the same page, I'm using
<form method="POST" action="theform.php" onsubmit="return validateForm(this);">
When the page post back to the same page the select box is empty. The select box is there but with no option.
I've searched on Google I found the code below plus a few similar ways but they don't work. I've used this code in the head and under the select but no luck.
var selectedVal = $("#SelItem").val();
$("#SelItem").val(selectedVal);
**HTML**
<select id="SelItem"><option></option></select>
I've been working on this for hours but can't seem to find a solution.
Can someone tell me how to keep the select value after the form has been submitted and returns to the same page?
When the page loads you need to check for the presence of your posted value, and if it's there pass the php value to either the javascript code to populate the select option, or use it directly in the html creating the select options.
First off, you should give your select a name attribute in the html so the value is passed into the $_POST array in php:
<select id="SelItem" name="SelItem">
Here's one way you can populate it in javascript (note this code relies on the var stateData being in the same scope):
$(document).ready(function(){
<?php if (!empty($_POST['SelItem'])): ?>
var posted_state = '<?php echo $_POST['SelItem'];?>';
if (stateData[posted_state] !== undefined) {
var itemval= '<option value="'+posted_state+'" selected>'+ stateData[posted_state].fullName+'</option>';
$("#SelItem").html(itemval);
}
<?php endif; ?>
});
EDIT: An alternative to the above would be to put it in the html for the select tag:
<select id="SelItem" name="SelItem">
<?php if (!empty($_POST['SelItem'])): ?>
<option value="<?php echo $_POST['SelItem'];?>" selected>
<?php echo $_POST['SelItem']; // this would be better if you can replace it with fullname ?>
</option>
<?php else: ?>
<option></option>
<?php endif; ?>
</select>
Note this method has a couple issues as it's written. First off, the option text in this example won't be the state full name but the abbreviation. Next, you shouldn't trust the contents of $_POST because a malicious user can easily change it to a value you didn't intend it to be. It would be better to validate the value of $_POST['SelItem'] in your php code that handles the post to make sure it is actually one of the correct values before using it. That is why in the previous example I did the check if (stateData[posted_state] !== undefined) before attempting to add the value to your select.
EDIT:
To provide the state fullname from php you need an array of states defined on the php side also (I only see it in your javascript code which is client side).
So in php if you have something like:
$states = array(
'AK' => 'Alaska',
'AL' => 'Alabama',
// etc...
);
Then you can use the posted state abbreviation to get the fullname:
if (array_key_exists($_POST['SelItem'], $states))
$fullname = $states[$_POST['SelItem']];

Modifying html dropdown to searchable dropdown using Chosen plugin

I have a working dropdown which gets its value from MySQL database in PHP.
I want to have a searchable dropdown instead of scrolling the list by using Chosen plugin.
Now, my question is how should I change my regular dropdown into Chosen dropdown?
(I need to know the procedure)
here is my code:
<form>
<select name="mySubmit" onChange="drawChart(this.value);">
<option value="">Select an option:</option>
<?php
// Make a MySQL Connection
$con = mysql_connect($dbserver, $dbuser, $dbpass) or die(mysql_error());
mysql_select_db($dbname) or die(mysql_error());
// Create a Query
$sql_query = "SELECT `Name`, `id`
FROM info AS t1
where
(SELECT COUNT(*)
from info AS t2
where t2.Name = t1.Name AND (t2.`Date`) > (t1.`Date`)) = 0";
// Execute query
$result = mysql_query($sql_query) or die($sql_query."<br/><br/>".mysql_error());
while ($row = mysql_fetch_array($result)){
echo '<option value='. $row['id'] . '>'. $row['Name'] . '</option>';
}
mysql_close($con);
?>
</select>
</form>
Thank you in Advance.
first, you have to give a class or id to your select HTML element.
<select class="chosen" .... //same html/php code
Then in your javascript code, you call the jQuery chosen plugin to change this select to a chosen element like this:
$(document).ready(function(){
$('.chosen').chosen();
})
and it should work, you don't have to change anything in you php code, just give a class or id to you your select element so you can get if with jQuery selector. I advice you to read the chosen documentation

Categories

Resources