Javascript(Ajax) vs PHP: Generating HTML Elements [duplicate] - javascript

This question already has answers here:
JSON vs HTML Ajax response
(3 answers)
Closed 9 years ago.
Does generating html elements such as table rows with js through a ajax callback function really any slower than php(echo "< tr>< /tr>)? The browser still has to render client-side the information into the table whether its done in php or js.
I couldn't find much information on this subject, so I wanted to get some opinions here. Are there any arguments to not use js to generate elements dynamically from a ajax call?
Note: I originally forgot to mentioned that the table rows would be data from a database.

In your case using ajax is time wasting because it should send request to server, and server should process it, then responding with the result, while using native JS (only javascript) is faster because the server is not included, and using direct print when page loading is fastest.
But if you need to work dynamic tables, you can work on JavaScript without AJAX call, I don't see any reason here to use AJAX for building HTML table.

Its perfectly fine to generate html elements using ajax call. There might arise occasion where you HAVE to return the DYNAMICALLY generated HTML elements.For this you cannot just print it client side since you need the info from the db.

If you have the info to be presented in a tabular form beforehand, meaning before the page is built, then you should use PHP.
If, the data is to be requested at runtime from the server, then AJAX should be used.
If you just want to built tables with no data (or repeating data which is already available on the page) then, using plain JavaScript is the best option.

Suppose you have an existing page with a table
| A | A | A |
| A | A | A |
Now you place an ajax-call reading some data from the server. If you want to replace the whole table it might be usefull to let php create the table, return it to the browser en let javascript replace the entire table.
If you only want the second row to change, you might want php to return an array with values and let javascript replace the cell-contents based on that response.
But one way or the other, you still have to go the circle browser => server => browser. So the few moments javascript takes to alter the page don't add too much time to that.

Related

Using JavaScript function result in PHP

Is it possible to use the results of a JavaScript function in PHP?
Let me break down why. I have a table that has several columns, including a column that gives each row a checkbox. When a user presses an edit button, an onclick event is activated. The onclick event does a few things, but primarily it goes through the table and figures out which checkboxes are clicked, and returns an array of numbers which indicate the IDs of the entries of the selected rows.
What I want to know is how can I take these Ids and use them in my inline php code that should use the Ids to get corresponding data from a database and generate a new table.
Also, is there another way of doing this type of thing? This seems a little convoluted. I've tried XMLHTTPRequests to get the data directly with Javascript but I had trouble/couldn't get past using the GET method of an XMLHTTPRequest. My code would execute, but I wasn't sure how to get/use the data.
Any help is appreciated.
You can't use javascript values in your PHP statements because, imagine that the javascript is a client-side language, so it don't communicate with the server, and imagine that PHP is a server-side language, so it can't communicate with javascript. When you request a webpage, the request go to the server and the server will trait your request, and all output of this request (the webpage) is a code on client-side language and it is rendered with javascript, html and css. So, we can say that javascript have no idea of what is PHP, because, what PHP do is write a full html code and send to your browser render like a response. But you can use Ajax inside your client-side, there is a lot of tools developed in javascript that do the work of make requests to server-sides

Save large data-set to mySQL table from Javascript without POST?

I have a large-ish amount of server-side data that I need to store in a mySQL table. [I'm a novice, working through the learning curve of javascript & php.]
I'm thinking it's best to stringify the javascript array into a JSON object and send that to a PHP page to save to the database. Once the data's in a PHP array, I know how* to get it into the database; I'm just not sure what's the best way to get it there.
I can't POST (like this example) since the maximum length of a POST string is 2048 characters, and I have maybe 10-20kb of data.
I'd rather not use AJAX or Node.js (like this example) for the sake of simplicity, and since this is a one-off (but both on my list to learn in the future!)
Or, would it be best to create a temp text file to the server with javascript, and then call a PHP page to load & process the data? (Although I can't find examples of how to do that without using POST.)
I understand the difference between server-side & client-side (thanks to this great explanation) but the size limit of POST seems to be my issue?
*Also I'm a little unsure as to when/how it's necessary to encode data (like with this deprecated mysql-real-escape-string example) for storage with {json/posting/DB tables/text}. In this case my data could contain 'single' & "double" quotes (but no foreign characters 国外 वर्ण), which [in my short experience] seem like the only times it will be an issue?
Thanks!
The problem is that Javascript is client side language while PHP is server side language. This means that PHP cannot interact with the user without some HTML, CSS or JavaScript and visa-versa, JavaScript can't interact with server side files without some PHP. Why is this? Since JavaScript is client side the user can edit it as they can see the code while with a PHP script it is all on the server and they are not able to see the code, only what it outputs/prints. So in short you cannot do what you are asking without POST or GET and it is not possible to do this without a server side script such as a PHP script (Python is also very useful if you are thinking of learning more about web backends).
There are numerous example of how to do this that you can find with a simple google search, here is a great example send data to MySQL with AJAX + jQuery + PHP
Hope I could clarify your question.

Filtering PDO and MySQL queries with JS/jQuery

Sorry for my ignorance on the lack of knowledge I have on this subject however I cannot find an answer to my question anywhere.
So I have this MySQL table:
Feed_ID Vehicle_ID FullRegistration Colour FuelType Year Mileage Bodytype Doors Make Model Variant EngineSize Price PreviousPrice Transmission PictureRefs ServiceHistory PreviousOwners Description FourWheelDrive Options Comments New Used Site Origin V5 Condition ExDemo FranchiseApproved TradePrice TradePriceExtra ServiceHistoryText Cap_ID
As you can see each column will contain vehicle data.
I have displayed all of the results in the database using PDO onto my front end, all data is displayed in a listing style similar to Ebay.
Now I need to filter these results however I have noticed that many result filter systems are using JS.
Here are some examples so you get a better idea of what I am talking about:
http://www.autotrader.co.uk/search/used/cars/
http://www.motors.co.uk/search/car/
As you can see all the filters are using JS however I am having a problem understanding how JS is filtering the MySQL query?
I know this question might be a little broad but can someone show me an example of how JS can filter PDO results just like the examples I have shown?
Thanks
The first one uses what I suspect to be a combined method of Javascript and a server-side language (it's hard to prove, because I can't see the server-side code involved). For simplicity, I'll assume this server-side language is PHP, though it could easily not be.
Basically, all Javascript is doing on the first website is setting cookies and telling you to refresh the page. Once you refresh, PHP fetches the cookies that Javascript set and filters the results from the MySQL query based on those cookies.
Now, the second one is actually filtering using Javascript, yet at the same time still using PHP (again, it could be any server-side language).
This is a method called AJAX. It is a function built into Javascript which allows you to fetch another page from Javascript (aka. send and receive an HTTP request).
The reason this is useful is because once you've changed an option on that page, Javascript can send an HTTP query using AJAX to something like "http://www.motors.co.uk/search/getcarinfo.php?transmission=manual", allowing PHP to fetch a new dataset from MySQL and return it to Javascript (this probably isn't the API entry point that they use, but it has to be somewhere in their Javascript).
Once Javascript receives the response from that page (usually in JSON or XML form), it can modify HTML to update what's shown on the page.
To answer your question directly, Javascript doesn't filter the data. MySQL filters the data based on a PHP query, which returns its response to the Javascript. Then, Javascript just puts it on the screen.

Getting HTML or JSON response from ajax call, Which is good? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I have a functionality in my project where I have implemented the search functionality.
On submitting the form via ajax, I need to show all the results in a division.
There are two ways I can do this.
Getting the JSON data as ajax response and bind it to the HTML elements.
I can also get the completely formatted HTML response from the ajax call and can directly bind it to the result div on the search page.
So which way is suggestible ?
To make a service (server-side script) the most re-usable or even make it into an API - the suggested way is to return JSON data (converted from data models) to the front end, where using JavaScript you can populate the data to the HTML.
As for the HTML - you can certainly make the server return the response as HTML (setting the correct mime & content type in headers) but this gives the server control over the UI layer and the separation between the interface and the server/db is not balanced properly...
Either option is fine, depending on your how much html there is and how much server-side processing you need to do on the HTML. If it is just a div and a value that needs to be inserted, then I say just go with JSON. The JSON approach will be more lightweight (consumes less bandwidth and keeps the role of the server as an API that is transferable to non web-page requests).
If you need to do a lot of server-side processing and assembling and what you are returning is really a sub-page, then you might consider html from the server. In this case have a partial html file that you read and send (inserting data where relevant) rather than building the html from strings on the fly. If you have a partial file, then you can edit and check it with standard html editors and you can see the html layout easily and it keeps the UI aspects separate from the business logic.
I'd send it as JSON and build the HTML client side for a few reasons:
The JSON payload would be lighter and therefore faster to send over the wire
The API becomes more reusable (if you ever wanted to hook up additional clients that render differently etc.)
If you build the HTML on the client side then it's probably easier to take advantage of templating libraries (e.g. JQuery Templates) or even better, directly binding the data to the UI (such as Knockout)
I always do the JSON response. To me it looks like a much more consistent and flexible way since you can return more data than only presentation. If you still want to return HTML you can also do it through a JSON response:
{
error: false
html: "<div>Done!</div>"
}
I'd send it as a JSON response, too.
As suggested by emiolioicai in his code, with JSON you can easily handle errors. For example:
{
error: true
error-message: wrong parameters
}
If you define your HTML client side, in the future you will be able to use the same AJAX request and customize HTML differently in another part of your website.

Dynamically / iteratively build up page content

I am planning to create a website which will let you iteratively construct an SQL query.
The idea is the following:
while(user wants more where clauses)
{
show selection (html select) for table columns
let user choose one column
upon selection, show distinct values of that column
let user choose one/multiple value(s)
}
I know how to handle the SQL part, but I am not sure how to tackle the iterative building of the page.
So my questions are:
What is the best method to build the page iteratively with the idea sketched above?
What do I do, if the user changes one of the previous selections?
The website will be build with Perl and I am thinking of utilizing Ajax for the dynamic part.
Any help is much appreciated.
If I were to do this, I'd use SQL::Abstract.
UPDATE:
If you don't want to redraw the whole page, you're going to be using AJAX. So find yourself a JavaScript library that you feel comfortable with that includes ajax calls. Jquery has this, a bunch of others do too. People have differing opinions on various libraries.
Anyway, your workflow looks like this:
user submits form
javascript performs client-side validation
javascript submits AJAX-style to the server
Server performs server-side validation, data manipulation, etc.
Server responds with data paylod
client updated the screen based on the contents of the payload.
So let's concentrate on 5 and 6.
Data Payload: The X in AJAX means XML, but many apps send back JSON, or HTML.
Update the Screen:
You can apply HTML directly to the existing page by setting a tag's innerHTML or outerHTML attribute. But that doesn't update the DOM. If you don't dig around the DOM in your clcinet code, then this can suffice. If you dig around, then you need to build nodes and add them to you page's DOM, so you might want to consider sending back JSON or XML.
So let's say that you have a div with id='generatedSQL' when your AJAX call retruns, it will fire a callback method (let's call it updateSQL()) and inside the callback you'll have code that looks approximately like:
$(#generatedSQL).innerHTML = theVariableHoldingTheHtml;
Your other option is to parse the JSONXML/etc. and using createNode(),etc, build new DOM bits and plug them into your page. I don't have the jquery chops to write this for you. I look it up every time I need to do something like it.
If the query text is only ever display-only, and you never try to dig around in it on the client side, just use the innerHTML method, whether you pass HTML or pass JSON and generate HTML from it. If the query text is important to the inner workings of the client, then you'll need to write bunch of DOM manipulation code.
No sure what you would be using but, if uses clicks on something then use the Onload event of the element with ajax call to script which brings back the data/content and on readystate just update the innerHTML of the container DIV.
Hope following link will help you understand the concept will give you a code to start with as well.
http://www.w3schools.com/php/php_ajax_database.asp

Categories