Inserting into MySQL database with javascript [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I'm currently working on a school project and I need some help. I ran into a problem when trying to put the data I read from another IP address (using AJAX) into a MySQL database. I tried using node.js but because I'm calling the function when I press the button on a webpage it doesn't work... So any suggestions or tips on how to make node.js work.
ajax function:
function AddShoots() {
$.ajax({
method: "POST",
dataType: "json",
url: "http://192.168.1.8",
success: function (html) {
for ($i = 0; $i < html.length; $i++) {
console.log(html[$i]);
}
},
});
}
The data I get and would like to insert into database:
EDIT: additional explanation
sorry for the HTML/CSS there was an error while copying. To clarify my endpoint I have a python image recognition program written on raspberry PI, the Raspberry PI server that is on the IP returns the numbers seen in the picture, I would like to insert the numbers into a MySQL database and I need help with how to do that because I only inserted data into tables with PHP before, but I can't do this in this case because I'm using AJAX (at least not with my knowledge) I hope this explains everything better.
Another edit:
A picture that might help with understanding (I'm super bad at explaining sorry English is not my primary language that's why I have bad expressions and a hard time explaining some stuff).

Sounds like you're getting your technologies mixed up a bit.
Lets clarify a few terms first:
NodeJS
Is a JavaScript runtime for server-side or backend code.
Runtime
An environment for code to execute like NodeJS or a web browser.
Server-Side
This refers to code running on a server. Could be PHP, Java, Python etc... or even JavaScript if you're using Node.
Backend
Usually means the same thing as "server-side" when people say "backend".
Frontend
In this context, "frontend" is referring to code being executed in a web browser.
AJAX
A style of HTTP request that a browser can use to send and fetch data without reloading the current page.
Now that we have that out of the way...
Node is a server-side runtime for JavaScript, so your JS code running in the browser has no way to talk to your Node code directly.
If you want to click a button in the browser and see data get written to your database you have to make an AJAX call to a url that your backend is listening to (known as an endpoint or a route).
It's a bit difficult to interpret your intentions from your example but I think you mean to send a POST to http://192.168.1.8. So you'll need a route configured in your Node app that can handle the AJAX request, and from there you can write the data to your database.
Of course you'll also need to pass the data with the request. That gets passed along with the options parameter in your $.ajax(/* ... */) call.
At a high level this is what I believe you're trying to achieve:
So basically your app should have at least two files:
index.html This will have your button as well as the JS code that fetches data from your Pi. This "front-end" JS will also have to send an AJAX request to your Node app.
app.js This will be your Node app. It will have to expose an endpoint that your front-end code can send data to. Inside the function of that endpoint, you'll handle writing the data to your database.
There's a library called Express that will help you make your endpoint. I recommend following their Getting Started guide: https://expressjs.com/en/starter/installing.html
Update
I see you updated your answer with a diagram. I assumed your mental model was probably exactly like that, which is why you're having a hard time.
When a user visits a url such as https://stackoverflow.com for example, the request doesn't go to the web browser. The request has to go through a server first. When you use Node, your app essentially is the server, and is responsible for returning the correct response.
In your case the response would be an HTML file like index.html for example.
That index.html is the webpage and it is going to contain your "front-end" JavaScript code, which can communicate to your Raspberry Pi server over HTTP to get that image data you're talking about.
JavaScript running in the browser has no way to communicate to a SQL database directly. So you have to send a request over the network to your Node service. Inside your backend application you can write the data to a MySQL database with the help of packages you can get from NPM. Here's an example of one: https://www.npmjs.com/package/mysql
Update 2
It sounds like you're more comfortable using PHP. You can swap NodeJS out with PHP and my diagram would still represent what you want to achieve at a high level. The key difference is you won't have to figure out how to set up a "route".
With PHP you can just have a file named something like SaveMyData.php:
<?php
// Get the body of the POST request
$data = file_get_contents('php://input');
// Decode the JSON string so you can work with it in PHP
$decodedData = json_decode($data);
// $decodedData is now an array of the data you sent from the browser
foreach($decodedData as $row) {
// write the row to your database here
}
Then the "endpoint" (making some assumptions about how your serving your app) is just http://localhost:8080/SaveMyData.php and that becomes the URL you pass to your AJAX call from the browser.
Your AJAX request would look something like:
function AddShoots() {
$.ajax({
method: "POST", // the post to your Pi I'm assuming?
dataType: "json",
url: "http://192.168.1.8",
success: function (data) {
$.ajax({
method: "POST", // this is going out to your PHP backend
dataType: "json",
url: "http://localhost:8080/SaveMyData.php",
data: data,
success: function (response) {
// do stuff with the response if you'd like
})
});
},
});
}
Tons of "best practices" are being violated here, but for the purposes of a school assignment this should get you pointed in the right direction.

Related

Changing a ajax request to a different php file vulnerability, potential exploit clarification

