I'm stumped I've looked all over the internet and found no real way to access mysql within javascript, therefore I can't do what I need to.
Basically my javascript code is loading random websites using Iframes and I would like those list of sites to be pulled from a mysql database, but I see no way in doing this. I've tried using php's include function in javascript with no luck.
Any ideas?
More information:
Im using a script I have on my server called sitelist.js for the source of the script. All that script contains is the following:
targetURLs = [
'http://www.aol.com',
'http://www.yahoo.com',
'http://www.bing.com'
];
But i would like it to load websites from the mysql database instead of having those websites.
-
First off, javascript should not have direct access to your database. Second, what do you mean bt "I've tried using php's include function in javascript"?Ivan– Ivan2012年01月04日 01:20:19 +00:00Commented Jan 4, 2012 at 1:20
-
3You're misunderstanding the role of javascript. Mysql runs on the server, and so must be accessed by another language on the server. Javascript runs on the client's machine, and therefore cannot access mysql directly. Look into AJAX, which lets javascript call your PHP files (and more).Ben D– Ben D2012年01月04日 01:21:21 +00:00Commented Jan 4, 2012 at 1:21
-
2Why don't you just make a PHP script that returns a JSON list of those website strings. Then you can do whatever you want with the list in javascript.styfle– styfle2012年01月04日 01:24:50 +00:00Commented Jan 4, 2012 at 1:24
2 Answers 2
Try something along these lines, with $sites being your array of urls from the database...
<script type="text/javascript">
var sites = JSON.parse("<?php echo addslashes(json_encode($sites)); ?>");
// now do stuff with sites.
</script>
4 Comments
This can't be done. Javascript (at the moment) doesn't have raw sockets. As a result, you can't call off to non-http network services like mysql. You could however wrap it using some horrible ajax API (SQL from javascript, no matter how it's accomplished, is a horrible idea).