I have this JavaScript code that creates a table, and puts in the rows and columns.
I want to call this function, based upon some data in a database. So the amount of rows is based upon the amount of data in the database.
My data in my database is a markscheme, I want the the table to fill depending upon the amount of questions are in the database
I have tried and here is my code:
hasLoaded = true;//page loaded set to true
<?php
$query = "SELECT maxMark, criteria FROM mark ";
$result = mysql_query($query);
while ($result != null)
{
addRow();//add row with everything in
}
The correct answer is json_encode your data from PHP and store it in a JavaScript variable like this.
<?php
// populate the php rows array
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows = array_push($rows, $row);
}
?>
<script>
// populate the javascript rows array
var rows = <?php echo json_encode($rows); ?>;
for (var = 0; i < rows.length; i++) {
addRow(rows[i]);
}
</script>
I would not recommend Jamund's solution, as it would require either inline javascript, or parsing your javascript files through PHP. I would recommend using an Ajax post in your javascript function to fetch the data from your server, and then populating from there.
$(document).ready(function(){
$.ajax({
type: "POST",
url: "yourscript.php",
data:{param1: 'yourParam'},
success: PopulateTable
});
});
functionPopulateTable(data, status)
{
// Build Table with data
}
http://api.jquery.com/jQuery.ajax/ is a good place to start if you are using jQuery on your page.
Related
I need to get some data inside a drop list, and then after selecting a specific type, I need the other drop list to get specific type of values from MySQL too.
I have this link that works properly, but I can't modify it to accept values from my database.
My column of the first drop list is:
Refrigerator
Microwave
TVs
Heaters
And then, when I click on one of them, I will get a new data selected into my other drop list, like if I choosed TVs, second drop list will bring new data like:
LG
SAMSUNG
VESTEL
...
Any help is appreciated.
You need to use something like AJAX,
Jquery/Ajax code
$(document).ready(function() {
$('#id-of-the-first-drop-list').change(function() {
// get the form information
// this can be done in many ways but we are going to put the form
// data into a data object
var formData = {
'selectedValue' : $('#id-of-the-first-drop-list').val()
};
// send the data via Ajax
$.ajax({
type : 'POST', // the method we want to use to send the data
url : 'get-data-from-database.php', // the url where we want to
// send the data
data : formData, // the data object we created
dataType : 'json', // what type of data we want to get back
encode : true
})
// execute function when data has been sent and server
// code is processed
.done(function(data) {
// HERE ADD THE CODE THAT UPDATES THE OTHER DROPLIST
// I BELIEVE YOU WILL BE ABLE TO ACCESS THE DATA LIKE THIS
// data[0], data[1]... TO GET THE VALUE
// I got this from somewhere else on stackoverflow
var myOptions = {
val1 : data[0],
val2 : data[1]
};
var mySelect = $('#id-of-the-second-drop-list');
$.each(myOptions, function(val, text) {
mySelect.append(
$('<option></option>').val(val).html(text)
);
});
});
});
});
Now here is the server side code that will get the data from the database
PHP code
<?php
$data = $_POST['selectedValue'];
// Connect to database
// Use the data to get the new information
$query = "SELECT * FROM table_name WHERE column_name = '$data'"
// MySQL
$results = mysql_query($query);
$data = array();
$i = 0;
while($row = mysql_fetch_array($results)) {
data[i] = row['column_name'];
$i++;
}
echo json_encode($data);
?>
This code wasn't tested and may have errors but this is the general idea. I hope it helps.
I've created a tag input for my user in my site, for that purpose I coded a tag function with dropdown help. So my problem is that, I want to fetch data from data base in JavaScript file.
Js
var FormSamples = function () {
return {
//main function to initiate the module
init: function () {
// use select2 dropdown instead of chosen as select2 works fine with bootstrap on responsive layouts.
$('.select2_category').select2({
placeholder: "Select an option",
allowClear: true
});
$('.select2_sample1').select2({
placeholder: "Select a State",
allowClear: true
});
$(".select2_sample2").select2({
placeholder: "Type to select an option",
allowClear: true,
minimumInputLength: 1,
query: function (query) {
var data = {
results: []
}, i, j, s;
for (i = 1; i < 5; i++) {
s = "";
for (j = 0; j < i; j++) {
s = s + query.term;
}
data.results.push({
id: query.term + i,
text: s
});
}
query.callback(data);
}
});
function format(item) {
opt = $(item.element);
sel = opt.text();
og = opt.closest('optgroup').attr('label');
return og+' | '+item.text;
}
$("select").select2({
formatSelection: format,
escapeMarkup: function(m) { return m; }
});
$(".select2_sample3").select2({
tags: ['Karachi','Lahore']
});
}
};
}();
In the end of JS file you'll see:
$(".select2_sample3").select2({
tags: ['Karachi','Lahore']
});
Instead of "Karachi","Lahore" I want to fetch tags from data base.
I am fetching data like this:
$conn = mysqli_connect($servername, $username, $password, $dbname);
$sql = "SELECT * FROM tags";
$result = mysqli_query($conn, $sql);
mysqli_query ($conn,"set character_set_results='utf8'");
$row = mysqli_fetch_assoc($result);
Any body please help me that how can I fetch data in JS by PHP.
You can use json_encode in php:
$ar = array('Karachi','Lahore');
echo json_encode($ar);
and in javascript:
<script type="text/javascript">
// pass PHP variable declared above to JavaScript variable
var ar = <?php echo json_encode($ar) ?>;
</script>
output:
['Karachi','Lahore']
You are almost there. Now you can access the relevant data members of $row by selecting based on column name. For example you can look at the value of ˚$row["id"]. Also fetch_assoc type functions work row by row, so you will have to run it for each row, not each column, when you have multiple results. You can store the results in a php array but you will have to output them to the javascript portion of your file, or store them in a file javascript can access, before ending the php portion of your script. Below I write a little about each of your options.
Save data obtained form php data query to csv file, from which javascript can read.
Take a look at this SO post to learn how you can read data from csv. So in this example, your php script could read data from a database and then generate, via php, a csv file. Your javascript could then read from the csv file.
Alternately you can write from php directly to the javascript encoded in the same page assuming you can use your script in the same web page and not as a .js include. In that case, you can use json_encode to print your php arrays to javascript arrays as described in this SO post.
For example, to create two arrays accessible in Javascript of cities and countries I would do this:
<?php
...
$city = array();
$country = array();
while($row = mysqli_fetch_assoc($result)){
array_push($city, $row['city']);
array_push($country, $row['country']);
}
...?>
<script>
var city = <?php echo json_encode($city); ?>;
var country = <?php echo json_encode($country); ?>;
...
</script>
Here I am assuming you stored the data in a database with column names 'city' and 'country'
You should also consider using PDO objects for safer SQL manipulation.
This is what I'm trying to achieve, but my Googling hasn't helped:
I have a button that adds a new row to a table dynamically. I also add a select component to a cell with the same action all in javascript. I'd like for that select component to populate with values from a sql select statement. Of course I don't want to define the connection to the DB in the JavaScript. So I was wondering if there was a way I could call a PHP function to retrieve the values then store it in variable within JavaScript.
PS I understand that PHP is server side as opposed to JS. But surely this is possible.
here's a simple implementation of such a thing using jQuery's ajax and php.
html
<select data-source-url="/category/list"></select>
javascript using jQuery
$("select[data-source-url]").each(function(){
var url = $(this).attr("data-source-url");
var el = $(this);
$.get(url, function(data){
for (i=0;i<data.length;i++){
el.append("<option>" + data[i] + "</option>");
}
},"json");
});
category/list endpoint (a php script)
$list = array();
$list[0] = "category 1";
$list[1] = "category 2";
$list[2] = "category 3";
$list[3] = "category 4";
$list[4] = "category 5";
echo json_encode($list);
a little explanation: what happens is a request being made via the JavaScript client to a php script, which returns an array of values in JSON (which is basically a javascript data-structure), those values are added to the select box dynamically.
Please note that on initial load of the page, the select box will be empty.
yes ofcourse you can. for storing s php variable in a js ariable you can do like this.
before storing it into js variable store the required value in your php variable
var value = '<?php echo $value;?>';
Javascript cannot connect directly to a database.
You want AJAX. A basic flow for this functionality looks like this.
Create a PHP script that connects to the database and gets the options for your select element (let's call it options.php). This script should fetch the options from the database and output them as a JSON array.
In your javascript, you would create an ajax request to options.php. With the JSON data returned from that script, you would loop over each element and create and append a corresponding option element to the dom inside of your select element.
Also consider using jQuery. It greatly simplifies ajax and provides a cross-browser solution.
Option 1
Pass a php array with all possible values to the client side using something like this on the client side:
var opt_values = [<?php echo $php_values; ?>]; //javascript array
or
var opt_values = <?php echo json_encode($php_values); ?>; //json object
Option 2
Another way is making an ajax request. Write a php function that return a JSON object and then you can manipulate the result using jQuery ajax method:
PHP function:
$json = array();
$result = mysqli_query ($connection, $query);
while($row = mysqli_fetch_array ($result))
{
$bus = array(
'id' => $row['id'],
'text' => $row['name']
);
array_push($json, $bus);
}
return = json_encode($json)
Jquery
$('#button-id').click(function(){
//adds a new row to a table dynamically
$.ajax({
type: "get",
dataType: "json",
url: "/get_values.php",
success: function (response) {
var $el = $("#myselect"); //get the select
$el.empty(); // remove old options
//Append the new values
$.each(response, function(key, value) {
$el.append($("<option></option>")
.attr("value", value.id).text(value.text));
});
}
});
});
Just thought i'd put it out there since w3schools is my friend and i kinda follow what they're saying in this post.
W3Schools PHP & AJAX communication
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/
I attempt to fill a drop down from a database. I query and add my result to an array. I then use json_encode to send my data to a php file.
$query="SELECT project FROM main";
$results = $db->query($query);
while ($row_id = $results->fetchArray()) {
$proj_option[] = "<option value=\"".$row_id['project']."\">".$row_id['project']."</option>\n";
$pselected=$row_id['project'];
}
$output = array( "proj" => $proj_option);
echo json_encode($output);
In my php file, I use jquery ajax to fill the drop down.
$("#turninId").change(function() {
var user_id = $("#turninId").val();
$.ajax ( {
url:"send_input.php",
type: "POST",
dataType: "json",
data:{id_selection: user_id},
success:function(response) {
for (var i=0; i<response.proj.length; i++) {
$("#exp").html(response.proj[i]);
$("#project").html(response.proj[i]); } });
});
This is great, BUT the only item in my drop down is the last item in the db. For example, my database has the following under Project:
Project: up, down, low, right
But my drop down only fills with the last entry, "right." Why is this? How can I fix it?
PHP json_encode() in while loop was similar, and I made the changes, but there is something missing here.
may be try this
success:function(response) {
$.each(response.proj,function(key,value){
$("#exp").append(value);
$("#project").append(value);
});
}
each time thru your loop in javascript you are overwriting your html. The .html() method sets the innerHTML property of the tag, so each time you call it you are resetting the html and only the last one will show. try not using a loop, instead join you response together and then call .html()
$("#exp").html(response.proj.join(''));
$("#project").html(response.proj.join(''));