Dynamic form PHP / Javascript - 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);
}

Related

How to use JS to hold a variable from a PHP form before submit

I'm quite new to PHP so apologies for not being fully aware of code structures.
In a PHP file I have a form with the options in a drop-down menu being populated from a database query (how many rounds for a tournament based on the number of entrants). Once a user has selected an option for the round of fixtures they want to view that option gets passed as a variable to determine what to display on form submit. On form submit the rest of the page changes to display the fixtures from the database that relate to the Round that the user selected from the drop-down.
My challenge is that after selecting the Round number from the drop-down menu I have to click the submit button twice - once to assign the variable and then the second press of submit to be able to use the variable as part of the process to display the fixture information from the database.
I'm aware that it is possible to use JS to store a variable that can then be used on form submit but I'm not sure how to integrate it with the way the form / has been written.
After looking at a few places on the web (like W3Schools) I've got some basic JS and have tried that but I think there's still a disconnect between the user selecting and storing the variable ready to be used when the submit is clicked.
//Basic JS
<script>
function getFormIndex() {
document.getElementById($_POST['roundselect']).innerHTML =
document.getElementById("roundselect").selectedIndex;
}
</script>
//PHP Elements
if(isset($_POST['submit'])){
$roundnum = $_POST['roundselect']; }
<?php
function setround(){
$roundnum = $_POST['roundselect'];
echo $roundnum;
}
?>
//Form
<div class="h2_select">
<? if($fnum) {
$select_opt = (isset($_GET['round'])) ? $_GET['round'] : 1;
?>
<form method="post" action="/tournaments/<?=$lid; ?>/fixtures/<?= $roundnum; ?>" name="rf">
<!--<input type="hidden" name="id" value="/<?=$lid; ?>" />
<input type="hidden" name="page" value="/fixtures" /> -->
<span class="minput">Select Round
<select size=1 class="mselect" name="roundselect" onChange=getFormIndex();>
<? for($i=1; $i <= $total_rounds; $i++) { ?>
<option value="<?= $i ?>" <?php if($i == $select_opt){ echo 'selected'; } ?> > <?= $i?> </option>
<? }
?>
</select>
<input type="submit" name="submit" value="<?= $lang[185] ?>" class="minput"/>
</form>
<? } ?>
</div>
To confirm, the form works and displays the correct information. The problem is that I currently need to click "submit" twice.
Thanks
Good start, I would do it with a bit of AJAX that allows us to send a request and receive an answer "in the background" - so that first time user changes the select I would fetch data from backend in the background and display it without double-submitting needed.
Please check this thread - I think it is illustrating the same thing;
How to Submit Form on Select Change
It is based on JQuery and I think it is a good start for new developers.
But - if you do not want to use a framework and does not care for older browsers you can just use "vanilla" Javascript with Fetch (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) and onchange https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event
Fetch returns the result so then you have to pass it back to the website.
It is very easy to do so with :
1. set a div on your page and add a unique ID to it (like )
2. use document.getElementById("result").innerHTML = resultFromFetch;
So:
listen to onchange on select
fetch from backend when select changes
display fetch result
AJAX is really neat and very good for the user experience as it allows us to get the data asynchronously and in the "back stage" of our application. But then it is a good user experience measure to show also some "please wait" indications and also make sure to show some potential errors (the connection can go "down" when waiting for results and then it is wise to show errors to users instead of them waiting forever).
Hope this helps to point you in a new and exiting direction.

Select data from mysql with php, display in html dropdown list and insert selected value as URL parameter via javascript

