Creating dynamic forms based on the values selected - javascript

I'd like to create a HTML form as follows:
<form action="<?php print($action); ?>" method="post">
<label for="possibilities">Possibilites</label>
<select name="possibility" id="possibility">
<?php foreach ($possibilites as $possibility): ?>
<option value="<?php print($possibility['id']); ?>"><?php
print($possibility['name']); ?></option>
<?php endforeach; ?>
</select>
<rest>The rest of the form</rest>
</form>
When the user selects a certain value from the options menu,
the rest of the form will be generated (instead of <rest>The rest of the form</rest>)
This page accepts a lot of PHP variables that will be used in the rest of the form.
How would you generate the rest of the form based on the value selected from the options?
The rest of the form will accept lots of PHP variables in various input elements generated dynamically. The user should have the possibility to switch between various rests (<rest> ... </rest> until he submits the completed form. The code should not open security holes.
Which approach would you choose and why? (Javascript with loading partial HTML files? Building various DOM trees (with PHP variables in it) for the <rest>...</rest>s or some approach from PHP code)?

create an additional div or any other html element where form needs to be displayed
<div class="formGenerated"></div>
Then in javascript
change event helps to know when any of the option is selected
$(document).ready(function() {
$('#possibility').on('change', function() {
var selectedVal = $('#possibility').val();//value of the option selected
$.ajax({
url:'multipleForms.php',
type:'POST',
dataType:'json',
data:{name:selectedVal},
success:function(resp){
$('.formGenerated').html(resp);
}
});
});
});
// multipleForms.php
<?php
$name = $_POST['name'];
if($name == 'x'){
$x = 'your form goes here';
echo json_encode($x);
}
//similarly for other conditions
?>
Hope this might help you.

With jquery tho following code would be an option:
$(document).ready(function() {
$('#selectId').on('change', function() {
$('#restDivId').load('partialHtmlPage.php?value=' + $('#selectId').val());
});
});

Building various DOM trees is the faster choice. And there is no better or more secure choice actually, both are the same if we're talking security...

Use document fragment and dom manipulation to dynamically update your markup. It is fast enough and completely client side. In respect to the use of jQuery, I would rather be framework agnostic at first unless you need some specific options provided by said frameworks.
Doc:
http://www.w3.org/TR/DOM-Level-3-Core/core.html
http://www.quirksmode.org/dom/intro.html
http://jsperf.com/jquery-dom-fragment-vs-createdocumentfragment/2

To me it would really depend on a few things:
How many additional form elements are you going to need to display?
Do you need record the steps in filling out the form on the server side in some manner?
Do you need to evaluate the data submitted in the form along with data only available on the server in order to determine what next form components to show?
If you only have a few different form options and addining in the DOM as hidden elements on page download does not add what you deem to be unacceptable incremental page download times, you may strongly consider a javascript only solution to hide/show form elements based on your desired logic. If you answered yes to either of other items, and assuming you want to do all this without a page reload, then you would need to use AJAX methodology.

Related

Showing a Wordpress Database custom table row column value from the database on button click

I have added a custom table to the WordPress database. In addition to this, I have created a shortcode to be able to attach this to specific pages on my WordPress website. Table has two columns, ID and coupon_code.
The custom table is used to store coupon codes, and I need to be able to display the first row column value (coupon_code = INSERT NUMBER) from this table on a click event of a button.
function coupon_codes() {
?>
<button class="reveal_coupon" onclick="reveal_coupon()">CLICK TO REVEAL
COUPON CODE</button>
<div class="coupon"></div>
<?php
global $wpdb;
$result = $wpdb->get_results ( "SELECT * FROM coupon_codes LIMIT 1"
);
foreach ( $result as $print ) {
echo $print->coupon_code;
}
}
add_shortcode( 'coupon_codes' , 'coupon_codes' );
I do understand that in order to achieve this, I need to move the PHP code into a separate PHP file, because this code is only run server-side and this can be achieved only if I run the file on a click event. That part I understand.
I cannot display the row value unless called with a click event. Which is why I think JS / jQuery would work for this case, but I am unable to figure out the script accurately to make it work.
You seem to have a misunderstanding of how the PHP and HTML/JS/CSS interact.
If you can't display the row value until a button click (which I'm assuming you have your <button class="reveal_coupon"... element for), you're almost on the right track here. Under the assumption that your <div class="coupon"></div> coupon is specifically to hold the coupon data output from your PHP script, there's a few observations I'll make:
You're echoing your data outside of your coupon div, so whatever you output won't necessarily be subject to the CSS styling and JS logic you've implented for this element. Move the PHP code between the <div class="coupon"> and </div>.
In order to achieve your desired functionality, you'll need to add your relevant JavaScript and CSS styles. The most maintainable way would be to break out your JS and CSS into separate files and utilize the wp_enqueue_script and wp_enqueue_style functions in a new function/enqueue hooking pair to insert references to these files in the DOM at the appropriate times:
add_action ( 'wp_enqueue_scripts', 'coupon_enqueue_scripts' );
function coupon_enqueue_scripts() {
wp_enqueue_script("coupon", "coupon.js");
}
add_action ( 'wp_enqueue_styles', 'coupon_enqueue_styles' );
function coupon_enqueue_styles() {
wp_enqueue_style("coupon", "coupon.css");
}
Within these files, you'd want to add (a) Javascript logic to implement the reveal_coupon() function referenced in your current HTML output, and (b) CSS styling to initially hide the coupon codes.

