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>
Related
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
I may have misunderstood the purpose of PHP here. But I want to do the following:
I have a PHP function, and I call it from HTML, e.g.
<BODY>
<DIV id='A'>
<?php emit("hello1"); ?>
</DIV>
<DIV id='B'>
<?php emit("hello2"); ?>
</DIV>
</BODY>
And I want to know, within the function, which DIV it was called from.
e.g.
<?php function emit($txt){
echo "$txt";
echo "from DIV id $DIVID"
}
?>
And I want it, obviously, to print
hello1 from DIV id A
hello2 from DIV id B
Is there any way of finding the "current" DIV's ID?
Yes, you have misunderstood the purpose of PHP.
PHP is a server side programming language, it does not run on the HTML page, but before the HTML gets loaded on to the browser.
The task that you are trying to do can be done from JavaScript if interested. I will give an example of jQuery:
var emit = function(el, txt) {
var id = el.attr('id');
el.html(txt+" from DIV id "+id);
}
Now call using
emit($("#a"), "hello1");
Same can be done from JS in the following way
var emit = function(el, txt) {
el = document.getElementById("el");
id = el.getAttribute('id');
el.innerHTML(txt+" from DIV id "+id);
};
Use like:
emit("a", "hello1");
Here is my javascript code which is added in the tag of my php/html page:
<script type="text/javascript">
$(document).ready(function() {
$('#status').change(function(){
var status = $('#status').val();
var html = ''; //string variable for html code for fields
if( status=="closed"){
html += '<th>Close By :</th><td align="left"><select name="close_by">'+<?php $user=mysql_query("SELECT * FROM user");
while($data=mysql_fetch_array($user)){?>+'<option value="'+<?php echo $data['username'] ?>+'">'+<?php echo $data['username']; ?>+'</option>'+<?php } ?>+'</select></td>';
}
$('#close_by').html(html);
});
});
</script>
The code is for that, if Status=="closed" then a select tag will be appeared and the option values will be fetched from the database using mysql functions.But its not working. Please help to sort out this problem.
Thanks in advance.
You can't. PHP/MySQL reside on your server, while JS is executed in the browser.
Of course you may let the browser interact with your server by proper HTTP requests, after setting proper routes on your server.
You can mix PHP into Javascript. The PHP will execute on the server, and then the JS on the client. It's horrible though, extremely bad practice, and a nightmare to debug. Much better to seperate them out and use jQuery ajax to load the data.
Or use PHP to put the data into a JSON object at the start of the javascript, and process that with Javascript, rather than using PHP code to concatenate strings inside Javascript.
But in your example, what exactly is the problem? What is the end result of the PHP (in the HTML source) of the html variable? I suspect there's a bracket or quote wrong somewhere.
You can do it with ajax
$(document).ready(function() {
$('#status').change(function(){
var status = $('#status').val();
if( status=="closed"){
$.ajax({
url: 'ajax.php?',//if you have parameters
success:function (response) {
$('#close_by').html(response);
}
});
}
});
});
And you create a new php file for the ajax request
ajax.php
<th>Close By :</th>
<td align="left">
<select name="close_by">
<?php $user=mysql_query("SELECT * FROM user");
while($data=mysql_fetch_array($user)){?>
<option value="<?php echo $data['username'] ?>"><?php echo $data['username']; ?>
</option>
<?php } ?>
</select>
</td>
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 :)
I have this jquery code in a foreach loop. Basicaly the variable $perf gets a new value with every loop. How can I use jquery to display the different $perf value with each loop? Is it possible?
foreach ($perfs as $perf):
<script type="text/javascript">
$(document).ready(function(){
var performerName = $(".transparency").data('title');
var divcontent = $(".transparency").html();
if ( divcontent == ' ' ){
$(".transparency").html(''+performerName+'');
}
});
</script>
<div class="transparency" data-title="<? echo $perf; ?>"> </div>
endforeach;
You should do it like this:
<?
foreach ($perfs as $perf):
?>
<script type="text/javascript">
$(document).ready(function(){
var $perf = "<? echo $perf; ?>"; //Get from php
alert($perf); //Show it
//Here goes the rest of your script
var performerName = $(".transparency").data('title');
var divcontent = $(".transparency").html();
if ( divcontent == ' ' ){
$(".transparency").html(performerName);
}
});
</script>
<div class="transparency" data-title="<? echo $perf; ?>"> </div>
<?
endforeach;
?>
That's it. It works.
(I tried to modify your code at least as possible, cause I don't know if I can remove parts)
PS: There would be more 'elegant' solutions, do you want one? or this is enough?
Can you please describe what you are trying to do? I'm about 90% sure there is zero reason for any javascript, jQuery or otherwise.
Why not just do this?
<?php
foreach($perfs as $perf)
{
echo "<div class='transparency' data-title='$perf'>$perf</div>";
}
?>
Unless there is something more you are trying to do, you don't need javascript at all. And even if you do need javascript, take the function out of the loop and call it once each iteration. you dont need the exact same function defined multiple times.
I suggest you look into the relationship between server and client-side scripting. For starters - take a look at the HTML source generated by your PHP and see if thats anything close to what you want. Also, read up about ajax. It seems that you are trying to do combine PHP/javascript in such a way that it needs additional HTTP Requests (ajax calls)
It is impossible to have PHP and javascript interact directly without AJAX, and it is difficult to answer the question without more knowledge of what, exactly, you want to happen.
If you want a different transparacy div for each value of $perfs you can use:
<?php foreach ($perfs as $perf) { ?>
<div class="transparency" data-title="<?php echo $perf; ?>"> </div>
<?php } ?>
And they you can use the jquery .each() to iterate over the divs
$(".transparency").each( function() {
var performerName = $(this).data('title');
// do stuff //
});
If all you want is to pass the values in $perfs to you javascript function you can use
var perfs = <?php echo json_encode($perfs); ?>;
OK I think I see what you are trying to do now. You'll want something like this:
<script type="text/javascript">
$(document).ready(function(){
var perfs = <?php echo json_encode($perfs); ?>;
$.each( perfs, function( index, value ) {
$( ".transparency" ).append( value+'<br>' );
} );
} );
</script>
<div class="transparency"></div>
This will output each value of $perfs inside of the transparency div.
Using JQuery each and append.
You will never want to wrap an entire script in a foreach loop, as that will create a separate script for each element in the array. Using json_encode you will change the PHP array into a javascript object & you can do whatever you want to with it.
Remember javascript is only able to access elements written to the page using echo or something similar. Whatever you can see when you look at 'view page source' in your browser is all your script will be able to use.