First, please understand I have just begun to learn php, javascript and ajax in the past 10 days so I will need some hand-holding and step-by-step examples and guidance. I've carefully read the courses for those topics at w3schools and found them very helpful; as a result, I was able to write some basic code for my project by using their examples and other snippets I've found here and other sites.
This post is a little lengthy so I can explain my ultimate goal for this code and what I've already tried.
I have started writing a piece of very complex code that has multiple parts, but the final result will be a dropdown selection list with an image thumbnail button of the main_image of that page linked to an external URL which is dynamically created based on the user's dropdown list selection.
This is my project:
I am building a website with Joomla 3.x.x, Bootstrap 3 and j2store (with other components and modules) that features photos for sale as digital images and that can be applied to physical products (canvas prints, t-shirts, coffee mugs, etc). Those physical products exist on a 3rd party website (Zazzle) which are embedded into my private website with Zazzle's RSS feed and another 3rd party javascript code (to embed Zazzle RSS feed grid displays into my website).
The Zazzle API allows my users to choose any image from my private website and apply that image to any product available in Zazzle's marketplace.
My users would ultimately select a category of products from a dropdown list on my website and then click a button that would open a new window to connect to the Zazzle marketplace which would display a grid of relevant physical products featuring the image shown on the active page of my website where the user clicked the button.
For example, the user starts by looking at the page on my website with the main_image "Light Purple African Daisy", chooses a category of electronic products from a dropdown list and then clicks the "Design Your Own Gifts" button which opens a new window, connects to the Zazzle marketplace and displays a grid of electronic products showing the "Light Purple African Daisy" image on the user's chosen products.
The URL behind the "Design Your Own Gifts" button needs to be created dynamically with the selected value after the user chooses a category of products from a dropdown list on my website.
This is the Zazzle API I need to use:
https://www.zazzle.com/api/create/at-238500395169782226?rf=238500395169782226&ax=DesignBlast&sr=250508120301240636&cg= <DYNAMIC CATEGORY ID FROM DROPDOWN SELECTION LIST> &t__useQpc=false&ed=true&t__smart=false&continueUrl=https%3A%2F%2Fwww.zazzle.com%2Fcapturedimagesmaine&tc=&ic=&t_coverimage_iid= <URLENCODED DYNAMIC PATH OF ACTIVE PAGE MAIN_IMAGE>"
I have created 2 tables in mysql database that hold the Names, Category IDs and Department IDs for the products in my Zazzle marketplace. I am also getting the main_image path from my j2store productimages table.
The code I have been able to write so far accomplishes the following tasks:
Connect to the database
Choose Columns/Tables
GET Data from Columns/Tables
Create HTML Form to Display Result of MYSQL Query
Create Dropdown Selection List of Query Results
Echo encoded URL with Zazzle API concatenated with Parameters/Dynamic Values
This is my code so far:
<div class="form-group" style="margin: 30px 10%;">
<h3>Create Zazzle Products</h3><p><h4>Select a Template Category</h4>
<form name="create-zproducts" id="create-zproducts" action="create-zproduct.php" method="POST">
<?php
//connection
$con = mysqli_connect('localhost', 'user', 'password', 'database');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$sql="SELECT * FROM david_cim_template_categories, david_j2store_productimages";
$cg = $_GET['cim_template_cg'];
$coverimage_iid = $_GET['main_image'];
$result = mysqli_query($con,$sql);
?>
<select name="selectZcategories" id="selectZcategories">
<?php
while($row = mysqli_fetch_array($result)) {
echo '<option value="'.$row['cim_template_cg'].':'.$row['cim_template_cgname']'">'.$row['cim_template_cgname'].'</option>';
}
?>
</select>
<button onclick="ajaxFunction();">Submit</button><br /><br />
<?php
<script>
function ajaxFunction() {
var selectedData=$("#selectZcategories option:selected").val();
$.ajax({
type : "POST",
url: "select_zproduct.php",
data: { selection : selectedData },
success: function (html) {
//Success handling
}
})
}
</script>
?>
<?php
echo $ZAPI = "https://www.zazzle.com/api/create/at-238500395169782226?rf=238500395169782226&ax=DesignBlast&sr=250508120301240636&cg=";
echo $cg = ['cim_template_cg'];
echo $ZPARAM = "&t__useQpc=false&ed=true&t__smart=false&continueUrl=https%3A%2F%2Fwww.zazzle.com%2Fcapturedimagesmaine&tc=&ic=&t_coverimage_iid=https%3A%2F%2Fwww.capturedimagesofmaine.com%2Fimages%2Fproducts%2Foriginal%2F";
echo $coverimage_iid = ['main_image'];
echo $product_text = "&t_text1_txt=Welcome";
?>
</form>
</div>
// new file (select_zproduct.php) added to same path as create_zproduct.php
// contents of select_zproduct.php below:
<?php
if( isset($_POST['selection']) )
{
$selecterData=$_POST['selection'];
$selecterArrayData=explode(':', $selecterData);
$cg=$selecterArrayData[0];
$coverimage_iid=$selecterArrayData[1];
$url='https://www.zazzle.com/api/create/at-238500395169782226?rf=238500395169782226&ax=DesignBlast&sr=250508120301240636&cg='.$cg.'&t__useQpc=false&ed=true&t__smart=false&continueUrl=https%3A%2F%2Fwww.zazzle.com%2Fcapturedimagesmaine&tc=&ic=&t_coverimage_iid='.$coverimage_iid.'';
?>
<script>
window.location.href=<?php echo $url; ?>;
</script>
<?php
}
?>
The code above is just the beginning of what I've been able to write by myself so far.
My obstacle at the moment is not being able to make the " cg= " parameter display the numeric value of $cg= which was selected by the user from the dropdown list. The current code returns the word "Array" in the URL instead of the selected value. (eg. cg=Array instead of cg=196215449301144739)
I believe I need to use AJAX and Javascript to accomplish this action but I don't know enough to write it by myself yet.
The Code I Need to Write will accomplish the following tasks:
Assign proper $variables to URL fragments ($ZAPI, $cg, etc) to be used for concatenation
Assign proper $variables to database dropdown SELECTION Result to be used in the URL above
Concatenate all $variables
Parse all $variables
Embed final encoded URL into button
Use thumbnail of active page main_image as button image src
What I need to know right now is how do I insert the numeric value of 'cim_template_cg' into the " cg= " parameter in the final URL so the final URL will output " &cg=196215449301144739 " when the user selects the 'cim_template_cgname' associated with that cg=.
Once I see the solution I can apply it to the other dynamic values I need to create. I've only written one javascript code with help from a snippet so any AJAX or Javascript code that needs to be written will need to be shown to me in an example and describing related files, please.
Thanks for your help in advance!
So if I understood your question properly, you have the necessary data to achieve this, i.e. you have the URL path and ID from the database, as well as the URL string, which needs these database values dynamically added upon selection?
And to answer one of your questions, yes this can be done via AJAX if you wish for the PHP logic to be handled in a seperate file.
What you could do, is concatenate your URL path and ID from the database with a seperator value that you could perform an explode(); on to get the values.
so, your <select> would look something like this instead:
<select name="selectZcategories" id="zCategories">
<?php
while($row = mysqli_fetch_array($result)) {
echo '<option value="'.$row['cim_template_cg'].':'.$row['cim_template_cgname'].'">'.$row['cim_template_cgname'].'</option>';
}
?>
</select>
Now to the AJAX function. Personally, I use the jQuery library, simply because it makes things easy and simple. It simplifies a lot of the code, so I am going to go by the jQuery standards in my AJAX example. If you wish to use jQuery AJAX to achieve the same results, you will need to install jQuery into a library that you include like any other normal JS/CSS file etc.
function ajaxFunction() {
var selectedData=$("#zCategories option:selected").val();
$.ajax({
type : "POST",
url: "/path/to/file.php",
data: { selection : selectedData },
success: function (html) {
//Success handling
}
})
}
What this achieves, is that the function will take the selected value of the <select> and parse the data to another file using the POST method. You are able to do a lot of things in the success function if you so desire, but for our purpose, I'll simply perform the redirect in the PHP file.
When the data has been parsed to the other file, you then perform an explode(); on the value to split it up into our two variables that we will parse along in our URL.
The PHP file could look something like this:
<?php
if( isset($_POST['selection']) )
{
$selecterData=$_POST['selection'];
$selecterArrayData=explode(':', $selecterData);
$categoryID=$selecterArrayData[0];
$imagePath=$selecterArrayData[1];
$url='https://www.zazzle.com/api/create/at-238500395169782226?rf=238500395169782226&ax=DesignBlast&sr=250508120301240636&cg='.$categoryID.'&t__useQpc=false&ed=true&t__smart=false&continueUrl=https%3A%2F%2Fwww.zazzle.com%2Fcapturedimagesmaine&tc=&ic=&t_coverimage_iid='.$imagePath.'';
?>
<script>
window.location.href=<?php echo $url; ?>;
</script>
<?php
}
?>
How you call the AJAX function initially is up to you. It could be via a button for instance.
<button onclick="ajaxFunction();">Submit</button>
Hope this helped, or pointed you towards the right direction.
For tests as per request by your comment,
Ajax for test:
function ajaxFunction() {
var selectedData=$("#zCategories option:selected").val();
$.ajax({
type : "POST",
url: "/path/to/file.php",
data: { selection : selectedData },
success: function (html) {
//Success handling
alert(html);
}
})
}
PHP:
<?php
if( isset($_POST['selection']) )
{
$selecterData=$_POST['selection'];
$selecterArrayData=explode(':', $selecterData);
$categoryID=$selecterArrayData[0];
$imagePath=$selecterArrayData[1];
$url='https://www.zazzle.com/api/create/at-238500395169782226?rf=238500395169782226&ax=DesignBlast&sr=250508120301240636&cg='.$categoryID.'&t__useQpc=false&ed=true&t__smart=false&continueUrl=https%3A%2F%2Fwww.zazzle.com%2Fcapturedimagesmaine&tc=&ic=&t_coverimage_iid='.$imagePath.'';
echo 'cg: '.$categoryID.' img path: '.$imagePath;
?>
<script>
//window.location.href=<?php echo $url; ?>;
</script>
<?php
}
?>
I contacted the developer of J2Store for help with getting the main_image value from the active J2Store product page and embedding my final API URL into my J2Store product pages so he rewrote my code to integrate error-free with both Joomla and J2Store, as follows:
<?php
/**
* #package J2Store
* #copyright Copyright (c)2014-17 Ramesh Elamathi / J2Store.org
* #license GNU GPL v3 or later
*
* Bootstrap 2 layout of product detail
*/
// No direct access
defined('_JEXEC') or die;
$db = JFactory::getDbo();
$query = $db->getQuery(true)->select('*')->from('#__cim_template_categories');
$db->setQuery($query);
$cg_values = $db->loadObjectList();
$image_path = JUri::root();
$main_image = $image_path.$this->product->main_image;
//$zazzle_api = 'https://www.zazzle.com/api/create/at-238500395169782226';
$zazzle_api = 'https://www.zazzle.com/api/create/at-238500395169782226';
?>
<?php if(count($cg_values)): ?>
<div class="cg_values">
<form method="get" class="zazzle_api_form" action="<?php echo $zazzle_api; ?>">
<select name="cg" class="cg">
<?php foreach($cg_values as $cg_value): ?>
<option value="<?php echo $cg_value->cim_template_cg; ?>">
<?php echo $cg_value->cim_template_cgname; ?>
</option>
<?php endforeach; ?>
</select>
<input type="hidden" name="rf" value="238500395169782226" />
<input type="hidden" name="ax" value="DesignBlast" />
<input type="hidden" name="sr" value="250508120301240636" />
<input type="hidden" name="t__useQpc" value="false" />
<input type="hidden" name="ed" value="true" />
<input type="hidden" name="t__smart" value="false" />
<input type="hidden" name="continueUrl" value="<?php echo urlencode('https://www.zazzle.com?www.capturedimagesmaine.com'); ?>" />
<input type="hidden" name="tc" value="" />
<input type="hidden" name="ic" value="" />
<input type="hidden" name="t_text1_txt" value="" />
<input type="hidden" name="t_coverimage_iid" value="<?php echo $main_image; ?>"
/>
<input class="btn btn-primary" type="submit" value="Create Your Own Custom Gifts"
/>
</form>
</div>
<?php endif; ?>

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.

