Parsing MySQL into JavaScript Arrays through PHP and jQuery - php

Ultimate Goal: I want to take data I keep in a MySQL Database and put it into an Array of Arrays in JavaScript, so it can be manipulated client side.
So far, I have been able to pull data from my database with this code:
<?php
...
$num=1;
$q = "SELECT blah1, blah2, blah3 WHERE blah4=$num";
$sth = mysqli_query ($database, $q);
$rows = array();
while($r = mysqli_fetch_assoc($sth)) {
$rows[] = $r;
}
print json_encode($rows);
?>
(from: JSON encode MySQL results)
This is where I am stuck, because I am having trouble getting this data into JavaScript.
One solution I can find is Parsing a Separate PHP Array in Javascript:
<script>
var jsonarray = <?php echo json_encode($array); ?>;
// now you can use jsonarray in your javascript
</script>
But the problem with this implementation is that it would spit out all of the database content I query onto the source-code of the page. If I have to do this, I might as well skip the database and just keep all of the content in javascript.
I am thinking there must be a way with jQuery/AJAX to pass the value of $num to a PHP script, grab this data and put it into a JavaScript Array without having to output all of it to the page.
Any assistance would be appreciated.
Thank you!

This solution you posted:
<script>
var jsonarray = <?php echo json_encode($array); ?>;
// now you can use jsonarray in your javascript
</script>
Is actually a very good approach. Using AJAX is drastically slower (because of network latency).
Unless you really need AJAX for some reason, you should avoid using it. It will add a noticeable split second of load time to the page, often for no benefit at all.
Above all when structuring your page, you want to try and reduce the number of individual network requests between the browser and the server. The less requests the faster your page will be. This is especially true for javascript and ajax, because they are unpredictable and browsers find it very difficult to optimise any part of the page where it's being used.
We're talking about one quarter of a second compared to one millionth of a second, for exactly the same end result.

Making an AJAX call with jQuery is easy enough. Take a look at the documentation: http://api.jquery.com/jQuery.get/

You can also do this without AJAX
var jsonarray = eval(<?php echo json_encode($array); ?>);

Related

How to encode large amount of data as json

I need to be able to pass a json from php to the client so javascript can parse the code and return it. Currently, the way I have always done this is:
<?php
$mysql_query = $mysqli->query(QUERY GOES HERE);
$array - array();
while($row = $mysql_query->fetch_assoc()){
array_push($array, $row);
}
$json =json_encode($array);
?>
<!-- javascript -->
<script>
var json = <?php echo $json;?>;
//...
</script>
<!--- rest of html --->
This usually works. However, the query returns more than 100,000 rows, and php is currently running out of memory on creating the entire array. I have seen some people say to use ajax. Is this the only way? And if so, how exactly would I go about implementing it? Or is there a more efficient method of encoding the mysql data into json without ajax?
Thank you
Since you said you can also send your array in chunks, meaning you can process your data while it's sorted out in several ways, i consider doing this:
Fetch the database data in small chunks (memory wise), in normal php arrays.
Doing it such a way that you unset the previously allocated chunk to free memory.
JSON encode your partial data into an HTML element.
Like this:
<input id="json-1" type="hidden" data-json='<?php echo json_encode($chunk[0]); ?>' />
<input id="json-2" type="hidden" data-json='<?php echo json_encode($chunk[1]); ?>' />
<input id="json-3" type="hidden" data-json='<?php echo json_encode($chunk[2]); ?>' />
Yes, it looks ugly but consider some pros:
There's no giant javascript JSON object, hogging the client's memory
You can parse the data in a progressive way, thus consuming only a portion of memory
javascript processing
$(document).ready(function() {
$("input[id^='json-']").each(function() {
var json = $(this).data("json");
// process the chunkied 'json'
// remove the memory allocated (since you dont want anymore the huge data, probably)
$(this).removeData(this,"json")
});
});
If you want to pass something from php to javascript you will have to use ajax as php is server side and javascript is client side.
Having an array of 100,000 rows is a bit big and could cause problems. Consider splitting the array into smaller chunks or limiting the query.
You can increase phps memory limit but it would be better to optimize the array first.
You don't need to handle so large amount of data.
Separate into pages.

HTML marquee change behaviour

If I put marquee in while loop it shows all the data at the same time, sliding right to left. I want this to behave one by one, when one finishes the second starts... and lastly the first comes again, how can I do this please help me out I would be very grateful to you, thanks in advance :)
$data=mysql_query("SELECT heading from moto_static_pages");
while($res = mysql_fetch_assoc($data)){
echo '<marquee behavior="scroll" direction="left" style="padding:0 0 10px 0;">';
echo $res['heading'];
echo '</marquee>';
}
PHP is server-side. Everything is computed on the server, and then all at the same time displayed on the browser in-front of you. So your loop is merely looping around what eventually will be displayed in the browser, and printing it all out at once, which is what it's supposed to do.
You will need to use JavaScript to accomplish this, as this is client-side. You cannot do this with PHP.
You will need to retrieve all the data from your database, convert it to json (json_encode()), and send this to your browser as one string. Then, in JavaScript, loop through the json and print out each one as a marquee with a timed event.
To reiterate, unless you are going to be doing something with asynchronous I/O with PHP, which you aren't, you will need to do this with JavaScript.
This is untested code and straight from the top of my head, but hopefully this will point you in the right direction.
<?php
// Server-side code, get your data, json encode it too!
$data = json_encode(mysql_query("SELECT heading from moto_static_pages"));
?>
<script type = "text/javascript">
// Client side code that happens in real time in the browser
// Get your data from your php variable
var data = JSON.parse(<?php echo $data; ?>);
// Loop your data
for (var i = 0; i < data.length; i++)
{
// Output your data in marquees
setTimeout(function() {
document.write("<marquee behaviour='scroll' direction='left'>");
document.write(data[i].heading);
document.write("</marquee>");
}, 4000); // Every 4 seconds
}
</script>
Don't expect this code to just work for you, so get debugging it and using var_dump() to see what you get from PHP, and console.log() to see what you have in JavaScript.
Final Note
mysql_query has been deprecated and should be used with caution. You should check out PDO / mysqli instead; they're not too hard to understand and they're interesting too!

