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.
Related
My goal is to obtain an array of data from a mysql database using PHP for use in a javascript function; graph() in the example below.
I have chosen to do this by loading the data i need to a DOM element. I am now trying to access it. The query works and I can see the information I need in my #loadTarget div. I am having trouble accessing the innerHTML though.
According to Jquery documentation, i can use a complete function which will execute once the load is done:
.load( url [, data ] [, complete ] )
Why then, when I can see the database data I need rendered in my element, can i not access it using getElementByID and innerHTML?
var dataLocation = document.getElementById("arrayTargetOne");
var data = dataLocation.innerHTML;
The above returns data is null. If i do the same getElementById on the parent element (not the one created in my PHP .load file, the one already there), i can see the data I need. It is like the .load function is not complete. Am i missing something minor or should i take a different approach?
The Javascript/Jquery
$( ".selectUser" ).click(function() {
var userChoice = document.getElementById(this.id);
var user = x.innerHTML;
$("#loadTarget").load("example.php",{"data":user},function() {
var dataLocation = document.getElementById("arrayTargetOne");
var data = dataLocation.innerHTML;
alert(data);
graph();
});
The PHP
<?php
$login_errors = array();
require ("config.php");
require (MYSQL);
$arrayOne = array();
$arrayTwo = array();
$exampleQuery = $dbc->prepare("SELECT exampleFieldOne,exampleFieldTwo FROM exampleTable WHERE userID=? AND name=?");
$exampleQuery->bind_param('ss',$_SESSION['user_id'],$_POST['data']);
$exampleQuery->execute();
$exampleQuery->bind_result($a,$b);
while($exampleQuery->fetch()){
array_push($arrayOne,$a);
array_push($arrayTwo,$b);
}
echo '<span id="arrayTargetOne">';
echo json_encode($arrayOne);
echo '</span><span id="arrayTargetTwo">';
echo json_encode($arrayTwo);
echo '</span>';
?>
});
var list = document.getElementById('loadTarget').children;
for (var i=0, len = list.length; i<len; ++i) {
var data = list[i].nodeValue; //for text nodes, use innerHTML for elements
//do stuff with data
}
The list will be a list of the created DOM nodes.
I am trying to make an html select list of options update according to a selection made on a prior html select object. My jquery is below. This is being called correctly.
var brandName = $("#Brand").val();
$.get("updateTypes.php?q="+brandName, function(data) {
$("#Type").remove();
var typeData = JSON.parse(data);
for (loop=0; loop < typeData.length; ++loop) {
$("#Type").options.add(new Option(typeData[loop]));
}
});
As I am using a singleton to interface with my mySQL database, this jquery function calls a 'go-between' .php file called updateTypes.php which is below:
include 'databaseInterface.php';
$brand = $_GET["q"];
$typesData = databaseInterface::getBrandTypes($brand);
return $typesData;
This calls the getBrandTypes function in my singleton below:
$query = "SELECT psTypeName FROM types WHERE brands_psBrandName='$BrandName'";
$result = mysqli_query($con, $query) or die ("Couldn't execute query. ".mysqli_error($con));
$resultArray = array();
while ($row = mysqli_fetch_assoc($result)) {
extract($row);
$resultArray[] = $psTypeName;
}
return json_encode($resultArray);
The webpage correctly removes the existing options from the jquery function but fails to update them. It seems to go wrong when I decode the JSON data in the jquery. Why is it going wrong? Is the loop for updating the select object appropriate?
You can use $.getJSON if your expecting a json response. You might also be able to use $.each() and then simply .append() to the select tag. You can reference this.property inside the .each().
Something like the following:
$.getJSON("updateTypes.php?q="+brandName, function(data) {
$("#Type").html('');
$.each(data, function(){
$("#Type").append('<option value="'+ this.value +'">'+ this.name +'</option>')
)
})
This would assume your json response is something like the following:
[ { name : "foo", value : "bar" }, { name : "another", value : "example" } ]
Your code $("#Type").remove(); removes the select object not its options. The correct way of removing options is:
$("#Type option").remove();
or
$("#Type").html('');
The second solution seems to be better as stated here: How to remove options from select element without memory leak?
There is also an error in the part that adds new options. Your javascript code should be:
var brandName = $("#Brand").val();
$.get("updateTypes.php?q="+brandName, function(data) {
$("#Type option").remove();
var typeData = JSON.parse(data);
for (loop=0; loop < typeData.length; loop++) {
$("#Type").get(0).options.add(new Option(typeData[loop]));
}
});
The $('#Type').get(0) method refers to the raw DOM object which has the "options" property that you wanted to use (How to get a DOM Element from a JQuery Selector)
I saw other posts but it doesn't work. I am a bit confused here on how I implement an array into JS from PHP...
In the PHP file (test.php) I have :
$table = array();
while($row = mysqli_fetch_assoc($result) )
{
$value=$row['value'];
$date=$row['date'];
$table[$value]=$date;
}
And in JavaScript I have :
<?php include 'test.php'; ?>
...
data: (function() {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
i;
for (i = -19; i <= 0; i++) {
data.push({
x: time + i * 1000,
y: Math.random()
});
}
return data;
So what I look for is to put $value=$row['value']; in the y : and $date=$row['date']; in the x : OR perhaps putting the entire table $table in the var data will work also .
I'm new to JavaScript, so thanks in advance..!
So in your php file....
Add a line at the bottom that converts the table to json data.
And give it a variable...
$table = array();
while($row = mysqli_fetch_assoc($result) )
{
$value=$row['value'];
$date=$row['date'];
$table[$value]=$date;
}
$jsondata = json_encode($table);
Then in your other file....
echo that variable into your data object, in the javascript.
Remember to remove that whole random number generating function...(its just an example)
Echoing PHP into javascript is definitely not considered good practice though.
And it would be better to actually do an ajax call to your php file, and insert like that....I'll also show you how to do ajax.
<?php include 'test.php'; ?>
...
data: [<?php echo $jsondata;?>], //remove that function that was here..
// it was just to generate random numbers for the demo
....
}
EDIT / UPDATE For ajax...
So for ajax...instead of assigning a variable to $jsondata.
Just return it like so...(in your PHP file)
return json_encode($table);
Then for this way....you dont include('test.php') like you did before.
Instead you just have this script inside your $(document).ready(function(){....
$.getJSON('test.php', function(myJSON) {
//and inside this function you put your highcharts stuff...
//remove that function() that generates random data
// And you will put the 'myJSON' return object inside the 'data':[] array...
// Provided you have structured your data correctly for highcharts, it should work...
// If not.... it'll be a start, and you're well on your way to debugging it
}
This function works fine, but it only returns one value. What I'm missing here?
Here's my code:
<script type='text/javascript'>
$(function () {
<?php
//Get the names and id's
$get_info=mysql_query("select * from table where id = '1'");
if($get_info){
while($row_info=mysql_fetch_array($get_info))
{
$username=$row_info['name'];
$user_id=$row_info['profile_id'];
?>
onDataRequest:function (mode, query, callback) {
var data = [
{ id:<?php echo $user_id;?>, name:'<?php echo $username;?>', 'avatar':'http://cdn0.4dots.com/i/customavatars/avatar7112_1.gif', 'type':'contact' }
];
data = _.filter(data, function(item) { return item.name.toLowerCase().indexOf(query.toLowerCase()) > -1 });
callback.call(this, data);
}
});
<?php
}}
?>
});
</script>
Expected result:
{
id: 295,
name: 'Mike',
'avatar': 'http: //cdn0.4dots.com/i/customavatars/avatar7112_1.gif',
'type': 'contact'
},
{
id: 296,
name: 'John',
'avatar': 'http: //cdn0.4dots.com/i/customavatars/avatar7112_1.gif',
'type': 'contact'
}
Actual output:
{
id: 295,
name: 'Mike',
'avatar': 'http: //cdn0.4dots.com/i/customavatars/avatar7112_1.gif',
'type': 'contact'
}
It just returns 1 item.
You database fetch loop isn't preserving each fetched value. You simply overwrite the previous fetch call with the current fetch. perhaps you meant something like this:
while ($row_info = mysql_fetch_asssoc($result)) {
$username[] = $row_info['name'];
$user_id[] = $row_info['profile_id'];
}
The [] notation on the vars tells PHP to treat the vars as array and push the new values into the array.
You'd then insert the arrays into javascript with:
var usernames = <?php echo json_encode($username); ?>;
var user_ids = <?php echo json_encode($user_id); ?>;
Every time you loop, you are assigning new values for your onDataRequest javascript function, however, it's the same function every time. You should think about execution order - first, you do PHP&MySQL server-side and what is generated as HTML or Javascript code there gets rendered and/or executed client-side later.
Basically, you have a PHP loop that goes over a set of values and those values are put inside a Javascript code that is within a HTML code block. So whatever you fetch from your database server last, is what is actually executed client-side.
The main idea here is that you shouldn't mix your server-side PHP code with client-side HTML or Javascript code.
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.