How to retrieve value from database on check box click?

Hi i have three check box where i want that which one check box i select regarding that check box value should retrieve from database
Here is my check box
<input type="checkbox" name="test" value="X-Ray" style="margin-top:10px;margin-left:120px;"><label>X-Ray</label>
<input type="checkbox" name="test" value="Ecg" style="margin-top:10px;margin-left:20px;"><label>ECG</label>
<input type="checkbox" name="test" value="Blood Test" style="margin-top:10px;margin-left:20px;"><label>Blood Test</label>
mysql query
SELECT SUM(price) from test where test='x-ray' or test='' or test='bloodtest'
how can i get my desired output? Any help will be appreciated.
You could get a hold on the specific input checkbox using the jquery selector :checked. So something like this in your javascript should get you started :
$( "input" ).on( "click", function() {
var sel = $( "input:checked" ).val();
//Here you can just make a simple ajax request to a php script passing the
//specific checkbox value and let that script perform the mysql query.
$.post( "test.php", { test: sel })
.done(function( data ) {
alert( "Completed");
});
});
Your test.php script could look something like this:
<?php
$test = $_POST["test"];
//Replace with your sql database credentials
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT SUM(price) from test where test='".$test."'");
mysqli_close($con);
?>
This is a barebone starting template of how you could proceed with your problem. Ofcourse, the specific use case could vary. For instance you could make a get request instead of a post request and make your php script interact and fetch data differently.
I just gave you an example of how the workflow would look like in simple jquery and php. So you just get the value of input checkbox and pass on the value to a script that interacts with the database and fetches the specific SUM. You should probably read some documentation on Jquery Ajax or PHP Mysql to get a better hang of this. Hope it helps.
I think that the best solution to this is to output all the prices as a JavaScript variable somewhere on the page, Let's alter the HTML a little bit.
<input type="checkbox" class="chkbox-update" name="test" value="X-Ray"><label>X-Ray</label>
<input type="checkbox" class="chkbox-update" name="test" value="Ecg"><label>ECG</label>
<input type="checkbox" class="chkbox-update" name="test" value="Blood Test"><label>Blood Test</label>
Now, the prices. Use PDO to itterate through results and construct a JSON-formatted variable:
<script>
var prices = {"X-ray": 3900, "ECG": 2000, "Blood Test": 1200};
</script>
Then use JavaScript to update the price field, I'm using jQuery for this.
$('.chkbox-update').click(function() {
var total;
$.each($('.chkbox-update'), function(k,v) {
total += prices[$(this).val()];
});
$('#result').text('The total price is '+total);
});
Make Sure that the key for the prices variable matches the value of the <input>

Dropdown onchange method using PHP and 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.

Categories