I try to send messages from PHP server to Node.js server. The purpose of the Node.js server is to convey the message forward using the Socket.io and Express.
$NodePage = file_get_contents($NodeServer. "/index.html?&message=". $message);
The server always returns empty string and do not send a message. Same URL in browser working Ok and a message is sent correctly. I also try redirect command.
header("Location: http://xxxxxxx.fi/index.html?message=". $message);
Also returns empty string. Working Ok in web browser. I make PHP calls from C# client.
HtmlWeb web = new HtmlWeb();
string tempURL = _url + _htmlMessageStr +
"?message=" + msg.fullMessage) ;
HtmlDocument doc = web.Load(tempURL);
HtmlNodeCollection tags =
doc.DocumentNode.SelectNodes(_nodeText);
_retVal = parse(tags[0].InnerHtml);
Any other data is ok from PHP, except node data (empty string). I tried to retrieve data from other Node.js servers and it restore the data correctly. Something is wrong with my Node.js server but what? Server is hosted by hosting company. The server does not run anything other than Node.js.
This needs to be enabled in the php.ini. The option you are searching for is "allow_url_fopen" and set it to true.
http://php.net/manual/en/filesystem.configuration.php
I found the problem. You can not use the file_get_contents command to connect Socket.io to the Node.js server. You need to connect to the socket.io.
This article explains how to do it.
enter link description here
I've recently build an socket with Ratchet (http://socketo.me/) in Symfony ( PHP framework ) with JS/jQuery. The problem im facing is that the socket IP+PORT are just visible in the js file, so everyone can connect with it using the console or something.
I'm executing several things with the socket, that impacts everyone's view that's connected with it.
Now I'm just able to open a new connection through the console using:
var socket = new socket('http://www.IP:PORT');
Then I'm able to use the send command to execute things that only the server should have access to. Like this:
socket.send(JSON.stringify({info: 'information', action: 'runAction'}));
Is there anyone that can explain me how to keep these send calls privately so not everyone can just have access to these actions and call them?
You try to have these things stored in your php code and make an api say /getSocketDeatils
Now make an authenticated REST call to your api and make the socket when your app starts.
This is just one way there can be multiple other
I am attempting to follow this tutorial - https://developers.google.com/maps/articles/phpsqlajax_v3
I have a rather fundamental & simplistic question.
Using firefox, I can see this error when I load the html page with the php and javascript built in, as taken from the tutorial above.
TypeError: xml is null
The MySQL database I have is on my computer and is not hosted on the website in question. So, when I run the php script that exports the xml in the command line, I can see that it functions correctly.
I attempted to add my ip address to the phpsqlajax_dbinfo.php file, such that -
<?php
$username="";
$password="";
$database="";
$host="";
?>
But this results in a connection error.
What changes do I need to make for this to be able to reference the database on my computer, rather than one on the site?
EDIT
I have verified that the host, database, password and username fields are correct. I am able to run the phpsqlajax_genxml.php file from the command line.
If you run MySql on your computer use "localhost" as a server in phpsqlajax_dbinfo.php:
$server="localhost";
Your MySql DB is probably not set up to listen to your public IP, if you really want to use your IP you can add it to my.cnf, but I would really recommend using localhost:
bind-address = your_ip
Can JavaScript connect with MySQL? If so, how?
Client-side JavaScript cannot access MySQL without some kind of bridge. But the above bold statements that JavaScript is just a client-side language are incorrect -- JavaScript can run client-side and server-side, as with Node.js.
Node.js can access MySQL through something like https://github.com/sidorares/node-mysql2
You might also develop something using Socket.IO
Did you mean to ask whether a client-side JS app can access MySQL? I am not sure if such libraries exist, but they are possible.
EDIT: Since writing, we now have MySQL Cluster:
The MySQL Cluster JavaScript Driver for Node.js is just what it sounds like it is – it’s a connector that can be called directly from your JavaScript code to read and write your data. As it accesses the data nodes directly, there is no extra latency from passing through a MySQL Server and need to convert from JavaScript code//objects into SQL operations. If for some reason, you’d prefer it to pass through a MySQL Server (for example if you’re storing tables in InnoDB) then that can be configured.
JSDB offers a JS interface to DBs.
A curated set of DB packages for Node.js from sindresorhus.
If you want to connect to a MySQL database using JavaScript, you can use Node.js and a library called mysql. You can create queries, and get results as an array of registers. If you want to try it, you can use my project generator to create a backend and choose MySQL as the database to connect. Then, just expose your new REST API or GraphQL endpoint to your front and start working with your MySQL database.
OLD ANSWER LEFT BY NOSTALGIA
THEN
As I understand the question and correct me if I am wrong, it refers to the classic server model with JavaScript only on the client-side. In this classic model, with LAMP servers (Linux, Apache, MySQL, PHP) the language in contact with the database was PHP, so to request data to the database you need to write PHP scripts and echo the returning data to the client. Basically, the distribution of the languages according to physical machines was:
Server Side: PHP and MySQL.
Client Side: HTML/CSS and JavaScript.
This answered to an MVC model (Model, View, Controller) where we had the following functionality:
MODEL: The model is what deals with the data, in this case, the PHP scripts that manage variables or that access data stored, in this case in our MySQL database and send it as JSON data to the client.
VIEW: The view is what we see and it should be completely independent of the model. It just needs to show the data contained in the model, but it shouldn't have relevant data on it. In this case, the view uses HTML and CSS. HTML to create the basic structure of the view, and CSS to give the shape to this basic structure.
CONTROLLER: The controller is the interface between our model and our view. In this case, the language used is JavaScript and it takes the data the model send us as a JSON package and put it inside the containers that offer the HTML structure. The way the controller interacts with the model is by using AJAX. We use GET and POST methods to call PHP scripts on the server-side and to catch the returned data from the server.
For the controller, we have really interesting tools like jQuery, as "low-level" library to control the HTML structure (DOM), and then new, more high-level ones as Knockout.js that allow us to create observers that connect different DOM elements updating them when events occur. There is also Angular.js by Google that works in a similar way, but seems to be a complete environment. To help you to choose among them, here you have two excellent analyses of the two tools: Knockout vs. Angular.js and Knockout.js vs. Angular.js. I am still reading. Hope they help you.
NOW
In modern servers based in Node.js, we use JavaScript for everything. Node.js is a JavaScript environment with many libraries that work with Google V8, Chrome JavaScript engine. The way we work with these new servers is:
Node.js and Express: The mainframe where the server is built. We can create a server with a few lines of code or even use libraries like Express to make even easier to create the server. With Node.js and Express, we will manage the petitions to the server from the clients and will answer them with the appropriate pages.
Jade: To create the pages we use a templating language, in this case, Jade, that allow us to write web pages as we were writing HTML but with differences (it take a little time but is easy to learn). Then, in the code of the server to answer the client's petitions, we just need to render the Jade code into a "real" HTML code.
Stylus: Similar to Jade but for CSS. In this case, we use a middleware function to convert the stylus file into a real CSS file for our page.
Then we have a lot of packages we can install using the NPM (Node.js package manager) and use them directly in our Node.js server just requiring it (for those of you that want to learn Node.js, try this beginner tutorial for an overview). And among these packages, you have some of them to access databases. Using this you can use JavaScript on the server-side to access My SQL databases.
But the best you can do if you are going to work with Node.js is to use the new NoSQL databases like MongoDB, based on JSON files. Instead of storing tables like MySQL, it stores the data in JSON structures, so you can put different data inside each structure like long numeric vectors instead of creating huge tables for the size of the biggest one.
I hope this brief explanation becomes useful to you, and if you want to learn more about this, here you have some resources you can use:
Egghead: This site is full of great short tutorials about JavaScript and its environment. It worths a try. And the make discounts from time to time.
Code School: With a free and very interesting course about Chrome Developer tools to help you to test the client-side.
Codecademy: With free courses about HTML, CSS, JavaScript, jQuery, and PHP that you can follow with online examples.
10gen Education: With everything you need to know about MongoDB in tutorials for different languages.
W3Schools: This one has tutorials about all this and you can use it as a reference place because it has a lot of shortcode examples really useful.
Udacity: A place with free video courses about different subjects with a few interesting ones about web development and my preferred, an amazing WebGL course for 3D graphics with JavaScript.
I hope it helps you to start.
Have fun!
No, JavaScript can not directly connect to MySQL. But you can mix JS with PHP to do so.
JavaScript is a client-side language and your MySQL database is going to be running on a server
Bit late but recently I have found out that MySql 5.7 got http plugin throuh which user can directly connect to mysql now.
Look for Http Client for mysql 5.7
I think you would need to add something like PHP into the equation. PHP to interact with the database and then you could make AJAX calls with Javascript.
Simple answer is: no.
JavaScript is a client-side language that runs in the browser (node.js notwithstanding) and MySQL is a server-side technology that runs on the server.
That means you typically use a server-side language like ASP.NET or PHP to connect to the database.
YES? Have a look a meteor. Links:
http://meteor.com/screencast and http://net.tutsplus.com/tutorials/javascript-ajax/whats-this-meteor-thing/
I don't understand how it is done. But Nettuts+ put this thing in the javascript-ajax section, maybe magic happens.
It also shows some way to connect and insert to MongoDB with JS, like this:
Products.insert({Name : "Hammer", Price : 4.50, InStock : true});
Products.insert({Name : "Wrench", Price : 2.70, InStock : true});
Products.insert({Name : "Screw Driver", Price : 3.00, InStock : false});
Products.insert({Name : "Drill", Price : 5.25, InStock : true});
Yes. There is an HTTP plugin for MySQL.
http://blog.ulf-wendel.de/2014/mysql-5-7-http-plugin-mysql/
I'm just googling about it now, which led me to this stackoverflow question. You should be able to AJAX a MySQL database now or in the near future (they claim it's not ready for production).
Depending on your environment, you could use Rhino to do this, see Rhino website. This gives you access to all of the Java libraries from within JavaScript.
You can send AJAX requests to some server-side RESTful wrappers for MySQL, such as DBSlayer, PhpRestSQL or AlsoSQL (for Drizzle, a fork of MySQL).
Yes you can. MySQL connectors use TCP for connection, and in JS there is an little modified version of TCP client called Websocket. But you can't directly connect to MySQL server with websocket. You will need some 3rd party bridge between websocket and mysql. It receive query from websocket, send it to mysql, response result and resend to JS.
And this is my example bridge written in C# with websocket-sharp library:
class JSQLBridge : WebSocketBehavior
{
MySqlConnection conn;
protected override void OnMessage(MessageEventArgs e)
{
if (conn == null)
{
try
{
conn = new MySqlConnection(e.Data);
conn.Open();
}
catch (Exception exc)
{
Send(exc.Message);
}
}
else
{
try
{
MySqlCommand cmd = new MySqlCommand(e.Data, conn);
cmd.ExecuteNonQuery();
Send("success");
}
catch (Exception exc)
{
Send(exc.Message);
}
}
}
protected override void OnClose(CloseEventArgs e)
{
if (conn != null)
conn.Close();
}
}
JS side:
var ws = new WebSocket("ws://localhost/");
ws.send("server=localhost;user=root;database=mydb;");
ws.send("select * from users");
JavaScript can't connect directly to DB to get needed data but you can use AJAX. To make easy AJAX request to server you can use jQuery JS framework http://jquery.com. Here is a small example
JS:
jQuery.ajax({
type: "GET",
dataType: "json",
url: '/ajax/usergroups/filters.php',
data: "controller=" + controller + "&view=" + view,
success: function(json)
{
alert(json.first);
alert(json.second);
});
PHP:
$out = array();
// mysql connection and select query
$conn = new mysqli($servername, $username, $password, $dbname);
try {
die("Connection failed: " . $conn->connect_error);
$sql = "SELECT * FROM [table_name] WHERE condition = [conditions]";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$out[] = [
'field1' => $row["field1"],
'field2' => $row["field2"]
];
}
} else {
echo "0 results";
}
} catch(Exception $e) {
echo "Error: " . $e->getMessage();
}
echo json_encode($out);
No.
You need to write a wrapper in PHP, and then export the returned data (probably as Json). NEVER, get from your "_GET" the SQL code, as this is called an SQL injection (people who learn this will have full control over your database).
This is an example I wrote:
function getJsonData()
{
global $db;
if (!$db->isConnected()) {
return "Not connected";
}
$db->query("SELECT * FROM entries");
$values = array();
while( $v = $db->fetchAssoc()){
$values[] = $v;
}
return json_encode($values);
}
switch (#$_GET["cmd"]){
case 'data':
print getJsonData();
exit;
default:
print getMainScreen();
exit;
}
Do learn about SQL injections please.
You can connect to MySQL from Javascript through a JAVA applet. The JAVA applet would embed the JDBC driver for MySQL that will allow you to connect to MySQL.
Remember that if you want to connect to a remote MySQL server (other than the one you downloaded the applet from) you will need to ask users to grant extended permissions to applet. By default, applet can only connect to the server they are downloaded from.
If you're not locked on MySQL you can switch to PostgreSQL. It supports JavaScript procedures (PL/V8) inside the database. It is very fast and powerful. Checkout this post.
Of course you can. In Nodejs you can connect server side JavaScript with MySQL using MySQL driver.
Nodejs-MySQL
I want to build an entire web app using only Javascript and MYSQL . How can I go about this if it's possible.
Try something like Jaxer, which will allow you to execute JavaScript on the Web Server and query databases.
Here are some syntax examples and usages:
Database, file, and socket access from JavaScript
alt text http://jaxer.org/images/Picture+4_0.png
Easily create RESTful JSON data services
alt text http://jaxer.org/images/Picture+6.png
Directly call server-side functions from the browser
alt text http://jaxer.org/images/Picture+2_0.png
You can do it with Jaxer. There are some screencasts that'll get you started. Also check out project Phobos. Jaxer integrates nicely in Aptana studio, Phobos in Netbeans.
If you can run javascript on the server, you can build a web-application with it (without the need for any other language like PHP etc.). Search the web for 'connection string mysql' to find out how to connect to your mySQL database and use ADO/ODBC. You'll need the MySQL ODBC-connector on the MySQL server.
Here's an example database connection (where MySQL server resides on the same server as the web server):
function connectDB()
{
var connectStr = "DRIVER={MySQL ODBC 3.51 Driver}; " +
"SERVER=localhost; " +
"PORT=[MySQL server port];" +
"DATABASE=[your database]; " +
"UID=[username];PWD=[password];" +
"OPTION=3",
conection = Server.CreateObject("ADODB.Connection");
//ERRID=>lib::connectDB::open
try {connection.Open(connectStr) }
catch(e) {errAlert(e,'rs::connectDB','connection failed',1) }
return connection;
}
(Where errAlert is a custom function to return the error)
You could write your application entirely in client side javascript with AJAX / REST calls to your database server - using something like CloudKit on your server (or CouchDB, which features a native JSON HTTP interface). On the client side, Dojo or YUI abstract out a great deal of the IO handling…
It's quite possible to write a web application using only javascript. One the key benefits of that is that since all code runs locally, you can make an application which doesn't require online connectivity.
The main detractor though, is that you can't hook it up to a database. But there are alternative data storage hacks you can use.
One example of such a javascript application is TiddlyWiki which is a personal wiki, contained in a single html file. The javascript application rewrites that html file, so you can carry it with you on a USB-drive or something.
You could look at triplify which should expose your database as json and rdf. I haven't actually used this but I would imagine that would let you bypass writing any server side js and talk to the database directly in a language javascript understands, using an ajax request and json.
You can build client-side applications in javascript, with an embedded database. HTML 5 has support for databases, and a couple of browsers have already implemented this part of the spec (safari, firefox with the gears plugin).
But this is only for clientside usage. You wont be able to share the database with other users. Also you can select which database you want to use. I think gears uses sqlite.
You will not be able to use Javascript and MYSQL without using something such as PHP on the server side to bridge the gap between the database and the Javascript on the client side.
Edit: I may be wrong, however I have no idea how you would run Javascript on the server side.