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.
Related
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.
Im using this ajax function to insert a product from an eccommerce site into the database.
I see that this method is very insecure, some experienced users with programming knowledge can use this ajax and insert products , or something else.
I read in others post that propose as a solution to use hidden input fields with a token, but as I said some experienced users with programming knowledge will find it.
Is there some REAL way to make this "add product" function secure without refreshing the page in every insert?
$(document).on('click','#save',function(e) {
var vidArt = $(".imagepreview").attr('value');
$.ajax({
data: {idArt: vidArt},
type: "POST",
url: "classes/add_to_cart.php",
success: function(data){
}
});
});
It doesn't matter if you design your API to be used by Ajax or by whole new page loads. An HTTP request is an HTTP request and people can make whatever HTTP requests they like.
There is no way to ensure that an HTTP request comes from code you have written.
However, that should not matter. If you are going to let the user add_to_cart using the user interface you designed, why worry if they add_to_cart using a user interface they designed?
If you want to impose restrictions (such as "Only products with an X in the name can be added") then impose those restrictions using your server-side code and not the user interface.
I'm new to Javascript and I couldn't find this information so far.
I'd like to create a button which, when clicked, creates a new entry in my database, and another one which removes a specific entry when clicked. The reason I don't want to use PHP is because I don't want the page to reload when the button is clicked.
Where can I find information on how to achieve this?
EDIT
Okay I found this:
<script type="text/javascript">
$(document).on('click','#save',function(e) {
var data = $("#save-form").serialize();
$.ajax({
data: data,
type: "post",
url: "save.php",
success: function(data){
alert("Data Save: " + data);
}
});
});
</script>
My HTML:
<form id="save-form" method="post">
<input id="save" type="submit" value="Save" name="save-submit" />
</form>
My PHP file (save.php), which creates a new record in my database, works, but only if my form's action is action="save.php". What should I put in my form's action to trigger the script?
Also, it seems like the submit button still reloads the page (even if my form has no action).
You cannot directly communicate with Database from your javascript. What you can do is like use Ajax to communicate with your server side language(It can be anything like PHP,.net,Java etc..) and with the help of server side language communicate with Database
If you are using Ajax then you can make the way asynchronous.
If you really want use JavaScript to communicate with Database then you can go for Node.js(There you can use javascript syntax) but still it is a server side language based on Javascript and its not related to your browser
Why you cannot connect database from client side ??
The main reason is Security. You're not granting DB access to anyone but web server/app user.
The other few reason are
DB load reduction
Scalability Issues
Encapsulation Issues
Ability for fault tolerance
See there are ways to insert into db with using PHP and without doing a postback.
But specific to your question you can find answer in below link
Insert Record in Database Using Textboxes in JavaScript
Not only in PHP but also in any other programming language(e.g: asp.net,java etc) you can create an entry and remove a specific entry without loading the page.
You need to use the plugin of jquery which is called 'ajax'.
Using 'ajax' you can send data to the server without loading the page. And after having your data in server side, you can do whatever you want to do.
You will find ajax documentation here: http://api.jquery.com/jquery.ajax/
Same kind of question answered here: Delete record without refresh page using php
If you having any problem,let me know.
Here is an example of a simple client server communication model. Client codes are executed at the browser which is JavaScript. The Server side codes are PHP, Nodejs, java, python etc) Which resides on server only. Client sends a request to the server for a resource. And server and back a response with an HTTP status. Which represents the status of a response. The client side JavaScript cannot communicate directly with the server database. What it does is sending a request to the server which will eventually trigger the actual code in server which inserts the data into the server.
The one you mentioned is the ajax method which sends an HTTP request without actually reloading a page. You can also use a form to post data into the server without ajax which will reload the page.
You must validate the user inputs in server side even though you will be validating it in the client side.
You can use the event.preventDefault() to prevent the form submit and then insert it via ajax.
$(document).ready(function() {
$('#save-form').on('submit', function(e){
e.preventDefault();
var data = $("#save-form").serialize();
$.ajax({
data: data,
type: "post",
url: "save.php",
success: function(data){
alert("Data Save: " + data);
}
});
});
});
I got a URL from a ecommerce website and when i access it i get all the last 5 products that i've visited in their site. I don't know how it works, i guess it's because of the cookie that this ecommerce website have left in my browser.
I would like to use this URL to show in my website something like this: "The Last 5 Products You Have Seen at X Ecommerce Website".
But to do that this URL must be executed in somehow in the client side and i will still need to get the JSON content returned by this URL.
Is there exist anyway to do that by using PHP or any other web technology?
Thank you!
It might be cookies, localStorage (there are other APIs to save data on local computer, imo they are unused or deprecated e.g. openDatabase) or last views could be connected with account and saved on internal database.
You should use AJAX, but by default in browser mechanism called CORS blocks all requests coming from other domain than resource.
In PHP you can download external page using file_get_contents function or cURL library, but without localStorage/cookies (which can be accessed from JS executed on domain, where that cookies are saved).
AJAX is your option for client side requests. Here's the jQuery guide for it.
https://api.jquery.com/jquery.ajax/
Here's a quick example:
$.ajax({
url: "http://ecommerce.com/your/url/here",
method: 'get',
dataType: 'json', //if you're sure its returning json you can set this
success: function(data) {
//handle success json here
//be sure that you're going to receive json though, possibly could receive some other data type and you should handle appropriately
},
error: function(error) {
//handle error json here
}
});
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
});