WordPress - Custom Form for custom post types in back-end

I am creating an eSports website and I want to create a bracket generator for each tournament. What I essentialy want to achieve is a custom form for each of the tournaments (post types). In that form I want to have an ability to choose how many rounds should this tournament have and be able to assign teams to any of the parts of the bracket.
I thought about doing this with custom fields but I doubt that they can be dynamic (for example, the amount of fields should increase if the tournament has more rounds than by default). They should also be simple to use for my client, so he shouldn't have to add custom fields manualy.
I decided to create a meta box with a form inside of it:
function add_meta_boxes() {
add_meta_box('peterworks-tournament-bracket', 'Peterworks Tournament Bracket', 'pworks_bracket', 'tournaments', 'side');
}
function pworks_bracket() {
?>
<form method="POST">
<input type="text" name="test_it" value="test" />
</form>
<?php
}
Then I tested if data from that form is reachable inside the wp_insert_post_data filter. It is:
function modify_post_title( $data , $postarr )
{
$data['post_title'] = $_POST['test_it'];
return $data;
}
This succesfully changes the title of a post to the value of that form's input. It means that I can create a custom form and make it dynamic with JavaScript.
My question is - is this approach correct? What are the potential problems I might be facing using this technique? Is there a better/easier way to do this?

Dropdown values disappear in an AJAX-based jQuery element

