Before anybody says this is a duplicate of this and that question, let me assure you I have tried the solutions there and I have failed. I am using a solution offered in this website to come up with my solution and I believe I am 90% done except for one error. I want to display a list of all codes that have a certain common ID associated with them.
Here is my PHP code that I am using to get a list of codes
<?php
$budgetcode=$_POST['budgetcode'];
//$budgetcode=2102;
$selectcodes="SELECT * FROM tblbudget_codes WHERE T1 = $budgetcode";
$query=$connection->query($selectcodes);
$count=$query->num_rows;
if($count < 1)
{
die('0');
}
else{
while($row=$query->fetch_array()){
$T1=($row['T1']);
$T2=($row['T2']);
$T3=($row['T3']);
$T4=($row['T4']);
$optionValue = $T1."-".$T2."-".$T3."-".$T4;
echo json_encode("<option>$optionValue</option");
// echo json_encode('1');
}
}
?>
Here is the ajax call i am using to fetch the codes
$.post("Functions/getbudgetcodes.php",{budgetcode:budgetid},function(data){
if(data!='0')
{
$("#budgetcode").html(data).show();
$("#result").html('');
}
else{
$("#result").html('<em>No codes found. Contact Administrator</em>');
}
},'json')
//alert(budgetid);
})
The problem here is that jquery does not understand the data it is receiving if it is not numeric. E.g if I comment out the json_encode('1') and put random html code instead of data in my success part, I get results displayed in my browser. Can anybody tell me why jquery is only recognizing numeric values that are being echoed from PHP and not varchar values. Using jquery 1.4.2. Any help appreciated.
EDIT
I have managed upto some point and now i am stuck. I have used John's Answer and here is my jquery code. i just need to split the array and append each element to a variable one at a time like here
here is the code. Somebody please tell how I split (data). i can alert it but it is comma seperated. Just need to get the individual items append them to variable html and then display it.
$.post("Functions/getbudgetcodes.php",{budgetcode:budgetid},function(data){
if(!$.isEmptyObject(data))
{
//alert (data);
// alert(split (data))
var html = '';
var len = data.length;
for (var i = 0; i< len; i++) {
html += '<option>' +data+ '</option>';
}
$("#budgetcode").html(html).show();
$("#result").html('');
}
else{
$("#result").html('<em>No codes found. Contact Administrator</em>');
}
},'json')
I would skip JSON altogether:
PHP
echo "<option>$optionValue</option>";
Everything else should work.
Finally figured it out. Here is the php code
$selectcodes="SELECT * FROM tblbudget_codes WHERE T1 = $budgetcode";
$query=$connection->query($selectcodes);
$count=$query->num_rows;
if($count < 1)
{
die('0');
}
else{
while($row=$query->fetch_array()){
$data[] = $row;
}
echo json_encode($data);
}
?>
Here is the jquery code
$.post("Functions/getbudgetcodes.php",{budgetcode:budgetid},function(data){
if(!$.isEmptyObject(data))
{
//alert (data);
var html = '';
var joiner='';
var len = data.length;
for (var i = 0; i< len; i++) {
joiner=([data[i].T1,data[i].T2,data[i].T3, data[i].T4].join('-'));
//alert(joiner);
html += '<option>'+joiner+'</option>';
}
$("#budgetcode").html(html).show();
$("#result").html('');
}
else{
$("#result").html('<em>No codes found. Contact Administrator</em>');
}
},'json')
Had to use join to join the multiple codes using a dash. Hope this helps. The PHP part and part of the jquery was inspired by this question
FWIW, for populating select lists I usually use the following jQuery code:
// populates select list from array of items given as objects: {
name: 'text', value: 'value' }
function populateSelectList(parent, items) {
parent.options.length = 0;
if (parent.options.length === 0) {
parent.options[0] = new Option("Please select something...", "");
}
$.each(items, function (i) {
if (typeof (this) == 'undefined') { return; }
parent.options[el.options.length] = new Option(this.name, this.value);
});
}
and to call the above function i pass the results of an ajax call using the map method where #select is the selector for the parent select element. I am setting the Text property to the name and Value to the value but that should change according to the objects returned by the ajax call (e.g. assuming the returned objects have a Value and Text properties).
populateSelectList($('#select').get(0), $.map(results, function
(result) { return { name: result.Text, value: result.Value} }));
Related
So I have a php array that I am JSON encoding and handing to some JQuery. Basically I am using the information from the array to dynamically change the content of one drop down based on the value of another drop down. I am running into some problems with the JQuery though as JQuery is pretty new to me.
First off my PHP:
<?php
$sql = mysql_query("SELECT * FROM menu") or die(mysql_error());
$menuItems = array();
$x = 0;
while($row = mysql_fetch_object($sql))
{
$menuItems[$x]['ID'] = $row->ID;
$menuItems[$x]['parent'] = $row->parent;
$menuItems[$x]['name'] = $row->Name;
$menuItems[$x]['header'] = $row->header;
$menuItems[$x]['Sort'] = $row->sort;
$x++;
}
?>
This code returns an array of ~30 menu items.
Then my JQuery:
<script>
var menuItems = <?php echo json_encode($menuItems); ?>;
$('#dropdown1').change(function (){
if($('#dropdown1').val() == 0){
$('dropdown2').children().remove().end()
for(var x = 0; x < menuItems.length; x++){
if(menuItems[x]['header'] == 1){
$('#dropdown2').options[menuItems[x]['sort']] = new Option(menuItems[x]['name'], menuItems[x]['sort']);
}
}
}
});
</script>
What I want this to do is when dropdown1 is changed, dropdown2's options are removed and then repopulated with specific things from the array.
Currently this code does delete the options for dropdown2 when dropdown1 is changed but re-population just isn't working. From what I can tell in testing, the for loop to iterate through the array is only entered once, despite their being about 30 items in it and I assume that is were my main problem is.
What am I doing wrong here?
change it to
for(var x = 0; x < menuItems.length; x++){
if(menuItems[x]['header'] == 1){
var option = $('<option />', {
text : menuItems[x]['name'],
value: menuItems[x]['sort']
});
$('#dropdown2 option[value="'+[menuItems[x]['sort']]+'"]').replaceWith(option);
}
}
$('#dropdown2').options[] is not valid, as jQuery doesn't have those methods, that's for plain JS DOM nodes.
So from the comments there seemed to be some confusion on what I meant, and I apologize. It was one of the instances where the explanation made sense to me, but I just must not have conveyed everything well enough.
To clear up a little bit of the confusion. The array that was passed from the PHP code to the javascript contained everything I could ever need for the second drop-down.
As many pointed out the .options[] was the culprit for why the code wasn't executing. This was simply from another example I had found, and with my limited knowledge I assumed it was correct, and it wasn't.
I instead used the the .append() function and things seem to be working normally now.
I have a web page that show a list of data feeds by name (the dataFeed variable below) and I am trying to simulate a pop-up window that contains more information about the data feed when the user clicks on the icon (dataFeed + 'dataLink') next to the data feed name. I have a hidden div (diagWindow) that contains a div (diagWindowContent) that is populated with this information about the feed. The getDiagData.php page returns this information that I want to display, using the dataFeed parameter passed to it.
At first I tried this...
for (i = 0; i < dataFeeds.length; i++) {
dataFeed= dataFeeds[i];
$('#' + dataFeed+ 'diagLink').click(function() {
$('#diagWindow').toggle();
$('#diagWindowContent').load('getDiagData.php?dataFeed=' + dataFeed);
});
}
but that only displayed the page returned for the last dataFeed in the dataFeeds array.
Then I tried using a a callback method on the toggle(), like this...
for (i = 0; i < dataFeeds.length; i++) {
dataFeed= dataFeeds[i];
$('#' + dataFeed+ 'diagLink').click(function() {
$('#diagWindow').toggle('fast', function(dataFeed) {
return function() {
$('#diagWindowContent').load('getDiagData.php?dataFeed=' + dataFeed);
}(dataFeed)
);
});
}
but that appeared to have the same result, displaying the information for the last data feed in the dataFeeds array.
I am seeking help on figuring out how to make the appropriate data feed information load from the getDiagData.php page when clicking on the icon next to the data feed name.
Thank you.
Try this.. You are not executing it in the correct context ..
for (i = 0; i < dataFeeds.length; i++) {
(function(num){
var dataFeed = num;
$('#' + dataFeed + 'diagLink').click(function() {
$('#diagWindow').toggle();
$('#diagWindowContent').load('getDiagData.php?dataFeed=' + dataFeed);
});
})(dataFeeds[i])
}
This is most likely a variable scoping issue, you could try something like this:
for (var i = 0; i < dataFeeds.length; i++) {
var dataFeed= dataFeeds[i];
$('#' + dataFeed+ 'diagLink').click(function() {
$('#diagWindow').toggle();
$('#diagWindowContent').load('getDiagData.php?dataFeed=' + dataFeed);
});
}
Notice the added var keywords
EDIT: Actually, Sushanth's answer is the more correct one. I believe variables in Javascript are scoped by the function, so my above code may not work correctly. His will.
Coming from Adobe Flex I am used to having data available in an ArrayCollection and when I want to display the selected item's data I can use something like sourcedata.getItemAt(x) which gives me all the returned data from that index.
Now working in php and javascript I am looking for when a user clicks a row of data (in a table with onClick on the row, to get able to look in my data variable $results, and then populate a text input with the values from that row. My problem is I have no idea how to use javascript to look into the variable that contains all my data and just pull out one row based on either an index or a matching variable (primary key for instance).
Anyone know how to do this. Prefer not firing off a 'read' query to have to bang against the mySQL server again when I can deliver the data in the original pull.
Thanks!
I'd make a large AJAX/JSON request and modify the given data by JavaScript.
The code below is an example of an actual request. The JS is using jQuery, for easier management of JSON results. The container object may be extended with some methods for entering the result object into the table and so forth.
PHP:
$result = array();
$r = mysql_query("SELECT * FROM table WHERE quantifier = 'this_section'");
while($row = mysql_fetch_assoc($r))
$result[$row['id']] = $row;
echo json_encode($result);
JavaScript + jQuery:
container.result = {};
container.doStuff = function () {
// do something with the this.result
console.debug(this.result[0]);
}
// asynchronus request
$.ajax({
url: url,
dataType: 'json',
data: data,
success: function(result){
container.result = result;
}
});
This is a good question! AJAXy stuff is so simple in concept but when you're working with vanilla code there are so many holes that seem impossible to fill.
The first thing you need to do is identify each row in the table in your HTML. Here's a simple way to do it:
<tr class="tablerow" id="row-<?= $row->id ">
<td><input type="text" class="rowinput" /></td>
</tr>
I also gave the row a non-unique class of tablerow. Now to give them some actions! I'm using jQuery here, which will do all of the heavy lifting for us.
<script type="text/javascript">
$(function(){
$('.tablerow').click(function(){
var row_id = $(this).attr('id').replace('row-','');
$.getJSON('script.php', {id: row_id}, function(rs){
if (rs.id && rs.data) {
$('#row-' + rs.id).find('.rowinput').val(rs.data);
}
});
});
});
</script>
Then in script.php you'll want to do something like this:
$id = (int) $_GET['id'];
$rs = mysql_query("SELECT data FROM table WHERE id = '$id' LIMIT 1");
if ($rs && mysql_num_rows($rs)) {
print json_encode(mysql_fetch_array($rs, MYSQL_ASSOC));
}
Maybe you can give each row a radio button. You can use JavaScript to trigger an action on selections in the radio button group. Later, when everything is working, you can hide the actual radio button using CSS and make the entire row a label which means that a click on the row will effectively click the radio button. This way, it will also be accessible, since there is an action input element, you are just hiding it.
I'd simply store the DB field name in the td element (well... a slightly different field name as there's no reason to expose production DB field names to anyone to cares to view the page source) and then extract it with using the dataset properties.
Alternatively, you could just set a class attribute instead.
Your PHP would look something like:
<tr>
<td data-name="<?=echo "FavoriteColor"?>"></td>
</tr>
or
<tr>
<td class="<?=echo "FavoriteColor"?>"></td>
</tr>
The javascript would look a little like:
var Test;
if (!Test) {
Test = {
};
}
(function () {
Test.trClick = function (e) {
var tdCollection,
i,
field = 'FavoriteColor',
div = document.createElement('div');
tdCollection = this.getElementsByTagName('td');
div.innerText = function () {
var data;
for (i = 0; i < tdCollection.length; i += 1) {
if (tdCollection[i].dataset['name'] === field) { // or tdCollection[i].className.indexOf(field) > -1
data = tdCollection[i].innerText;
return data;
}
}
}();
document.body.appendChild(div);
};
Test.addClicker = function () {
var table = document.getElementById('myQueryRenderedAsTable'),
i;
for (i = 0; i < table.tBodies[0].children.length; i += 1) {
table.tBodies[0].children[i].onclick = Test.trClick;
}
};
Test.addClicker();
}());
Working fiddle with dataset: http://jsfiddle.net/R5eVa/1/
Working fiddle with class: http://jsfiddle.net/R5eVa/2/
Edit:
Solved using the below suggestion of removing:echo '{"results":'.json_encode($arr).'}';
and replacing with echo json_encode($arr);
This combined with replacing these lines:
var items = [];
$.each(data, function(key, val) {
$.each(val, function(key, val)
{
//Test insert into box using customer number
$("#chatbox").html(val.number);
});
});
with
$.each(data, function(key, val) {
$("#chatbox").html(this.number);
});
Made it work, I can now access the object data using the this followed by the property I want.
End Edit
Hi could anyone help me with these JSON feed. I am almost there with it (I think) however whenever I put this feed into JQuery it is picked us as a string rather than as an array of JSON objects and I can't figure out why.
The PHP to create the feed:
<?php
session_start();
include 'connect.php';
$number = $_SESSION['number'];
$query = "SELECT * FROM $tableName WHERE number='$number'";
$result = mysql_query($query, $sqlCon);
$arr = array();
while($obj = mysql_fetch_object($result)) {
$arr[] = $obj;
}
if (count($arr) == 0)
{
echo "Your reference number is: $number";
} else {
echo '{"results":'.json_encode($arr).'}';
}
?>
The returned JSON looks like this:
{"results":[{"id":"40","number":"466741","message":"dsfdsv","date":"2011-10-05","time":"00:28:32"},{"id":"41","number":"466741","message":"sacsac","date":"2011-10-05","time":"00:30:17"}]}
What I instead want is:
[{"id":"40","number":"466741","message":"dsfdsv","date":"2011-10-05","time":"00:28:32"},{"id":"41","number":"466741","message":"sacsac","date":"2011-10-05","time":"00:30:17"}]
Or a return value which would allow me to iterate over the objects.
The JQuery I'm reading it with:
$.getJSON('get.php', function(data) {
var items = [];
$.each(data, function(key, val) {
$.each(val, function(key, val)
{
//Test insert into box using customer number
$("#chatbox").html(val.number);
});
});
});
I'm guessing my problem is the way in which I'm creating the JSON feed but I'm just stuck and cant figure out how to fix it.
Any help would be appreciated, thanks.
You should set the headers from PHP to specify that it is json content. This isn't 100% required but good practice and you'll see the content-type parsed correctly in tools like firebug.
header('Content-type: application/json');
You are wrapping your json content with a results key that that you aren't looking for in your javascript so you either need to remove that part or look for that your javascript. Since you say you want the array and not the object with the results key/value just replace echo '{"results":'.json_encode($arr).'}'; with echo json_encode($arr);
What I'm trying to do is use jQuery to grab any checkboxes that are checked on the page. The boxes are dynamically created using a specific ID number of each one for the ID and Value.
What is the easiest way about getting it to grab the values of each checked item? Then check if less than or greater than 3 is checked. If only 3 are checked then send the values of each checkbox to my php script. I'm using a regular button on the page so I will proably have to use the .click method since its not actually part of a form to submit.
I've seen several examples around here but not quite what I'm trying to do.
$('#mybtn').live('click',function(){
$("input[type=checkbox]").each(function() {
// I guess do something here.
)};
)};
the code i believe you are wanting is this
$('#mybtn').live('click',function(){
var num_checked = $("input[type=checkbox]:checked").length;
var checkbox_values = new Array();
if( num_checked > 3 ) {
//its greater than 3
//do what you need to do
} else if( num_checked < 3 ) {
//its less than 3
//do what you need to do
}else {
//it equals 3
//do what you need to do
//go thru and add values to array
$("input[type=checkbox]:checked").each(function() {
checkbox_values.push($(this).val());
});
}
});
if you want to send email of variables you can output array checkbox_values to php
If all your checkboxes are in a form, you can do $('#form_id').serialize();
You can get how many are checked using
$("input[type=checkbox]:checked").length
http://jsfiddle.net/XKRRL/7/
Not really sure what you want to do with the ones that are checked, but the js fiddle loops through the checked ones. From there you could grab id's etc.
full code
$(function() {
$('#mybtn').live('click', function() {
var checkedBoxes = $("input[type=checkbox]:checked"),
checkedNum = checkedBoxes.length;
if(checkedNum === 3){
for(var i=0; i< checkedNum; i++){
alert($(checkedBoxes).eq(i).val());
}
}
});
});
It's simple to grab all checked checkboxes:
var checked = $('input[type=checkbox]:checked'),
count = checked.length;
if (count == 3) {
values = $.map(checked, function(i){
return $(this).val();
});
}
Then do whatever you want on the values array.