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.
Related
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!
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.
I have a form.php which adds username selected from dropdown select, and user payments received into database. After inserting values by going to add_form.php, it comes back to form.php. I have sent the username from add_form.php to form.php by using below code
$result=mysql_query($sql);
if($result==1){
echo '<script language="javascript">';
echo 'alert("Payment added successfully");';
echo 'window.open("form.php?name='.$name.'", "_self");';
echo '</script>';
}
Now problem is that, how can I use this get parameter to select the passed value into dropdown automatically? I want the end user of the application to select a name once and add multiple payments, i.e., selected name should be there even after payment is added into db
I am not sure what you want but if filling up the select with options dynamically (with some js variables) is what you want then you can try something like.
$("#id_something").empty();
$("#id_something").append('<option selected="selected" value='+somejsvariable+'>'+someotherjsvariable+'</option>');
Hope it helps.
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 a html form which includes a dynamically created dorpdown list. The dropdown list contains the names of newsletters which are stored in my MySQL database. What I want the dropdown list to do is: When I select a newsletter an other php script will activate which will take the data from the newsletter in my DB and writes it to a .txt file. The codes I currently have is:
The dropdown list:
<?php
echo "<select id=\"NieuwsbriefSelect\" name=\"show\">";
echo "<option size =30 selected>Select</option>";
if(mysql_num_rows($sql_result))
{
while($row = mysql_fetch_assoc($sql_result))
{
echo "<option value=\"$row[Titel]\">$row[Titel]</option>";
}
}
else {
echo "<option>No Names Present</option>";
}
?>
And the write script:
<?php
$title = $_REQUEST["show"];
mysql_connect('localhost','root','root');
mysql_select_db('NAW') or die (mysql_error());
$strSQL = "SELECT Content from NAW.Mail where Titel = '$title' ";
$sql_result = mysql_query($strSQL);
$row = mysql_fetch_assoc($sql_result);
$file = 'nieuwsbrief.txt';
$current = $row["Content"];
file_put_contents($file, $current);
?>
I do not want the page to redirect to the write script but just to execute it (I hope you get this^^). Is this possible using the HTML onChange Event or do I have to use javascript? Any help would be great and if you have a question about my code just ask in the comments!
NOTE!
I know I shouldn't be using Mysql_* and That I am vulnerable to sql injection but that is not the point.
You need to define a onchange event on your SELECT option and inside this onchange event, you can redirect to another page with selected item OR do an AJAX call to another PHP script
Unfortunately what you are asking is not possible without JavaScript. PHP is a server side language and therefore cannot be run, without a call from the client-side browser. You're best bet would be to use ajax in conjunction with the JavaScript onchange event. When the change event occurs, fire an ajax call off to the server to run the script with the selected option. This is the only way to do what you're asking without a page reload or redirect.