PHP/JSON Array display values based on dropdown selection - php

Having a difficult time trying to suss this out. I've searched through, but I'm not sure if the phrase I'm using to search is correct or not.
I have a JSON file that I'm using to bring in an array of data from an outside source. Using PHP, I decode the contents. I've created a dropdown box that will display the keys, but what I'm looking to do now is dynamically populate a printout with the different values that the keys are attached to based on what the select box has selected.
<?php
// JSON string
$json = file_get_contents("showrace.json");
$races = json_decode($json, true);
?>
<select id="raceSelect">
<option value="select one" selected>Select One</option>
<?php foreach($races as $key => $value) { ?>
<option value="<?php echo $key ?>"><?php echo $value['race'] ?></option>
<?php } ?>
</select>
<div id="template">
Str Plus: # Dex Plus: # Wis Plus: # Int Plus: #<br>
</div>
And here is a sample of what the JSON file looks like:
{
"Ithorian":{"price":0,"wis":3,"str":2,"lck":0,"int":2,"frc":0,"dex":-2,"con":2,"cha":-3,"app":"No","hp":1200,"ac":0,"race":"Ithorian","lang":"ithorian"},
"Weequay":{"price":1000,"wis":-2,"str":3,"lck":0,"int":-2,"frc":0,"dex":0,"con":2,"cha":-3,"app":"No","hp":1350,"ac":0,"race":"Weequay","lang":"weequay"}
}
In the first snippet, the #'s in the template div will be outputs for the JSON values such as "str" and "dex" and such. While I was able to find out how to set the select to draw in the keys from the JSON, I am baffled at how to populate the template portion with the corresponding values, based off of the selected item.
Thanks in advance!

This may help you get started, as it is not fully fleshed out for everything. But it covers some basics you could use.
First off you would want an onchange handler in your jquery. This will fire off everytime someone changes their choice with the :
$("#raceSelect").change(function(e){
// magic will go here (see further below)
});
// or
$("form").on("change","#raceSelect",function(e){
// magic will go here (see further below)
});
Next up you would want to have access to all that json data in your jquery area to use for displaying those values based on what they chose:
<script>
// define this in your php page output near the top
// or within your jquery .ready block
var jsonData = <?PHP echo $json;?>;
</script>
Now you are ready to do some of the magic with the onchange. Accessing the right array in the jsonData, with the id chosen, you can swap out spans and divs to your hearts content. A combined example is as follows:
<?PHP
// your php script
$json = file_get_contents("showrace.json");
$races = json_decode($json, true);
?>
<!-- your form here as you have it in your example -->
<div id="template">
Str Plus: <span id="dat_str">#</span> Dex Plus: # Wis Plus: # Int Plus: #<br>
</div>
<script>
$( document ).ready(function() {
// this is your jquery .ready block
var jsonData = <?PHP echo $json;?>;
$("form").on("change","#raceSelect",function(e){
var race = $(this).val();
$("#dat_str").html( jsonData[race].str );
// you can set the dex, and wiz, etc as well
// following the same format to assign
});
});
</script>
Disclaimer: I hand typed this out, and didn't vett or test it. Its purely an example of pieces that should hopefully help you out.

you can do it using JS
var raceSelect = $('#raceSelect').find(":selected").text();
and check out this link on how te select from json
then print what you want
select from json

Related

Populate a drop-down list depending on what is selected from another drop-down list from two variables PHP

