How many ajax files should I have? [closed] - javascript

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 8 years ago.
Improve this question
I'm starting out php.
I'm wondering how many ajax files should I have. Should I have a seperate one for each operation I want to do? each query insert etc,
Or do I like send something in the data, or maybe request that ID's the request so that the server knows what to do?
Is there a good example for that?
I don't know if it matters but I'm using jQuery.

To answer your question, I personally like having as many files as possible (with fewer lines of code), but keeping related functions groupped in an object inside the same file.
For example, you could have one file called userAjax.js which contains the userAjax object:
var userAjax = {
getUserLevel : function (userId) {
$.get // blah, blah, or any ajax request
},
setUsername : function (userId, username) {
$.get // blah, blah, or any ajax request
}
};
In your app you could then use (after including the userAjax.js):
userAjax.setUsername(37, "John");
I like using this method because it keeps code structured, you do not have too much code for too little functionality. I use it in small to medium sized projects and works great :) (both for production & maintanance).
For the server-side, you could either do the same thing, or simply have a file for each command. I also like file-per-command method because if you structure your files in folders it's very easy to maintain the code (you can go directly to the function you want by navigating through the file tree). But again, for larger projects I think you should use a more OOP-approach, like having a class with many functions in a single file.
To sum it up, it all depends, mostly based on the size of the project.

Well, you can create functions for all operations what you want to do, and handle this functions with one file. Or you can create as many as want files for handling requests. If you are using some framework built on MVC architecture, you will probably use only one file (Controller) or more functions in more controllers, it is really variable, depending on usage.
There is lot of tutorials how to use PHP with AJAX. You just need only search for them.

Related

Is it a bad practice to add large parts of HTML that's not required to be visible when the site loads using javascript? [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 1 year ago.
Improve this question
I need to have 2 popup modals in each HTML file to allow users to login and sign up, and was wondering if it was possible to simple have a common js file to add it using innerHTML or a similar method instead of typing it out in every HTML file. Would this cause any performance issues?
Neither should cause major issues with performance, especially since you're not trying to show these models until the user has interacted with the page.
You're mentioning that you would have to copy-paste this HTML chunk into every file. This would violate the DRY principle, and cause you to be left maintaining copy-pasted HTML in many different files, which is never a good thing. In this scenario, I would go for dynamically generated HTML.
If you want to dynamically generate the HTML yourself (without a templating library, etc), then I would avoid .innerHTML as much as possible - it's convenient, but it's also easy to fall into security pitfalls with it. Prefer using the Javascript built-in DOM APIs.
I personally like to use this helper function to make the DOM APIs easier to use.
function el(tagName, attrs = {}, children = []) {
const newElement = document.createElement(tagName);
for (const [key, value] of Object.entries(attrs)) {
newElement.setAttribute(key, value);
}
newElement.append(...children);
return newElement;
}
// USAGE
const customElement = el('div', { id: 'myId', class: 'myClass' }, [
el('p', {}, ['Some Text']),
el('br')
])
// The above element will get added to the body, and has the following shape:
// <div id="myId" class="myClass">
// <p>Some Text</p>
// <br>
// </div>
document.body.appendChild(customElement)
You certainly don't have to use it, do whatever floats your boat, but I just find that a helper function like that makes it easy to write HTML-looking Javascript code, without the temptation to actually use .innerHTML.
Just use it. It won't affect the performance.
it shouldn't effect performance. If anything, if the scripts loading is deferred it might improve the performance.
As for bad practice, I don't think it would be. I mean how is it any different to something like React that has a html file with a div with an id and injects the bundled react app (webpack js files) into