How to combine PHP and Javascript together?

I have a function in my Javascript script that needs to talk with the PHP to get the data in my database. But I'm having a small problem because I start the PHP in the for loop in Javascript, and then inside that for loop I get the data in my database. But the pointer in the for loop inside the PHP code is not working.. I guess the problem is in escaping? Or maybe it's not possible at all.
Here's my code:
(function() {
var data = [];
for(var i = 0; i < 25; i++) {
data[i] = {
data1: "<a href='<?= $latest[?>i<?=]->file; ?>'><?= $latest[?>i<?=]->title; ?></a>", // The problems
data2: ....
};
};
});
I think you are confused, you are trying to use a variable of javascript in php.
You cannot do this:
<?= $latest[?>i<?=]->file; ?>'
Which expands to:
<?php
$latest[
?>
i
<?php
]->file;
?>
how can you possibly know the value of i, if i is a variable generated in the client side?, do not mix the ideas, i is defined in the browser and the php code is on the server.
You may want to consider using PHP to output the JavaScript file, that way the PHP variables will be available wherever you want them.
The following links better explain this.
http://www.givegoodweb.com/post/71/javascript-php
http://www.dynamicdrive.com/forums/showthread.php?t=21617
1.Pass the javascript variable to the URL to another php page.
window.open("<yourPhpScript>.php?jsvariable="+yourJSVariable);
2.Then you can use this variable using $_GET in the php script.
$jsVaribleInPhp=$GET['jsvariable'];
//do some operation
$yourPhpResult;
3.Perform any server side operation in the Php and pass this result.
header("Location:<your starting page>?result=".$yourPhpResult);
4.Redirect back to the page you started from thus passing the result of PHP.
Php and Javascript have different roles in web development.
This task can also be performed if there's a php script and js in the same page. But that I leave for the readers to work it out.
Hope this helps!!

Parsing a Separate PHP Array in Javascript

So, as sort of an exercise in learning, I am trying to port a site I was working on for someone, written in PHP, MySQL and CSS, over to Ajax (Specifically, really, just adding Javascript so that the page is dynamic instead of needing to constantly reload).
Unfortunately, I have some scripts I'd like to keep as PHP (for instance, a script to update a database given an array of victims) because I need it to interact with a database, and this means that the array must stay as PHP (I think).
So, given this file,
<?php
$victims = array(
// Animals
"chickens",
"horses",
"cows",
// Supernatural
"werewolves",
"zombies",
"vampires",
"phantoms",
// Human
"U.S. Congressmen",
"performance artists",
// Inanimate, non-mechanical
"pieces of fencepost",
"barnhouses",
// Mechanical
"robots",
"cyborgs"
);
?>
is there a way to reach into that file using Javascript an extract a value?
Or, come to think of it, would it be better to store the list of victims as an XML file so both the PHP and Javascript can read it? Or even, how would I go about doing that?
Read up JSON and check out json_encode() for PHP5.
You can convert a PHP array into JSON, this is a string. Then print that string out into your page and use it with your Javascript
<script>
var jsonarray = <?php echo json_encode($array); ?>;
// now you can use jsonarray in your javascript
</script>
This is especially useful when returning data for an Ajax request
<script>
var jsonarray = <?php echo json_encode(array("status" => "success", "message" => "Something was completed OK")); ?>;
</script>

re-fetch request in php and javascript

here it goes;
echo "<a href='#' class='thumb'><img class='thumb-img' value = ".$row->aid." onclick='getVote(".$row->aid.", \"".$row->atitle."\")' src='images/roadies/th".$row->aid.".jpg' /> </a>";
the above function sends the "$row->aid" value to a javascript function through ajax.
in the javascript however, i want to make a function that needs the ++value of the $row->aid variable. i want the php to get the new value and then pass it again to javascript.
how do i do it without a page reload?
to make things more clear, i just need to get the next incremented value of the php variable. i want php to get the next ++ value from the DB and pass it back to JS.
please help me do this. ;))
Maybe I'm misunderstanding,
But can't you just have a PHP script that returns a string, or a JSON object containing the value(s) you need, and then have the javascript function grab it from the server and update the properties in the link/image?
Also, typically you would get $row from mysql_fetch_assoc() or a similar function -- by calling the server again, re-querying the database, and iterating over mysql_fetch_assoc the necessary number of times, you're probably wasting time. Wouldn't it be easier for the PHP script to grab all of the rows, store them in JSON objects, and then (rather than using AJAX) having the javascript iterate through the JSON object and update the properties on each click?
update:
JSON is a text-based way to represent an object in JavaScript. Think of it like a multi-demensional array. http://en.wikipedia.org/wiki/JSON
You'll have a PHP script write a JSON object to a variable, which you would echo into a <script> tag like echo "var rows = {$JSON_obj};";. In javascript you would start with rows[1] and then each time the link is clicked, move to the next rows[i] or whatever.
jQuery is your friend here. It'll make AJAX (for wherever else you use it) and changing HTML elements much easier. I moved to jQuery and have never, ever looked back to the old ways. http://jquery.com/
I don't have an example on hand right now, but it's a pretty simple concept. I'm sure you'll be able to code this up with little effort.
you can write it to the standard output in PHP via echo $value; and finish PHP script there. javascript will then fetch the value and return it in the AJAX processing function.

Categories