I am creating an application, that accepts a ajax call (jquery) and returns the validated user an entry token to the website.
Say for example the ajax is called checkAuth.php and there are all the other php files in this directory. By changing the JS to validate another file like checkMail.php for example:
var xmlRequest = $.ajax({
url: "checkAuth.php",
processData: false,
data: xmlDocument
});
change the url to checkMail.php and create a vulnerability in the site?
var xmlRequest = $.ajax({
url: "checkMail.php",
processData: false,
data: xmlDocument
});
Although the result would return a different object but by doing so would this create an "open door" perhaps where the malicious user would keep sending requests in order to gain access? I understand that the user would have to know that the php file exists however I am unsure how to process this securely whilst maintaining my directory structure.
Please note this is not my actual code and I cant clarify the answer with these other posts or I am not understanding this correctly.
Edit: In addition - would this mean that any site using jquery would be able to ajax request any file from the server and create a vulnerability?
How to authenticate an AJAX request to a PHP file?
Question regarding Ajax Hacking
Ajax Security questions
How to send secure AJAX requests with PHP and jQuery
In general, any AJAX request can access all files which accessible via http request like as user types full URL as the browser address.
So, you have to check security token or something else in the begining of PHP-scripts.
You can restrict access to folders or files using .htaccess, see https://stackoverflow.com/a/11729748/3325396

How to use JavaScript/Ajax and Python to edit local SQL database?

I've developed the front-end of a web site using JavaScript.
I have a button that when it's clicked retrieves an integer value from another object on the website.
I have a local SQL database. How do I make SQL calls when this button is clicked?
I've seen answers with JavaScript/Ajax and PHP, but I don't want to use PHP.
Using JavaScript only, can I open a local SQL db and make SQL calls? If yes, how?
If I can't do this using JavaScript only, can I use JavaScript/Ajax and Python? If yes, please post a reference or simple example.
Technically it is possible to connect to a database using client-side JavaScript. However, as others have already pointed out, doing so is considered to be really bad practice for a few reasons - the most important of them being security.
When the browser is asked to load a certain page it will go ahead and ask the server for the content that is found at that URL. This means HTML files, external JavaScript files, images, stylesheets and other resources that are needed in order for the page to get rendered. Since the user has access to the these files, especially your JavaScript code, it means he has access to your database credentials. You could try to minify/obfuscate the code, but that won't make it any safer.
If you do understand all the consequences and for some reason you still want to do it, take a look at this example.
The best way to go at it is to have a server handle the interaction with the database. Depending on your language of choice, you could build that part of the application using PHP (among with an HTTP server such as Apache), Java, Python and so on. You could even use JavaScript (see Node.js).
Since you asked for a Python snippet, here's one that connects to a MySQL database and creates an HTTP server that listens for connections on port 8080. For each GET request it will receive, the script will query the database and send back the result as text/html.
#!/usr/bin/python
import MySQLdb
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
PORT_NUMBER = 8080
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
# prepare a cursor object using cursor() method
cursor = db.cursor()
# execute SQL query using execute() method
cursor.execute("SELECT VERSION()")
# Fetch a single row using fetchone() method
data = cursor.fetchone()
self.send_response(200)
self.send_header('Content-type','text/html')
self.end_headers()
self.wfile.write(data)
return
try:
db = MySQLdb.connect(host="localhost", user="root", passwd="yourpwd", db="pw_exam")
server = HTTPServer(('', PORT_NUMBER), myHandler)
print 'Started httpserver on port ' , PORT_NUMBER
server.serve_forever()
except KeyboardInterrupt:
print '^C received, shutting down the web server'
server.socket.close()
You can't do this from the javascript in the browser for a simple reason - if your database is available to your javascript code, it is also available for any web site user. And someone will just delete all your data or will replace it with something funny.
That is why we usually also have the server-side application and it can basically be in any language - php, python or javascript.
And there are frameworks and libraries to simplify your job also for any language.
For example, for python you can use flask and sqlalchemy.
If you want javascript everywhere, then use nodejs on the server and expressjs as server-side framework is one of most popular options for node. And you can find node.js packages to make SQL queries to your database too.
The general flow of your application can look like this:
Your client-side application is opened in the browser and it needs some data from the database
It sends the AJAX request to the sever
Server makes a database request and returns the data as json
Client-side application displays this data
It works similar when data need to be modified.
The difference here is that your database is "covered" by server side, so you can be sure that only allowed operations are performed.
Like nobody is able to drop the database, or only a registered user can edit the profile data (and only own profile data editing is possible), etc.
JQuery is a brilliant way to create live Database feeds in Website development. You can simple import the JavaScript files from CDN or Google or download and use it here: https://jquery.com
Front end:
$(document).ready(function(){
$("#idHere").click(function(){
var testdata = document.getElementByID("#idHere").value;
var anothertestdata = document.getElementByID("#idHere").value;
$.ajax({
url: "/inc/Database.php",
data: {
example: testdata,
anotherexample: anothertestdata
},
success: function( data ) {
$( "#idHere" ).html( "<strong>" + data + "</strong> " );
}
});
});
});
PHP file:
if(isset($_GET['testdata'])):
$db = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
$query = "SELECT * FROM TABLE";
$result = mysqli_query($db, $query);
while($row = mysqli_fetch_array($result)):
echo $row['CollumnName'];
endwhile;
$db->close();
endif;
Anything echo'd will show in the response.
Using JavaScript to open a Database is hard, long and has MANY security issues. I would not recommend in doing so.