I am growing quite fond using AJAX, JSON, and jQuery. I am coding from scratch an application to replace a previous application that is flawed.
Although I am progressing and getting better using the AJAX method, I am coming across various issues that I want to correct, so that my replacement application is flawless.
My application uses AJAX to call PHP scripts. It returns JSON that I use to populate certain dropdowns for the user to select.
For the most part, the application does what it is supposed to do. The many dropdowns populate with the parsed JSON data. The user can select 1 or more dropdowns which will then fire a SEARCH query that will return data.
The issue appears to happen when the data-set from the previous search is large. I'm talking barely thousands. When I click on the dropdown to conduct a new search, the dropdown (that was previously populating the JSON data) is now blank.
It doesn't do it all the time. It seems this issue arises when the initial search returns a large data set. I cannot be for sure.
Here is the html within my file called bpSearch.php: (just two of my dropdowns)
<div class="input-group">
<span class="input-group-addon">Sales Rep</span>
<select class="form-control" id="salesRep" name="salesRep">
<option value=""></option>
</select>
</div>
<div class="input-group">
<span class="input-group-addon">Services</span>
<select class="form-control" id="service" name="service">
<option value=""></option>
</select>
</div>
There are a few more dropdowns. I only listed 2.
Here is the javascript (also within the same file, bpSearch.php) that populates the dropdowns via AJAX and JSON:
<script type="text/javascript">
// populates the dropdown id #salesRep
$.getJSON( "api/reps.php", function( data )
{
$.each(data, function(index, item)
{
$('<option>').
attr('value', item.fullname).
text(item.fullname).
appendTo($('#salesRep'));
});
});
// populates the dropdown id #service
$.getJSON( "api/services.php", function( data )
{
$.each(data, function(index, item)
{
$('<option>').
attr('value', item.service).
text(item.service).
appendTo($('#service'));
});
});
</script>
Here is the PHP called reps.php. This returns the JSON data for the #service dropdown:
<?php
if ($result =
mysqli_query($dbc, "SELECT DISTINCT(service)
FROM services_imp ORDER BY service"))
{
$out = array();
while ($row = $result->fetch_assoc())
{
$out[] = $row;
}
echo json_encode($out);
mysqli_free_result($result);
}
?>
At this point, I don't think I need to show the code for reps.php. It pretty much looks exactly the same as the code for services.php, except of course for the names of the fields that I search in the query.
With all the code above, I can populate the dropdowns as stated. But, as I also previously stated, sometimes the dropdown values disappear after conducting a search. This seems to always happen when the data-set is large.
Here is what the services dropdown looks like when it is working:
And here is what it looks like after I conduct a search that returns a larger data-set:
I do not understand why this is happening. What might be causing it?
It is a good practice to ensure that the dropdowns are loaded in DOM ready event
$(function()
{
//AJAX call for loading dropdowns
})
Please make sure first that the calls are made in DOM ready event.
The following code disables the dropdown when the AJAX function is called and enables it when the data is fully loaded. Execution starts when the page is fully loaded and I reduced your AJAX calls to one generic function that accepts an element and a uri as input. This function also makes a clone of the select. Appending the new options in memory and when the list is build the original select is replaced with the cloned one. This should enhance the browser performance.
function loadDataAndAppendToSelect(select, uri)
{
$(select).prop('disabled', true); //disable
// populates the dropdown id
$.getJSON( uri, function( data )
{
var tempElement = $(select).clone();
$.each(data, function(index, item)
{
$('<option>').
attr('value', item.fullname).
text(item.fullname).
appendTo(tempElement);
});
$(select).replaceWith(tempElement);
$(select).prop('disabled', false); //enable
});
}
$(document).ready(function(){
loadDataAndAppendToSelect('#salesRep', 'api/reps.php');
loadDataAndAppendToSelect('#service', 'api/services.php');
});

how to get current selected from <select> and on every change in selected

i was trying to make a dynamic where the selected option was supposed to be caught in a variable for php as i would use it as a condition to be put in a where clause for mysql. and when a user selects another option the of another tag would change
<form method="GET" action="">
<select name="docSpec" id="docSpec">
<?php
$docSpecQuery = "select DISTINCT specialty from doctors"; // i was going to put a where condition here so i could only project names of the doctor with the selected specialty.
$docquery = "select doctorName from doctors";
$docSpec = mysqli_query($conn,$docSpecQuery);
$docresult = mysqli_query($conn,$docquery);
//this php block is for my options, i used a loop
while ($row = mysqli_fetch_row($docSpec))
{
echo "<option value='$row[0]'>$row[0]</option>";
}
unset($row);
?>
</select>
<script type="text/javascript">
$('#docSpec').on("change",function(){
var option = $("option:selected",this).val();
alert(option);
});
</script>
</form>
i hope i was clear enough i will be waiting if you want to clarify some things in my code.
tell me if you need another parts of my code. please i need help
PHP is executed on the server, which means that by the time you print the <select> you run the jQuery code you can't affect the mysql query directly. You can however move the query to another script, and target it with an ajax call that returns the select and options or, ideally, the dataset so you can create it programmatically.
Your php script will do the same as it does right now but fetch the value from the url for the conditional query. For instance, you could have this php at mysite.com/select.php and pass the variable gynecologist like so mysite.com/select.php?spec=gynecologist then read it with $_GET['spec'] and use it in the query.
In your javascript, you'll get that html by calling something like:
$('#docSpec').on("change",function(){
$.get( "mysite.com/select.php?spec="+$(this).find("option:selected"),
function( data ) {
//data contains the output for the php file, update the dom
//with it or whatever
});
});

cakephp - Javascript

We are working on an application using the CakePHP framework
Basically, its a questionnaire application and it has a few dependant questions, i.e. based on a response to a specific question, it needs to show or hide the next one
For e.g.
Question: Are you married? Yes/No
If the user selects Yes, then using javascript the next question gets displayed for user input
Question: Spouse's name
Saving this information is fine, but when editing, when populating the form, we would want to be able to display the fields for which user has inputted data - in this case, it needs to show the field that has the spouse's name
Since by default we are hiding the spouse name field, when editing, it doesn’t display the field, even though there is a value to it
Is there some way that CakePHP can handle this or does it require us to write some javascript to take care of this?
Thanks in advance.
CakePHP does not manage this for you. While CakePHP is very powerful and a great framework, it will not write this kind of logic for you. You must write it.
I would suggest making the EDIT screen different from the ADD screen. Build the list of values from the database and display the fields that have values (and include any empty fields that should require values).
Keep in mind reusable does not necessarily mean that all CRUD actions fit into the same view.
Like others I advise you use differents EDIT and ADD screens.
But you can try make it with Javascript like this:
<script>
function enableDisableField(targetFieldId){
var targetField = document.getElementById(targetFieldId);
var checkbox = event.target;
console.log(checkbox.checked);
if (checkbox.checked){
targetField.disabled = false;
targetField.value = "empyt";
}else{
targetField.disabled = true;
targetField.value = "empyt";
}
}
</script>
<label><input type="checkbox" onchange="enableDisableField('married')"/> Merried</label>
<?= $this->Form->input('married',['label' => false, 'disabled']); ?>
It works well for ADD, but if you and EDIT you have to change de disable value according a field value:
<label><input type="checkbox" onchange="enableDisableField('married')"/> Merried</label>
<?= $this->Form->input('married',['label' => false, !isset($user->married) ? 'disabled' : '' ]); ?>

Categories

Resources