I have a question on how to populate a drop-down list depending on the value that is selected in another drop-down list.
I'm working with an MVC pattern and when the view loads, it already brings me two variables with the values I need. What are $tipohardware and $tiposoftware.
So I wouldn't need to call a .php file again to get the data, because it's already loaded.
My static drop-down list is:
<select id="producto" class="form-control" required>
<option value="">Seleccionar..</option>
<option value="1">Hardware</option>
<option value="2">Software</option>
</select>
And the dynamic drop-down list I want to populate depending on what is selected in the drop-down list "producto" is:
<select id="tipoproducto" name="tipoproducto" class="form-control">
</select>
I already have two variables that have the data of the tables, "tipo_hardware" and "tipo_software". What are $tipohardware and $tiposoftware.
So, for example, if I select the "Hardware" option in the drop-down list, the second drop-down list should be filled with the data of the variable $tipohardware.
On the other hand, if I select "Software" the drop-down list should be populate with the values of the variable $tiposoftware.
Here's my controller if you needed to.
<?php
namespace app\controllers;
use \app\models\Hardware;
use app\models\Software;
use app\models\TipoHardware;
use app\models\TipoSoftware;
use \Controller;
use \Response;
class IngresarProductoController extends Controller
{
public function actionIndex()
{
$softwares = Software::all();
$hardwares = Hardware::all();
$tiposoftware = TipoSoftware::all();
$tipohardware = TipoHardware::all();
Response::render("ingresarProducto", ["hardwares" => $hardwares,
"softwares" => $softwares, "tipohardware" => $tipohardware,
"tiposoftware" => $tiposoftware]);
}
}
I think I should call a php code in a javascript onchange function like:
$("#producto").on("change",function){
<?php
foreach($tipohardware as $tipohard) {
?>
<option value="<?php echo $tipohard->idtipo_hardware ?>"><?php echo
$tipohard->nombre_tipo_hardwarecol ?></option>
<?php
}
?>
}
});
But I dont know how I can continue with that,
Thanks for the help!
You are mixing frontend script with backend script, which does not work. Backend will build the entire page before the frontend starts doing it's thing. PHP creates the DOM and JavaScript manipulates the DOM after PHP spits it out. That is why your jQuery does not work/update.
For example, if you do this:
$('.button').on('click',function(){
var whatever = <?php echo rand() ?>;
alert('This value is'+whatever);
});
It will run the php first so you will end up with the random number off the bat:
$('.button').on('click',function(){
var whatever = 3241231;
alert('This value is'+whatever);
});
No matter how many times you click the button element, it will always say 3241231 until you reload the page when PHP will run the rand() function at load.
To make it load in real time, you need to create an ajax listener to receive a value from the target, send to the backend PHP, then when that backend page responds, you place the response back into your currently loaded page, altering the DOM.
A simple example would be:
/index.php
<?php
# Create the back end to listen for your front end ajax
if(!empty($_POST['test'])) {
# Do your code here to send back.
$rand = rand();
die('Ajax done! Here is a random number: '.$rand);
}
?>
<!-- CLICK ELEMENT -->
<div id="button">CLICK</div>
<!-- PLACEMENT ELEMENT -->
<div id="response"></div>
<script>
$(function(){
// When you click the div
$('#button').on('click',function(){
// Fire the ajax to the same page (you may want to do a
// different page in production). Note, I am referencing a new instance of
// of index.php in the background and sending $_POST['test'] = true as noted
// in the data section of the ajax below.
$.ajax({
'url': '/index.php',
'type': 'post',
// Send the data from the click or whatever
'data': {
'test':true
},
// If there are no server errors,
'success': function(response){
// place the phrase 'Ajax done! Here is a random number: 123124'
// back into the placement div
$('#response').text(response);
}
});
});
});
</script>
In this example, the random number will change each click of the div. Anyway hope this example was helpful.

jQuery UI Sortable - how to set data, based on the got data