How to manually submit a post request to a server?

I am looking for a way to manually submit a Post request to a server, without using the website's UI. I can see the request headers and the post parameters in Firebug when I perform the action manually (clicking the UI's "submit" button). I am hoping there is a way to reverse engineer some Javascript using these headers and parameters so that we can automate this process.
Reason: My company recently purchased some process automation software that enables us to write automation bots that access out business partner's portal site and automatically adjust our digital marketing bids. For one of our partner sites, front-end manipulation doesn't appear to work, because the Post request is submitted via AJAX.
The software does allow us to execute custom javascript within the environment, so I am trying to construct some Javascript using the headers and request parameters.
Is there a standard template into which I can plug these parameters to execute Javascript that will send the Post request to the server?
Thank you
UPDATE:
Thank you all for your help! I've made some progress but am still having difficulty implementing the solution within the software.
The following request works when I run the code in Firebug in Firefox:
$.ajax({
type: "POST",
url: "http://acp.example.com/campaigns/122828",
data: "data-string"
});
However, the software we're using might be a little out of date and I'm not sure it recognizes the AJAX syntax.
Is there a way to effectively write the same statement above, but in Javascript rather than AJAX? Then I think it would work.
You can use AJAX to post data to a server without any direct UI interaction. I will break down a simple jQuery example below:
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
});
$.ajax Is a method offered by the jQuery framework to make AJAX requests simple and cross browser compatible. As you can see I have passed in a JSON object containing various values:
type - This is the first key I have specified, in this instance you'll want this to be of the value POST as this determines the HTTP Request Method.
url - This specifies the server end point, for example: post/data/here.php would post the data to that url so that it can be picked up and handled correctly.
data - This key expects a JSON object, string or array of data to send in the POST request.
success - This key expects a function, it is called on the server's response to the request, with any relevant data passed through.
More documentation is available at: http://api.jquery.com/jquery.ajax/
If all you want to do is POST data, no JavaScript needed.
You should be able to use a browser extension for this. I have one called REST Console that is similar to what you describe. I believe REST Console is for Chrome only, but a quick Google search yielded a similar looking extension for FireFox called RESTClient.

Minimising server access with heavy javascript webpage

I've been working on a webpage that has a PHP backend to access a database and generate the basic page HTML. Once loaded, all user interaction is controlled by javascript.
To communicate back to the server I'm using the traditional post method:
jQuery.ajax({
type: 'POST',
url: ajaxurl,
data: postdata,
success: function(data) {
// PHP returns data
}
});
However, the moment I start communicating back to the server using this method, I create lag in the UI and the user experience suffers, especially if they have a slow connection. I've got the usual loading gif spinners and progress bars where appropriate, but I want the UI to be as instant as it can be.
The primary reason I'm going back to the server is to grab information from the database. I've been wondering if there are ways to remove this?
1) Download the database data and access it directly in Javascript? Completely removing to need to go to the server to retrieve data. Is this possible? Are there any libraries for this?
2) In general, are there more efficient ways to retrieve data from a server than using the post method?
Some possible solutions are to preload data where possible, turn on caching on server side if needed, optimize your queries to database, do not return whole html from POST etc.

What is the right way for Searching functions in a Website with Javascript?

Its known that interactions between Javascript and SQL-Databases are not very secure. But most Websites use it cause the Webside doesent reload to show matches in a search.
With PHP it isn't possible to change Page-Contents without a completely Page-Refreshing.
Witch is the right way to get Data from SQL with Javascript without security-neglects.
Aspeccialy for a Searching function with directly matches in a list.
You can use 2 way to get data from db by using js;
1. Ajax:
function refresh() {
$.ajax({
url:"your url",
method: "GET",
data: your_params,
success: function(response) {
$("#specific_div_id").html(response);
}
});
}
You can do this within an interval like;
setInterval(refresh, 5000);
in order to get content in every 5 sec.
2. Websockets
In AJAX, you are requesting in every 5 secs to get updated content from server. Think that, you are not getting content server pushes updated content to you. In other words, server notifies you on any updated data. You can have a look at Socket.io for an example implementation of websockets. When server notifies you, you can take data and put it related html area
As mention in the commentaries, the best way is to use AJAX, which is an acronym that stands for Asynchronous Javascript and XML.
The last part, XML, is a bit misleading. It kept that name because that's what is was first use for. But AJAX can now be use to make HTTP request and interface with any language, including PHP.
Depending on the technology you are built on, there are several implementation available. Chances are you have jQuery installed already. In that case, jQuery Ajax, and particularly jQuery.get() would address your concerns.
If you are using a router on the backend, you can simply call a route, specifying it as the url, first argument of the function. Otherwise, you can directly call a file by using the relative path from the html page the javascript is embedded in.
jQuery.get will return anything you echo within you server script. In other words, anything that is directly rendered on the page. You can use a callback catch the data returned and process it.
Example :
$.get('/path/to/file.php', function (data) {
console.log('Here is the data received from the server!', data)
// Process data here
});

Categories

Resources