Best way to integrate frontend and backend without ajax or api [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 4 years ago.
Improve this question
I wanna use php variable in frontend framework like Vue js.
What is the best way of integration frontend and backend framework?
This is my idea, but i think there are better way to do this.
<script id = "data" >
let $user = <?= json_encode($user) ?>
</script >
Some content...
<script >
new Vue({
data: {
user: $user
},
mounted() {
$("#data"). remove ()
}
})
While 'simplicity' is wonderful, 'functionality' is also pretty critical...
Sometimes you can get by with your type of coding (use it for some things that come into the PHP file that are needed to load the page, for example), and what you have may work for this particular situation (and, no, there isn't any way I can see to make it "better"...), though most pages will need more data that is 'fluid', and you will quickly run out of projects where you can write only 'simple' code.
Learn to use ajax (it is pretty simple once you get the hang of it) and copy/paste from your own 'library' (save snippets in a place you remember - you will find MANY things you want to keep... - I keep a 'functions.php' file and over the years it has grown pretty large with great bits-n-pieces.)
Since you are using jQuery already, here's one way to do ajax... (there are others, again, study and find the way you like...)
var url = "https://theURLtoMyAjax.phpPage";
var elements = "theStuff=thatIwantToSend&someMore=somethingElse"; // this is like writing everything in the address bar - again, there are other ways...)
$.post(url, elements, function (data) {
// do all kinds of wonderful things in here!
// the 'data' is what is returned from your call, so you can use it to update data on the page, etc.
});
So, as you can see, only a couple lines of code to add Ajax and tons of things you can do once you do it, so learn it - and use it!
Happy coding!

Python backend with JS frontend [closed]

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 6 years ago.
Improve this question
I'm creating a Python-powered web framework aiming to make use of javascript as minimal as it possible. Need to make something lightweight like uilang to pass events to my Python code. I suppose that should be jQuery solution somehow pinging kind of observer object(?).
I have discovered some efforts to create pure-Python interface like Remi but still have no clue how should I reimplement it in my code.
Let's say I make a class like that:
class WebView():
def __init__(self, template, **callbacks):
"""
Callbacks are dict, {'object': callback}
"""
self.template = template
self.customJS = None
for obj, call in callbacks:
self.setCallback(obj, call)
def __call__():
"""
Here I return template
Assume {{customJS}} record in template, to be simple
"""
return bottle.template(self.template, customJS = self.customJS)
def setCallback(self, obj, call):
"""
Build custom js to insert
"""
self.customJS += ('<script ....%s ... %s' % (obj, call))
So, how could I make JS to pass an event from, say, pressing button back to my callback?
I understand that question might be on the edge of being too broad, but I'm solely trying to be as descriptive as possible because I really don't know JS at all.
Thing is you don't need javascript for a python web framework. You would be fine serving pages with flask or django without the single line of JS.
These pages would be pretty static with a few forms but would work perfectly.
Now if you want to have more dynamic content and interaction you'll probably need JS, and use XMLHttpRequests to asynchronously call your python backend on events. But in order to do so properly, you should start by learning JS.
You could probably do it with websockets too, however i don't think it's the best way. You can use websocket-python library on the python side, and on the website, you just send a websocket message on every button click callback.

Need to Understand Process behind Web Processes with HTML, PHP, Javascript, through existing HTML Button to PHP function Issue [closed]

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 7 years ago.
Improve this question
Note: I'm asking less for a solution and more for help. I understand this question is probably basic and repetitive, but I'm less sorry than I am frustrated with how little other websites explain.
I am absolutely positive this question has been asked in a million variations because I've looked it up so many times, but the problem is how many times I've had to look it up and I still don't understand half of what I'm doing every time I attempt it. Pretty sure I've scraped the barrel with this one.
I have a process I'm running that calls several queries to a SQL database, and I'm doing them in PHP. Problem is, they're all run automatically when the page is opened, and that makes me so queasy it isn't funny. I'm trying to make a button that does not redirect to another page to call this process, be it by function or what-have-you. I'm trying to keep all of this on one page... Though I'm not averse to make it more pages.
I'm trying to avoid JQuery. My tools available are: JavaScript, PHP, and HTML. If I need to, I'm willing to convert all 8 or 9 queries into JavaScript to run it through button or even AJAX, but I'd like to keep it in PHP if I can. I know PHP and HTML run differently, but this is where I get confused on how best to combine them, and how to use JavaScript, and when to use JavaScript, and what GET and POST and SUBMIT are in relation to PHP, and just a million things. I'd like to know the BEST method AND the "you can do this with what you have already done", and WHY one is better than the other, if at all possible.
I'm sure 90% of this question is super repeated, but thank you in advance for your patience. I hate not understanding.
EDIT: I was asked for my code, and I can give a basic idea of it, without being able to give the code itself:
<?php
mysql_pconnect ('host', 'username', 'password');
mysql_select_db('database');
// the company I work for has so far refused to let me upgrade our website, so I
// am trying to keep it the same so that half of it isn't new and the other
// super outdated. Believe me, I'm pushing.
$query0 = "TRUNCATE table templateTable;";
$query1 = "INSERT INTO templateTable
(item1, item2, item3, item4...)
SELECT
table1.itemA, table2.itemB, table1.itemC, table2.itemD...
FROM table1, table2
WHERE table1.itemA = table2.itemQ;";
// there are a LOT of items in this query, like 100
$query2 = "UPDATE templateTable, table1
SET templateTable.itemX = \"thing\",
CASE
WHEN table1.itemAB = 1
THEN itemX = 'THING1';";
$query3 = "UPDATE templateTable, table2, table1
SET templateTable.itemY =
CASE
WHEN table2.modelNumber = table1.modelNumber
THEN itemY = table2.modelNumber
ELSE
itemY = table1.otherInformation;";
// these queries are using data from two tables to fill an inventory
// template table that will only be filled and edited through queries. there
// is no manual editing of this table- just queries.
/*
I'm hoping you get the gist of this because there's 5 other queries even
longer and more complicated #.# I have a procedure in MySQL to do this but my
coworkers are nervous about running the procedure, so I'm trying to make it more
friendly by allowing it through the website. This was requested of me
*/
?>
Long story short: I'm trying to run a PHP function on the same page with HTML through a button, the php has 8 queries being run to a MySQL database, and I don't really understand any of this.
I'm trying to run a PHP function [...] through a button [...] that
does not redirect [or reload]
First you need to understand when is PHP executed, when is HTML rendered and when is Javascript executed.
Look for "difference between cliend-side and server-side" on the Internet, you'll find good explanations. It seems to be a big deal when you're a beginner but once you understand that, knowing when you have to use PHP, if and when you have to use Javascript, and which is the most accurate, is quite easy to get.
In a few words :
PHP is a server-side language. When you load a webpage, your browser (client) sends a request to the server. The server executes the PHP code, generates some HTML (in our case), and sends this HTML back to the browser.
HTML is rendered client-side. This is your browser that reads and renders HTML.
Javascript is a client-side language. Javascript code goes with the HTML sent from the server to the browser. The browser is able to execute Javascript.
In order to execute PHP code when you click on a button, there is 2 solutions :
Either this button is a link, or is part of a form. When you click on it, the page is reloaded (you can send it GET or POST parameters if needed), then your PHP code can be executed.
Either you use Javascript and AJAX, and you don't need to reload your current page. Your browser, with Javascript, will send another request to the server "in the back"*, and the server will be able to run some PHP code without you having to reload anything.
*(looking for an English expression that I don't know)
A quick word about jQuery : jQuery still IS Javascript. jQuery is a Javascript library, basically allowing you to have some cleaner, clearer and easier to write code (IMO). But, as halfer mentions in a comment, you don't need it everytime. Other libraries exist, and sometimes, for what you need, "pure" Javascript is enough.
If you place your button into a form with a hidden field like so:
<form>
<button type="submit">Run Queries</button>
<input type="hidden" name="submitted" value="1">
</form>
And use and IF statement around your queries:
if ($_GET['submitted'] === '1') {
// Run queries
}
You get the results it seems you want.
Very simplified: On an initial page load, the queries will be bypassed by the IF statement, which checks the submitted get parameter. When you press the button (submit the form) the submitted parameter will become 1

Javascript best practice use [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 7 years ago.
Improve this question
I'm looking for the best practice use of external private Javascript file.
I have a project with many different HTML files.
My question is what is the best practice, is it to have 1 .js file for all HTML pages or should I have a seprate .js file for each HTML?
I still nor clear if it is feasible at all the have 1 .js file for many different HTML pages, how can I use DOM capabilities?
This is a rather broad question and it really depends on how you structure your project.
This day and age, my general advice would be: structure it in whatever way it makes it easier to work with, but when building/deploying/whatever merge all the files together and minimize the result.
This results in easy development for you and maximum performance for the end user. Also, don't forget about proper caching headers and a timestamp in the URL for that JS file.
This advice actually applies to CSS files as well.
I agree with #Vilx-'s answer, but I suspect the question is a little more basic than that.
On each HTML page, you can simply link to a script containing site-wide functions and variables, and perhaps also a script unique to that page. For example, if you had special functionality on an About Me page, you could link to it like:
<!-- Global functions and variables -->
<script type="text/javascript" src="/scripts/global.js"></script>
<!-- Functions and variables that only apply to this page -->
<script type="text/javascript" src="/scripts/about-me.js"></script>
That way, you still have your utility functions in global.js, but you control the specific page using about-me.js.
Another way you could do this is by storing all of your JavaScript in a single file, but executing relevant functions inline on the corresponding page.
Main.js
function homepage(){
// do things specific to the homepage
}
function aboutMe(){
// do things specific to about me
}
function contactUs(){
// do things specific to the contact page
}
About-Me.html
<!-- Global functions and variables -->
<script type="text/javascript" src="/scripts/main.js"></script>
<script>
// Execute the relevant function defined in main.js
aboutMe();
</script>
The best way is really what fits your application. If it's a large, complex application then you'll want to have separate files, but you'll probably want to concatenate them before publishing the project. If it's a small personal project, then there's no harm in simply structuring your project the way you see fit.

Categories

Resources