I am a newbie to MySQL.
I want to transfer data from MySQL table to javascript.
I want to create a multidimensional array in javascript using the table in MySQL.
This multidimensional array is to be used in other functions for calculation.
Is there any way to do it using PHP or JSON?
Read records from your database table in PHP page and Create JSON And send it to Javascript. JSON can hold any level of hierarchical data.
A sample JSON may looks like this
[
{
"Customers": [
{ "Name": "Steve", "ID": "A12" },
{ "Name": "Mark", "ID": "A22" }
]
}
]
JsonLint is a useful tool when working with JSON data. It can validate JSON.
If you want to populate the javascript data on initial page load, you can do something like:
<?php
// get stuff from DB
$array_from_db = ... // some value determined via MySQL queries
?>
<script type="text/javascript">
var db_array = <?php echo json_encode($array_from_db); ?>
</script>
<?php
// more PHP stuff
This should work
<?php
var query=mysql_query("SELECT fields FROM table WHERE condition");
while($obj=mysql_fetch_array($query)){
arr[]=$obj
}
$array=json_encode($arr);
?>
<script type="text/javascript">
var db_array = <?php echo $array; ?>
</script>
Related
I'm trying to create an update form where the user selects an ID and the rest of the form gets automatically filled with the corresponding data to that ID which would make updating really simple, obviously i'd have to use AJAX but do i really have to write a whole form code inside the PHP and return it in a single statement and then assigning it in a single innerHTML?
Is it possible to run whatever returns from the php file as a javascript, such that i would be able to write a mini scripts to set the innerHTML of each element by itself and without having to reload the whole form's HTML code, just the values inside form elements?
<?php
$myname = "test";
$myage = 22;
echo
'<script>
document.getElementById("name").innerHTML = "$myname";
document.getElementById("age").innerHTML = "$myage";
</script>';
?>
PS i have no experience of AJAX and i can only find the xmlhttp.responseText for returning the output of a PHP script.
It would be better if you return the data structured in some form (e.g.: JSON), then process it with JavaScript.
For example, instead of what you are returning, do something like this:
<?php
$to_return = array(
"name" => "test",
"age" => 22
);
echo json_enconde($to_return);
Then on your page, parse your response, and process it:
data = JSON.parse(response);
document.getElementById("name") = data.name;
document.getElementById("age") = data.age;
If you want to standardize it a little bit more, you could return something like this:
[
{
"target": "name",
"value": "test"
},
{
"target": "age",
"value": 22
}
]
and create a function like this:
function populateForm(data) {
for (var x = 0; x < data.length; x++) {
document.getElementById(data[x].target).innerHTML = data[x].value;
}
}
Then call that function with the JSON response from your PHP.
I would recommand to return an Array in the server side (the php that handles the ajax request). and in the browser side after you get the the respone from the server then you set
document.getElementById("name").innerHTML = $myname;
document.getElementById("age").innerHTML = $myage;
Is it possible to send an empty array to PHP from JS using JSON?
<?
if ($_GET['test']) {
$data = $_GET['data'];
print_r($data);
exit;
}
?>
<head>
<script type="text/javascript" src="jquery-1.6.4.min.js"></script>
</head>
<script type="text/javascript">
$.getJSON('temp.php', {
"test": 1,
"data": []
})
</script>
This is a simplified version of what I'm trying to do. Basically, I'm sending data to PHP so it can update the database. If I send an empty array, it should save an empty array. However, in the above example, only "test" gets passed and "data" gets thrown away. The only solution I can think of is to do something sloppy, like this:
if (! isset($data = $_GET['data']))
$data = array();
So, I'm basically just making an empty array after JSON/JS throws it away. Unless there's another way? Thank you!
$.getJSON('temp.php', {
"test": 1,
"data": JSON.stringify([])
})
I can think of plenty of ways to use ajax to load information from my database. For example: http://www.w3schools.com/php/php_ajax_database.asp
However, I really want to separate my structure (HTML), behavior (JS/AJAX), style (CSS), and data (MySQL + PHP) to keep my website scalable.
The above example shows how to just paste in the HTML via AJAX into the existing HTML doc, but what if I have the HTML already and just want to modify HTML elements via ajax using one MySQL call?
For example
Say I have this structure (HTML)
<body>
<h1 id="first">First name here</h1>
<h2 id="last">Last name here</h2>
<h3 id="email">Email here</h3>
</body>
I currently use PHP to make a MySQL query,
"SELECT * FROM `user` WHERE `id` = ".$id;
And of course I could assign each field to individual PHP vars, $first $last, $email. But then when it comes to using jQuery or plain ol AJAX, how do I use this single MySQL statement and single GET request from AJAX to change <h1>, <h2>, and <h3> in the above example?
I know I can use jQuery selectors
$(document).ready(
$('#first').innerHTML = ?
...
)
But is there an elegant way to load values retrieved from PHP into jQ/js? (Let's assume I'm GETting the php doc via jQ/js).
A nice way might be to use JSON with selectors, so return this from your PHP script:
{
'#first': 'First name updated value',
'#last': 'Last name updated value',
'#email': 'etc.'
}
Then, when retrieving the results (don't forget to use 'json' as your dataType):
for(var x in data) {
if(data.hasOwnProperty(x)) {
$(x).html(data[x]);
}
}
Oh, and jQuery can do that for you too:
$.each(data, function(selector, newContent) {
$(selector).html(newContent);
});
Your PHP can return simple json, like the following:
[{ firstName: "Joe", lastName: "Smith", email: "joe#smith.com" }]
And in your ajax success callback, you can use jsRender to render your html, or in other words, "fill your html with data."
What this looks like...
HTML:
<body>
<div id="personContainer"></div>
</body>
<script id="personTmpl" type="text/x-jquery-tmpl">
<h1>{{=firstName}}</h1>
<h2>{{=lastName}}</2>
<h3>{{=email}}</h3>
</script>
in Ajax success callback:
$.ajax({
...
success: function(data) {
$("#personContainer").html(
$("#personTmpl").render(data);
); // where data is in the json format above
}
});
Similar example here: http://jsbin.com/ihuhep/3/edit
I am working on an e-commerce website. There is an array "products" in javascript defined by the following code
<script type="text/javascript">
var products =
[
{"id":"1","title":"Apple iPhone 4"},
{"id":"2","title":"BlackBerry 9780 Bold"}
];
/*some other javascript code*/
</script>
I want this array to be updated dynamically according to the number of rows returned by querying the database.
For example, suppose I query the database and 5 rows are returned. I want this array to be updated with those 5 rows. Please help me getting this done. I am using PHP, MySQL, Apache on Windows machine.
You want the push function: http://www.w3schools.com/jsref/jsref_push.asp
var products =
[
{"id":"1","title":"Apple iPhone 4"},
{"id":"2","title":"BlackBerry 9780 Bold"}
];
// Let's add a new phone:
products.push({"id":"3","title":"HTC Evo"});
/*
products now equals:
[
{"id":"1","title":"Apple iPhone 4"},
{"id":"2","title":"BlackBerry 9780 Bold"},
{"id":"3","title":"HTC Evo"}
];
*/
To account for the possibility you may have an existing array and you'd like to update it via ajax, you can do this dynamically with PHP:
<script type="text/javascript">
<?php foreach($phones as $phone): ?>
products.push({"id":"<?=$phone['id']?>","title":"<?=$phone['name']?>"});
<?php endforeach; ?>
</script>
The top answer to the question JSON encode MySQL results could achive this for you:
$sth = mysql_query("SELECT ...");
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
print json_encode($rows);
In your case, replacing the last line with
?>
var products = <?php echo json_encode($rows); ?>;
<?php
would initialize the JavaScript object with your query results. This would need to be done before the page is loaded, because the PHP runs on the server producing the JavaScript for the client. If you need to get the results after the client page is loaded you would need a more complicated solution, probably using AJAX.
I would make a server side script that makes the connection to the database, get's the products, and constructs the JSON for you, so that way all you have to do is make an AJAX request to the script from the client side and it will return everything for you for use on your webpage.
You can use PHP to output json directly into the page.
Assuming that $data is an array that contains the products you want to output.
In the template you would do something like this:
<script type="text/javascript">
var products = <?php echo json_encode($data) ?>;
</script>
products[products.length] = {..some data..};
products.push({..some data..});
Or you need something else?
I'm trying to read in values from a db using php (mySQL) then have them show on a graph in flot. I know the values are read in correctly and I'm not getting any errors but the graph won't show.
Little help?
Thanks in advance.
<?php
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
$graphdata[] = array( (int)$row[0], (int)$row[1] );
}
?>
/////
<div id="placeholder" style="width:600px;height:300px"></div>
<script language="javascript" type="text/javascript">
var dataset1 = <?php echo json_encode($graphdata);?>;
var data = [
{
label: "Random Values",
data: dataset1
}
];
var plotarea = $("#placeholder");
$.plot( plotarea , data);
</script>
The contents of your pastebin show that the JSON string you're outputting is invalid JSON.
var data = [{ label: "Random Values",data: dataset1}];
will validate if it's changed to:
var data = [{"label": "Random Values","data": "dataset1"}]
That's just an example, but I suspect that Flot is looking for a slightly different format, so you'll have to verify exactly what they're looking for against their documentation. I'm going through the same exercise right now with FusionCharts, so I'm feeling your pain. jsonlint.com is your friend on this one, output your JSON and verify it frequently. I'd also recommend that to initially get it working, start with just a string of JSON (even one that you copy from their examples) that you put right in your code. Get the chart working first, then work on getting your PHP to duplicate the example JSON string separately.
Try delaying creating the graph until the DOM is loaded:
jQuery(document).ready(function ($){
var plotarea = $("#placeholder");
$.plot( plotarea , data);
});