I'm using jQuery UI Sortable to let the user sort on a queried data, and saving the sorted data into another table. I'm putting the changed order into a hidden field and saving the data.
HTML
<?php
// $queried_data is queried in LIFO order from a table, suppose an order like: 1,2,3,4
$saved_data = '2,3,4,1'; //queried as a string from another table
?>
<div class="data-sorter">
<ul id="sortable-data">
<?php foreach($queried_data as $key => $value) : ?>
<li id="<?php echo $value->ID; ?>">
<?php echo $value->title; ?>
</li>
<?php endforeach; ?>
</ul>
<!-- HIDDEN FIELD: putting saved data here, and updating according to the changed data, and finally saving as a comma-separated string -->
<input type="hidden" class="data-sorted" value="<?php echo $saved_data; ?>">
</div>
JAVASCRIPTS
jQuery( document ).ready(function($) {
"use strict";
var sortable_data = $( "#sortable-data" );
sortable_data.sortable({
update: function( event, ui ) {
var list_id = this.id,
item_moved = ui.item.attr('id'),
order = $(this).sortable('toArray'),
positions = order.join(',');
var hidden_field = $('#'+ list_id).parent().find('.data-sorted');
hidden_field.val(positions).trigger('change');
}
});
sortable_data.disableSelection();
});
But as you can see the $queried_data ≠ $saved_data. So, after refresh, the PHP loop is putting things into original order. I'm okay with that. I just need to manipulate the DOM using the jQuery UI sortable so that they appear according to the order, got from the $saved_data.
I need a way to trigger jQuery UI sortable (I did in line#6 in Javascripts) as well as set the value according to the $saved_data (that available as a value of the hidden field .data-sorted).
I understand that I need the Sortatble create event, but I can't figure out, how.
Check this logic, should work. Considered that li id is the same as comma separated values.
On page load call function reorder() after sortable call.
$("#sortable-data").sortable({update: reorder});
function reorder()
{
orderArray = $('.data-sorted').val();
elementContainer = $("#sortable-data")
$.each(orderArray, function(key, val){
elementContainer.append($("li#"+val));
});
}

PHP - creating/calling JSON from Select Options

Getting down and dirty with javascript and JSON.
I want to store some html values inside a JSON array, so I can call them when needed (usually from some jquery event listener)
This beats constantly using $.ajax for client-to-server calls.
So, I have a <select> that has database populated options:
<select name="emailmsgid" id="emailmsgid">
<option value="0">------select a template-------</option>
<?php
$q = mysql_query("SELECT emailmsgid,emailmsgsubject,emailmsg_html FROM tbl_email_templates");
while ($r = mysql_fetch_array($q)){
$emailmsgid = $r['emailmsgid']; // int
$emailmsgsubject= $r['emailmsgsubject']; // short desc
$emailmsg_html = $r['emailmsg_html']; // usually html with images (save to json, somehow)
?>
<option value="<?=$emailmsgid;?>"><?=$emailmsgsubject;?></option>
<? } ?>
</select>
<br>
<textarea name="selectedmsg" id="selectedmsg"></textarea>
<script language="javascript" type="text/javascript">
$(document).ready(function(){
// populate the textarea above
$("#emailmsgid").change(function(){
var selectedID = $(this).val();
/* how to look into json here with selectedID */
$("#selectedmsg").val("whatever the json has saved for that emailmsgid");
});
});
</script>
This is what's missing above.
-Creating the json string, (from inside the php/mysql while statement), so the jquery below can reference the json, matching up the selectedID to what's inside json?
I do admit I am new to JSON, and this is a great way for me to learn how to work with it, as well as call the name/value pairs from jquery.
I'm hoping to save the emailmsg_html inside json, then load it into the textarea when I select it's matching emailmsgid in the select input.
(I'm basically working at eliminating any times my code needs to call the server, and seems this is the best route)
Have you tried using json_encode(): http://php.net/manual/en/function.json-encode.php
You can pass it objects, arrays, etc and it will convert them for you.
Extra Comment
Your code is pretty messy. Having MySQL requests in the middle of the HTML isn't great. You might want to do some research into MVC frameworking.
What I would do, to prevent various encoding and transport issues, is to place the html in hidden containers that you can access later:
<div style="display:none">
<?php while ($r = mysql_fetch_array($q)){ ?>
<div id="container_<?php echo $r['emailmsgid']; ?>">
<div class="description">
<?php echo $r['emailmsgsubject']; // short desc ?>
</div>
<div class="html">
<?php echo $r['emailmsg_html']; // usually html with images (save to json, somehow) ?>
</div>
<?php } ?>
</div>
Then your script would become:
$(document).ready(function(){
// populate the textarea above
$("#emailmsgid").change(function(){
var selectedID = $(this).val();
var msgHtml = $('#container_' + selectedID).find('.html').html(); // This line is how you get the html
$("#selectedmsg").val("whatever the json has saved for that emailmsgid");
});
});
</script>

how to store php object to access its data on click with javascript

I'm trying to figure out the least obtrusive and least computationally expensive way to store PHP objects coming from my MySQL database such that their data can be rendered by JavaScript on click by a user.
Currently, I'm storing the data as custom attributes on a button. But this generates a lot of code and I've heard is "slow". I'm wondering if I should JSON encode my PHP object, $items (see below), and how that JavaScript would then look. Note I'm using Codeigniter for the PHP so that's what up with the alternate foreach loop syntax.
Here's where I'm at so far with the HTML/PHP:
<img id="img"></img><a id="url"></a> <!--elements where data is rendered on click-->
<? foreach($items as $item):?>
<button data-id="<?=$item->id?>" data-url="<?=$item->url?>" data-img="<?=$item->img?>">click<?=$item->id?></button>
<?endforeach;?>
And here's my JS:
$(document.body).on('click', 'button', function(){
var $this=$(this), id=$this.data('id'), url=$this.data('url'), img=$this.data('img');
$('#img').attr('src', img);
$('#url').attr('href', url).html(url);
});
Most of my site's data is coming from PHP via MySQL and I've long been confused by the issue of when should I convert that data to a JavaScript array/JSON or not.
If you json_encode your $items array (assuming it only consists of data you will want in JS), you can assign this to a JS variable:
<script>var items = <?php echo json_encode($items); ?></script>
You can then remove the data-url and data-img attributes. Then, within your JS code:
var $this = $(this), id = $this.data('id'), url = items[id].url, img = items[id].img;
// the rest of your code
Edit: when you move the click handler in a separate file, you would get something like this:
function setup_click(items) {
var $img = $('#img'), $url = $('#url');
$('button').click(function(evt) {
var id = $(this).data('id'),
url = String(items[id].url),
img=String(items[id].img);
$url.attr('href', url).html(url);
$img.attr('src', img);
});
}
here's a JSfiddle showing off the javascript/JSON part: http://jsfiddle.net/fz5ZT/55/
To call this in one shot from your template:
<script src="[your ext script file path].js"></script>
<script>setup_click(<?php echo json_encode($items); ?>);</script>
Hope that helps :)

Changing contents of HTML select based on dropdown

I have a select item, that is filled with a list of files. This list of files is stored in a php variable.
I have another list of files, from another directory, stored in another variable.
I have a dropdown, with 2 options. When I change the dropdown, I want the items in the select to change to the file list associated with the item selected.
For example, my dropdown contains:
Misc Images
People
I have 2 variables, $misc and $people.
When Misc is selected, I want the select to contain all the images listed in $misc, and when the People option is selected I want the select to contain all the options listed in $people.
As far as looping through the php to generate all the items is fine, what I don't understand is how to do the javascript portion?
Thanks, and apologies for poor wording.
Try this code out.
PHP:
<?php
$miscArray = array("misc1", "misc2", "misc3");
$misc = implode(", ", $miscArray);
$peopleArray = array("people1", "people2", "people3");
$people = implode(", ", $peopleArray);
?>
HTML:
<form action="#">
<select id="fileCat">
<option id="misc">Misc</option>
<option id="miscData" style="display:none"><?php echo $misc ?></option>
<option id="people">People</option>
<option id="peopleData" style="display:none"><?php echo $people ?></option>
</select>
<select id="files"></select>
</form>
JS:
init();
function init()
{
addListeners();
}
function addListeners()
{
document.getElementById("fileCat").onchange = fillSelect;
}
function fillSelect()
{
var fileCat = document.getElementById("fileCat");
var imageFiles;
switch(fileCat.options[fileCat.selectedIndex].id)
{
case "misc":
imageFiles = document.getElementById("miscData").innerHTML.split(", ");
break;
case "people":
imageFiles = document.getElementById("peopleData").innerHTML.split(", ");
break;
}
var parent = document.getElementById("files");
parent.innerHTML = "";
if(imageFiles.length)
{
for(var i=0;i<imageFiles.length;i++)
{
var option = document.createElement("option");
//populate option with corresponding image text
option.innerHTML = imageFiles[i];
parent.appendChild(option);
}
}
}
I mocked up some data in PHP and then echoed it into a hidden <option> tag for each category. Then, the data is grabbed using a case/switch depending on the id of the selected option.
I think something like this would work. You would set the onchange attribute of your drop down box to call that function. You will need to have a URL that returns the options you want to use in JSON (selectMenus.php in that example). You'd need two different urls or one that takes a parameter to indicate which option set.
could You provide us some code? It is quite heavy to write it completely of nothing :)
UPDATE:
then how about You try the following (or similar) by using jQuery:
<select id="foo">
<option class="misc">MISC</option>
<option class="misc">MISC2</option>
<option class="people">People1</option>
</select>
<script type="text/javascript">
$(document).ready(function(){
$('option.misc').click(function(){
$('#foo').html('<option class="misc">MISC</option>
<option class="misc">MISC2</option>');
});
});
</script>
PHP is server side. JavaScript is client side. You have two options
(1) send an XmlHTTP request back to your server to pull the options and update the select list, or (2) send the values to a hidden field on the initial render of the page and get the values from there.

Categories