I have an apparel ordering form on a page. I want to "swap-out" that form with another one when I select an option from a drop-down list/menu. Ajax maybe? PHP include()? The options in the drop-down would select different forms already created as templates in another directory and render it in place of the other form.
I just want one form showing at a time. Thanks! :)
Don't put too many hidden forms if you can. It's just bad design, especially regarding performance. Your best bet is to:
Create some PHP files with a form inside each
Use an AJAX request to communicate if the condition is met
If you like stuffing up things in one file try passing a unique parameter with AJAX to the PHP file and check its value to decide which form to load.
Example:
var xhr = new XMLhttpRequest();
formID = (condition) ? 1 : 2; // etc
//^^ This one line above means:
if (condition) {
formID = 1;
}
else {
formID = 2;
}
...
// GET request
xhr.open("GET", "forms.php?formID=" + formID);
// POST request
xhr.send("formID=" + formID);
In PHP:
<?php
if (isset($_POST["formID"]) && $_POST["formID"] === 1):
?>
<form id = "1"></form>
<?php
else:
?>
<form id = "2"></form>
<?php
endif;
?>
[EDIT]:
If you want to have each form in a different file then the above code will be:
<form>...</form> // No PHP necessary
In JavaScript use xhttp.send("") without putting any values (only if the forms are in different files).
Related
I'm new to Yii framework and I'm designing a form (I'm using create form) to create a row in database.
Let me explain about the scenario succintly, so that I can make it clear for what I want-
I have 10 fields in this form. Out of this 10 fields, five fields change dynamically.
I created two div's basically div A and div B and repeated the fields as required for the two cases.
Say some fields which are textfields in div A will be dropdownlists in div B.
<div id="A">
<?php echo $form->labelEx($model,'selectionList'); ?>
<?php echo $form->textArea($model,'selectionList',array('rows'=>6, 'cols'=>50)); ?>
<?php echo $form->error($model,'selectionList'); ?>
</div>
<div id="B">
<?php echo $form->labelEx($model,'selectionList'); ?>
<?php echo $form->dropdownList($model,'selectionList',array('rows'=>6, 'cols'=>50)); ?>
<?php echo $form->error($model,'selectionList'); ?>
</div>
I have two radiobuttons say Single and Multi. When I select Single radiobutton, div A should be considered and div B discarded and when I select Multi, vice versa should happen.
So, is this the right way to change the form fields dynamically. Or else how can I do this using Ajax validation.
Not so related to question:
1) You are using same name for all fields, so only last one will be submitted (check generated html, name is MyModel[selectionList] and not MyModel[][selectionList]
2) You will have lots of problems with Ajax validation and dynamic fields (generated via js), since CActiveForm will generate js code via php.
Related to question:
3) To use one or another field, i suggest you to have two separate field names and just hide with js/css one, that is not needed right now. After submitting, just check value of radio button and decide what fields will be saved.
To validate these inputs, you have to use model scenarios (will define in rules what to validate and what not to):
$model = MyModel();
if ($_POST['C'] == 'multi') {
$model->scenario = 'validateOnlyFirstField';
} else {
$model->scenario = 'validateOnlySecondField';
}
Also you can use second CActiveForm.validate() parameter to define what attributes to validate.
I have a Jscript Query.
I have done a bit of reading and found out that AJAX is just a side server for a lfash script that can be used on Linux with php. (please correct me if I have interperated that wrong)
I have no knowledge on how scripts work so this is new, I have tried a couple of different tries but no luck.
I have one drop down box (Box1) (populated from Database)
I have another box (Box2) for a calculation to insert into my database for other uses on ohter parts of hte site.
I need the Box2 to change the figure when someone changes Box1 dropdown before hitting the submit button.
I think because I have the calcualtion this is getting me stuck... Code is as below... Can someone please help me figure out (I think I need some form of Script to do this.) the answer...
Box1
<td><p>selection 1</p>
<select id="t1_type" name="t1_type">
<?php $result = mysql_query("SELECT * FROM `t2` ORDER BY t2_value");
while($valuerow = mysql_fetch_array($result)){
echo '<option value="'.$valuerow['t2_name'].'">'.$valuerow['t2_name'].'</option>'; } ?>
Box2
<input name="t1_value" id="t1_value" value="
<?php
$var1 = $row_value['t2_value'];
$var2 = $row_dropdown['t1_number'];
$total = round ($var2 * $var1);
echo "" . $total . "";
?>" />
I hope this is all the code you need, (Let me know if more required)
What it needs to do is show new calculation whenever someone changes the box1 option BEFORE the submit button is clicked, so it submits the correct calculation to the database for future use.
I think it would need pretty much "t2_value" from box2 to change when ever "t2_name changed from box1.
And once again the best link to learn about the solution. (Learnt about Joins now from my last question!! Almost a intermediate user. ;-) )
Edit :
I saw that your second box was a textbox I believe, if thats the problem then you should do something like this
<select id="t1_type" name="t1_type" onchange="change(this);">
<?php
$result = mysql_query("SELECT * FROM `t2` ORDER BY t2_value");
while($valuerow = mysql_fetch_array($result))
{
echo '<option value="'.$valuerow['t2_name'].'">'.$valuerow['t2_name'].'</option>';
}
?>
</select>
This defines your <select> box like you did in your question.
Add an onChange event into your first <select> and then create a function to handle to onChange event. An onChange event fires whenever the user changes the item in the <select> element.
Javascript :
( put this part of the code above the </head> )
<script language="javascript" type="text/javascript">
function change(element)
{
// do here whatever you want
// you can change the value of the <input> box with :
// document.getElementById(element.id).value = your_value
// If you want to see if this part works, then try adding this :
// alert("It works!");
// If you want to get the text of the item which has been selected in Box1 use :
// $("#t1_type option:selected").text();
}
</script>
Note: because PHP is server side, you can't update your Box2 dynamically without a page refresh, Javascript however is Client Side and CAN do this.
Note : the $("#t1_type option:selected").text(); code requires you to include the jQuery library into your script. Be sure to convert this variable to a float, int or double if you want to calculate with it, else the outcome will give NaN (Not a Number)
Tutorial on including jQuery Libary :
http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery
If you're new to JavaScript, you should try some tutorials. The ones at w3Schools.com helpt me alot, but some people say they're not always correct, but anyhow, read some stuff about Javascript to actually know what you are doing, instead of copypasting code :)
I have ran out of ideas for this assignment for a class. I had to create two PHP forms using PHP_SELF and I am suppose to use javascript or jquery to toggle between the forms. I tried using
Form 1
Form 2
This does work on changing the forms, however when I hit the submit button the form it goes back to form 1 and doesn't display the results. The thing I have to figure out is after the form has been submitted using PHP_SELF, how to get it to stay on that form to show the results generated by the server.
You'll need to use something like this
if($_POST){
//display success message here
}else{
//display form here
}
You could add a hidden field to the form called formId and have PHP echo it back, so that you know from Javascript which form's results you're reading:
<?php
...
if (isset($_POST['formId']))
{
$show = 'form1' == $_POST['formId'] ? 'form1' : 'form2';
$hide = 'form1' == $_POST['formId'] ? 'form2' : 'form1';
// This PHP must be inside the Javascript section of the page, at end.
print <<<SETVISIBILITY
\$('#$show').style.display = 'block'; // Should be unnecessary (?)
\$('#$hide').style.display = 'hidden';
SETVISIBILITY;
}
?>
Or you can do the SUBMIT and result display all in jQuery, so that you needn't reload the page losing your form visibilities.
Hi I'm trying to create a form that is pre-populated partially by form on the page before. This information is then posted to this new page which is then populated into the form on that page ready to be submitted to a database.
I'm not a developer so I'm a little out of my depth here but this is what I've got so far..
<?php
$amount = $_GET['text-386'];
$covermultiple = $_GET['radio-30'];
$coverdobd = $_GET['d-o-b-d'];
$coverdobm = $_GET['d-o-b-m'];
$coverdoby = $_GET['d-o-b-y'];
?>
<script type="text/javascript">
document.getElementById('text-386').value = "<?=$amount ?>";
document.getElementByName('radio-30').checked = "checked";
document.getElementById('d-o-b-d').value = "<?=$coverdobd ?>";
document.getElementById('d-o-b-m').value = "<?=$coverdobm ?>";
document.getElementById('d-o-b-y').value = "<?=$coverdoby ?>";
</script>
I'm getting the values out of the URL ok and can echo these out on the page fine, I've even managed to get text-386 appearing in the right place.. so thats one down! The problem is the other elements are a radio button with two options (radio-30) and a 3 select boxes with the days, months and year of a persons d-o-b. These two bits are populating.
So in a nutshell..
How can I use javascript (if that is the right way) alongside php to populate the radio and select tags on this form using information in the url? In a preferably straight forward way as possible?
The url if it helps is..
http://localhost/datacapture/form-page/radio-30=Just+for+me&text-386=%C2%A340%2C000&d-o-b-d=11&d-o-b-m=05&d-o-b-y=1977
Thats obviously on the local build I'm using so that URL wouldn't work for you. I can see when googling lots of help posting information using radio/select etc but I want the opposite, how do you populate these from a url?
Any help would be a lifesaver
I would just use an if statement.
if( $covermultiple == "Just for me" ) {
// Echo the field here
echo "<input type='radio' name='radio-30' value='Just for me' checked />";
}
else {
// Check for the next case
}
Put this block right where you want the radio buttons to be.
I think something like that will work fine. I don't think you really need javascript in this case unless you really want to use it.
Im not 100% I have an answer, but I cant find comment anywhere so I will joust post here.
You cant access PHP variables from Javascript. PHP is running on the server, and Javascript is inside users browser.
Javascript cant get $_GET and $_POST variables like PHP.
Now what you can do is this, with JavaScript you can get document.location string that holds your current URL. And you can brake that URL into parts. To do that use this function:
<script>
var $_GET = {};
document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function () {
function decode(s) {
return decodeURIComponent(s.split("+").join(" "));
}
$_GET[decode(arguments[1])] = decode(arguments[2]);
});
alert($_GET['someVar']); // This will alert content of someVar
Now you can use $_GET['vars'] to get your URL vars.
And then you dont use PHP to echo variable content, you joust prepare your URL so it holds variables you want to insert into your form.
So you do something like this:
<script type="text/javascript">
document.getElementById('text-386').value = $_GET['urlVar'];
document.getElementByName('radio-30').checked = "checked";
document.getElementById('d-o-b-d').value = $_GET['urlVar'];
document.getElementById('d-o-b-m').value = $_GET['urlVar'];
document.getElementById('d-o-b-y').value = $_GET['urlVar'];
</script>
So as you can see, JavaScript takes variables from URL, using function $_GET you wrote and it dosent needs PHP. And you can use PHP to generate URLs you need, so they contain variables you can get using $_GET javascript function.
Hope this answers your question.
I have an HTML form which contains a drop down, a tinyMCE textarea, and a save button.
The dropdown is used to select a file to edit.
I load up the required file into the tinyMCE editor by making an ajax call when the jquery change() event is triggered from the dropdown. That works fine.
The problem I'm having is saving the file off. I am trying to do it by posting the form off to another php page which will write to the file and then send us back to the main page.
This is the php code within my writeFile.php page:
<?php
session_start();
if (!isset($_SESSION['id'])) {
header ('Location: index.php?error=0');
}
else {
if (isset($_POST['save'])) {
$text = $_POST['mceContent'];
$index = $_POST['files']; // << PROBLEM LINE!
$array = array('homeText.txt', 'anotherText.txt');
$fileName = $array[$index];
$path = '../txt/'.$fileName;
$length = strlen($text);
echo "INDEX: $index"; // TO TEST THE INDEX VARIABLE.
$fh = fopen($text,'w',true);
fwrite($fh,$text,$length) or die('Could not write');
fclose($fh);
header ('Location: admin.php');
}
}
?>
The $index variable is meant to be the selected index in the dropdown, however it is posted by my form as the selected string value in the dropdown.
I can think of three solutions (ordered from least likely to work to most likely)
There is some way to get the index from that php post?
I can make a change in the HTML form/select tag to tell it to post the index and not the value string
I change it to a jquery event, with the on-click, and pass in the index to a post manually with xhr.
If someone could help me with implementing one of these method that would be great.
If you have your own, better solution I would be happy to hear that as well.
Also note that I can't build the path from the value string, because my dropdown uses descriptive strings, not actual file names.
Thanks in advance, bear in mind I'm new to php and especially jquery.
I am not sure why you can't use the value attribute - the descriptive string would be the text portion of the option element, the filename to save could be the value:
<option value="path/to/file_to_save.php">Descriptive file name</option>
Doing it that way, the user sees the descriptive text, the server gets a useful bit of information it needs when the form posts.
If that is not an option, you could add an onSubmit event to the form in which you pass the selectedIndex property to a hidden form field, then return true and let the form submit normally.
Form snippet
<form onsubmit="return beforeSubmit()">
<input type="hidden" name="file_index" value="" id="file_index_fld" />
<select id="file_name_dropdown">
<option>...</option>
Javascript snippet
var beforeSubmit = function () {
$('#file_index_fld').val($('#file_name_dropdown').attr("selectedIndex"));
return true;
}
... now in PHP's $_POST variable, you'll see $_POST['file_index'] contains the selectedIndex of the select element.
The long and short of it is that the selectedIndex property is a DOM item and not part of the POST data. No matter what, you are either going to have to intervene with javascript to add the data to POST, or modify your option elements to pass the desired data. I would always lean toward the former route as it is less complex.
Another option I can think of: Before posting, catch the new index in the change-event and write it to a hidden input-field of your form. After that, you can serialize and post it with jQuery.