Please someone help, I am really stuck on this for 2 days :|
I have a PHP form and I would like to enable user select movies by title, or by actors.
So, I was thinking about a dropdown menu by these values (moviebyTitle, moviebyActor). For selecting movies by title, I used jQuery auto-complete which get movie titles from my DB and it works fine.
This is my code:
<select id="selectType" name="source">
<option value="">MoviesBy</option>
<option value="byTitle">byTitle</option>
<option value="byActor">byActor</option>
</select>
<input type="textbox" name= "tag" id="tags">
<div id="byActor" class="style-sub-1" style="display: none;" name="stylesub1" onchange="ChangeDropdowns(this.value)">
<select name="films[]" multiple="multiple" width="200px" size="10px">
<?php
include('moviedropdown.php');
?>
</select>
and here is the javascript:
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.1/themes/base/minified/jquery-ui.min.css" type="text/css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.1/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#tags").autocomplete({
source: "actorsauto.php",
minLength: 2
});
$("#selectType").change(function () {
if ($(this).val() == "byTitle")
$("#tags").autocomplete("option", "source", "filmsauto.php");
else
if ($(this).val() == "byActor")
$("#tags").autocomplete({
source: "actorsauto.php",
minLength: 2,
select: function (event, ui){
var selectedVal = $(this).val(); //this will be your selected value from autocomplete
// Here goes your ajax call.
$.post("actions.php", {q: selectedVal, q2: $("#selectType").val()}, function (response){
// response variable above will contain the option tags. Simply put in the dropdown.
$("#movieImdbId").html(response);
});
}
});
}
});
});
</script>
EDIT:
and this is the actions.php: (please kindly see also javascript part above)
<?php
if(isset($_GET['q']) && !empty($_GET['q']) && isset($_GET['q2']) && !empty($_GET['q2']) ){
// Here goes the cleaning code. Never use the variables received from $_GET and $_POST directly before processing it for malicious code.
$q = $_GET['q'];
$q2 = $_GET['q2'];
//$sql = fetchResults($q, $q2); // Some function which will run a database query and return some records in either object collection or arrays etc.
//I added this part to fetch data from DB
include('imdbConnection.php');
$sql = $conn->prepare('SELECT DISTINCT movieImdbId FROM movie_roleNames WHERE castName = :q');
$sql->execute(array(':q' => $q));
$html = "";
while($row = $sql->fetchAll(PDO::FETCH_OBJ)){
$option = '<option value="' . $row->movieImdbId . '">' . $row->movieImdbId . '</option>';
$html = $option;
}
echo $html; // <-- this $html will end up receiving inside that `response` variable in the `$.post` ajax call.
exit;
}
?>
My question:
I just wonder how can I add a drop down list based on the value user has typed in the textbox. For example, if user wrote "Tom Cruise" in the auto-complete textbox, a dropdown will be added that shows movies in which "Tom Cruise" has played. (I make a COMMENT in the JavaScript code where I had problem)
I really searched a lot, but all samples where to dynamically populate some dropdown (like this one, or adding a textbox based on value selected in dropdown...
Please help, I really don't mean someone write the code for me, I just want to find any sample or some way that I can learn how to do it.
Thanks,
You should have something like the following.
What you actually need is when you type into the auto complete box and select something, you need to get a hold of that value for later use. After that, you need to call the server (a php script) with an ajax call and send that value from the autocomplete box along with the value from the drop down (only if you need to). That php script will need to generate a pile of something like the following in loop and save the whole html in a variable.
<option value='v1'>Value1</option>
<option value='v2'>Value2</option>
After that, send that back to the calling ajax script and then you need to put this as the content inside that drop down that you're trying to populate.
Here's some sample code on how to accomplish the javascript part.
<select id="filmsdd" name="films[]" multiple="multiple" width="200px" size="10px">
</select>
<script>
$(document).ready(function () {
$("#tags").autocomplete({
source: "actorsauto.php",
minLength: 2,
select: function (event, ui){
var selectedVal = $(this).val(); //this will be your selected value from autocomplete
// Here goes your ajax call.
$.post("actions.php", {q: selectedVal, q2: $("#selectType").val()}, function (response){
// response variable above will contain the option tags. Simply put in the dropdown.
$("#filmsdd").html(response);
});
}
});
});
<script>
EDIT:
path/to/somefile.php would be any file which is stored in your directory along with other website files. let's call it actions.php (I have updated the $.post ajax call)
When $.post runs, it will send a request to actions.php along with two variables q and q2. These variable names can be anything.
q contains the selected value from the auto complete box.
q2 contains the selected type from the drop down.
in actions.php, you end up with something like this.
if(isset($_GET['q']) && !empty($_GET['q']) && isset($_GET['q2']) && !empty($_GET['q2']) ){
// Here goes the cleaning code. Never use the variables received from $_GET and $_POST directly before processing it for malicious code.
$q = $_GET['q'];
$q2 = $_GET['q2'];
$sql = fetchResuls($q, $q2); // Some function which will run a database query and return some records in either object collection or arrays etc.
// Initialize a variable that you will send back to your ajax call, its still waiting for this script to be completed.
$html = "";
// Assuming your function returned a list of objects. Loop through the records.
while($row = mysql_fetch_object($sql)){
$option = '<option value="' . $row->property_id . '">' . $row->property_name . '</option>';
$html .= $option;
}
echo $html; // <-- this $html will end up receiving inside that `response` variable in the `$.post` ajax call.
exit;
}
I hope this helps.
The real question is, what's the point of the second drop down box. Why dont you just display all of the movies in a "table" once they've selected the actor.
I'd suggest a unified "Search" box, and on the PHP side, querying both your movies and actors, displaying all results that way?
If they choose a autoComplete value that is of type actor, display all the actor's movies. If they select an autoComplete value that is of type "movie" - display all the movies.
Effectivly - you're eliminating the By Actor or By Movie radio in favor of a better search bar.
Related
First SELECT:
<?php
function select_size($itemSizes){
echo "<select id=\"size\" name=\"size\">";
$sizes = array("0" => "All Sizes","1" => "Large","2" => "Medium","3" => "Small");
foreach($sizes as $s => $si){
if($itemSizes == $s){$selected = "selected";}
echo "<option value=\"" . $s . "\" $selected>" . $si . "</option>\n";
$selected = "";
}
echo "</select>\n";
}
?>
Second SELECT:
$(document).ready(function() {
$("#eventCategory").change(function() {
var val = $(this).val();
$("#eventType").html(options[val]);
});
var options = ["
<option value='all_items'>ALL Items</option>
<option value='red'>red</option>
<option value='blue'>blue</option>
<option value='green'>green</option>
];
});
First select retains value due to PHP. onChange is working properly as once a value in Select #1 is chosen, Select #2 populates with it's appropriate list. The problem I'm having is Select #2 is not retaining it's value through a POST and page reload. I've worked out a bit of JS that does this but it fouls up the onChange function. I'm trying to achieve both at the same time and have failed thus far. Yes, I'm an amateur with JS. Pretty good with many other languages. The syntax is causing me troubles. Any assistance is greatly appreciated.
You can send an ajax when first select triggers onChange event.
Then, on the success of this Ajax, you can get values from php and changing the second one. As you are using ajax, the first option will not be modified.
As you asked for "reloading page" you will need to print a script in the view that browsers can render, this can look like:
if you can know the ID of each option (if any):
echo "<script> $('#selector1 option#'.$idOption.').attr('selected', 'selected'); </script>";
if you can't know the ID of each or there are any id to catch, you'll get the value for sure, the script will look like:
$('#selector1 option[value="'.$value.'"]').attr("selected", "selected");
where in the first case $idOption is the id of the option selected on first selector and retrieved from php. $value in the second script is.. well, the value.
don't really know if there solves your entire problem as i can only see a part of your code, i'll edit it if you provide feedback.
Maybe you would var_dump / console.log values for getting a backtrace of your data and see where it's lost to ensure you pass the needed data around your functionallity.
I don't know how to solve the variable $cat by following script.
"text" variable from Form to javascript and pass to php function to be $Categories_name and to be $cat.
I already test the $cat variable, it is not "String", it is "object", I don't understand.
But I need $cat to be "String".
when Test = "This is Cat" (3 words),
I test $cat by php str_word_count and the output is 1 (I need to correct answer 3);
I test $cat by php var_dump and no output (I need to correct answer "String").
<p id="CaTable"></p>
<script>
function CaFunction()
{
var text = document.getElementById("CategorySelect").value;
document.getElementById("CaTable").innerHTML = "<?php php_catable('" + text + "'); ?>";
}
</script>
<!-- Generate Table by php and MySQL-->
<?php
function php_catable($Categories_name)
{
$cat = $Categories_name;
.................
.................
$sql = "select * from table where xyz = '" .$cat. "'";
}
?>
You are confusing server side code and client side code. Your php code live on the server and can only be executed on the server. And your javascript is on your client's browser and does not know about the server (remember, php generate a text file, and only that text file is sent to the browser). if you want to use the php_catable() function from your client, you will need to do an AJAX call or to redesign your page to do a form submit (just like what Steve is proposing).
Your First Page:
Assuming CategorySelect is a dropdown select box, create a script for its onChange event and create a method="post"post form with a hidden input that goes to "generate_table.php".
<input type="hidden" name="ca_table" id="ca_table" />
You make ca_table a hidden input so php will pick up the value from it when this page gets submitted to a second page where you can generate your table using the php function.
<script language="javascript" type=text/javascript>
function CaFunction(){
documentGetElementById('ca_table').value = documentGetElementById('CategorySelect').value;
submit();
}
</script>
add this to your select dropdown:
onChange="CaFunction();"
Your Receiving Page:
So your receiving page "generate_table.php" would have
<?php
function php_catable($Categories_name)
{
$cat = $Categories_name;
.................
.................
$sql = "select * from table where xyz = '" .$cat. "'";
}
$category_name = $_POST['ca_table']; // cleaned up at least with suitable preg_replace etc
// and call your catable function
php_catable($category_name);
?>
So that way your result will have been posted back to the server as per comments about client side/server side by #Fluinc and answer by #litelite. To get it to do something which performs looking like innerHTML which changes a part of the page without submitting the whole page you will need AJAX, again as per #litelite's answer.
Might get marked down for being dependant on JavaScript but intended mostly to help clarify client v server.
If you want to avoid the JavaScript dependency of this script you could leave out the onChange altogether and add a submit button, then collect $_POST['CategorySelect']; assuming that is its name - ensure it has name="CategorySelect" for php as well as its Id for your css/javascript. Php gets its variable from the item's name.
To get something a bit like the effect of AJAX visually (though the page is still submitted) you could submit the page to itself using action="<?php echo $_SERVER['PHP_SELF']; ?>" on the form and have all the code on the one page. You can put the table generating code in the div where you want the table to appear - it would need a default state set, of course.
#litelite's comment regarding not using posted data directly in an sql query is also vital to prevent attack - make sure you clean it up before you use it!
I have a select input with the following code:
<select name="color" id="color" multiple class="form-control chzn-select" tabindex="8" onchange="autosave(this.id,this.value)">
It is successfully sending the function ID and select value, but seeing as one can select multiple items, it's having an issue. I can select up to 3 items without a problem, but attempting to select a 4th is causing it to pass the value of the first selected item. Not the most recently selected item. Here's the function, which sends other information such as title and date (both text inputs):
function autosave(inputid,values) {
var dataObj = {};
dataObj[inputid] = values;
$.ajax({
type: "POST",
url: "save.php",
data: dataObj,
success: function(msg) {
$('#autosavenotify').text(msg);
console.log('success');
}
})
}
HTML wise I am using Bootstrap3 if that makes a difference and here's how I'm populating the select options:
<?php
$colors = array('Red','Blue','Yellow','Purple','Green','Orange');
foreach($colors as $c) {
$selected = '';
if(in_array($c, $_SESSION['array']['colors'])) {
$selected = 'selected';
}
echo '<option value="'.$c.'" '.$selected.'>'.$c.'</option>';
}
?>
Any ideas why this might be happening? My save.php page is placing all items successfully within the array, the ajax is just sending the incorrect value for some reason.
Because you're already using jQuery, you'd probably be better off just using $(this).val( ) to get the selected options from your select. Here's a fiddle I came up with using your provided code: http://jsfiddle.net/y7NfF/1/
Another route you might consider taking would be using jQuery's .serialize() or .serializeArray() function to get all values of your form when submitting the data through ajax. However, if you want to do one element at a time, your method works just fine.
Here are a couple of links to those functions:
http://api.jquery.com/serialize/
http://api.jquery.com/serializeArray/
I have the following situation:
In a codeignitor project, from the controller, I load a view.
Within that view, I load another view. This sub view is slide open and close based on a radio box selection.
Now this sub view expects the value of the radio box selected.
<?php $this->load->view('myview', $value); ?>
Since the main view is already loaded, and loads the sub view too, how can I assign the value of the radio box selected to the $value variable?
I am using this code for radio box:
<input type='radio' name='var1' id='var1' value='myvalue' onchange=show('true');>
Then in the SHOW function I have this:
function show(val) {
if (val == 'true') {
var var1 = $("#var1:checked").val();
}
}
So I get the value on change to var1 in javascript correctly. But how to pass this value to the value variable in the sub view:
<?php $this->load->view('myview', $value); ?>
Tried the AJAX route too:
I tried ajax route and did this:
$.ajax({
type: "POST",
url: "",
data: "var1=" + value,
success: function(result) {
}
});
And in controller funtion set the
$this->template->set('$value', $this->input->post('var1'));
echo 1;
But still the
<?php $this->load->view('myview', $value); ?>
doesn't read value.
<?php
$this->data['value']= $value;
$this->load->view('myview',$this->data['value']);
?>
myview.php
<?php
echo $value;
?>
There are two environments that you are working on. What you can do is to send a GET or POST variable to your PHP script and process the data. Because everything is rendered in the back-end (PHP part) you need to get status of the checkbox before to load your views. So, without ajax your option is to reload the page with a get parameter set.
Okay. please see bottom screenshot for illustration on frontend. What i'm trying to do here is when the user makes a selection in the select form ie: selects Received, I want to get the value of the inputbox directly on the bottom of the select form and send it via $.post to another script in order for me to process it.
I can't seem to get the data pass over via $.post to read the value in the inputbox. Main focus should be at the $.post area. I tried using $('.order_item_id').val(); in my $.post data but i only get the value under the first inputbox regardless of whichever selectbox i make the selection from.
Here is the section of my javascript and php.
.js
$('.order_stat_sel').change(function(){
var closest_div=$(this).closest('div.order_receipt');
var closest_selectbox=$(this).closest('.order_stat_sel');
if($('.select_received:selected').length>0){
if(confirm('Confirm Receipt of this item?')){
$.post("/seller/buyer_cfm_receive.php",{order_item_id: $(this).closest('.order_item_id').val()}, function(data) {
alert("Congrats, Order Item Completed" + data);
closest_div.append('<p>Completed</p>');
closest_selectbox.remove().fadeOut("slow");
});
}else{
$('.order_stat_sel').val('p');
}
}
});
php
if($this->orderstatuses[$item->order_status]!='received'){
echo '<select class="order_stat_sel" name="order_status">';
echo '<option class="select_pending" value="'.$pendingitem_state[2].'">'.$pendingitem_state[3].'</option>';
echo '<option class="select_received" value="'.$enditem_state[2].'">'.$enditem_state[3].'</option>';
echo '</select>';
}?>
<form class="send_order_cfm_input">
<input class="order_item_id" name="order_item_id" value="<?php echo $item->virtuemart_order_item_id;?>" type="text" readonly="readonly">
</form>
Any help appreciated
.closest() finds the closest ancestor of the element, but you are actually searching for a descendant of a neighbour:
$.post("/seller/buyer_cfm_receive.php",
{
order_item_id:$(this)
.next(".send_order_cfm_input")
.find('.order_item_id').val()
},
function() {
/*...*/
}
);