Is it a good practice to use php code inside 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 9 years ago.
Improve this question
I heard lot of experts saying entering php code inside javascript is not a good practice. I wanted to know if it's true. If yes, then will it effect the performance? or is there any other reasons?
For example:
<?php
$num=1;
?>
<script>
var x = "<?php echo $num;?>";
</script>

No, it is not good practice.
will it effect the performance?
I do not specifically know which performance you meant when you wrote that line, but about all performances I can imagine, I would say: Most certainly, no.
is there any other reasons?
Mixing two languages is hard as it requires proper encoding. This makes things complex. Complexity is bad practice.

Typically, it is bad practice to use language X to generate code in language Y.
Try decoupling the two languages by making data their only interface -- don't mingle the code.
In your example, you could improve the code by using PHP to populate a cfg structure that's available to JavaScript:
https://softwareengineering.stackexchange.com/questions/126671/is-it-considered-bad-practice-to-have-php-in-your-javascript

NO it will not effect the performance, but it affects manageability and security.
In your case, can your javascript function without knowing the value of num? or Are you just developing the JS script from PHP? Latter is the use you should avoid.
Lets take an example where num was used to know the number of items in shopping cart. Now thats a very vital piece of information, but since its JS, it can easily be manipulated. In such case, you should store such sensitive information on the server and not on the client.

A few points:
You lose the ability to minify your JS scripts because it depends on PHP output
Code quickly gets difficult to maintain. You will need to scan through PHP tags in your javascript code.
Normally, I declare a global config object and pull it through a separate ajax request when the page loads (This can be a PHP script echoing JSON).
MyApp : {
x: '123',
y: 'xxx'
}
and then access it from my javascript files later:
(function(){
alert(MyApp.x)
})();

I dont think this a bad practice, if the values are dynamic, you can just do as,
test.php
<script type="text/javascript">
var foo = '<?php echo $foo;?>';
</script>
<script type="text/javascript" src="test.js"></script>
test.js
$(function(){
alert(foo);
});
If it is not dynamic values, recommends no need to use php tags

I don't think it is that bad. Assign your dynamic PHP values to a JavaScript variable in your PHP templates(as first line if possible) and then call these variables inside your external JavaScript files. And I fully agree with #hakre answer.

Related

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!

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.

Is building big portions of page in javascript bad? [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
On an existing project I am working on, I noticed many of the developers are building big portions of pages with javascript. For example:
$( targetdiv ).append("<div>");
$( targetdiv ).append(" <div class='info'>");
$( targetdiv ).append(" <div id='modes'>");
$( targetdiv ).append(" <table cellspacing='0'>");
$( targetdiv ).append(" <tbody>");
// much more...
I understand using javascript to build certain elements on page. Sometimes the content is dynamic and it is now know when the page first loads (ajax stuff).
However, most of the code (not all is shown) is not dynamic and will be build the same way every time. No 'if' statements or loops
Is there any reason why one would build large parts of pages using javascript vs just having the html be part of the html doc? I would think one would want to minimize javascript html generation because its more confusing and harder to write. Also, javascript html generation has to hurt the performance (Does it?)
I am a "newer" javascript dev so maybe I am missing something. I want to say something but I am "newer" so maybe i don't get "it"
Thanks
That is quite possible the most horrible way I have ever seen a kitten getting killed. Now, that's not just a kitten you killed: each line like this kills a thousands of kittens. And puppies.
Don't do this. It's wrong. It's bad. It's horrible. It's terrible. It's hell. It's anything but good.
On a more serious note...
The code doesn't even work as intended. See the comments on your question.
The HTML is the content, the JavaScript is the behavior. You're mixing both for absolutely no compelling reason.
Every time you call the DOM, you have time to go grab a coffee. You're calling append so many times that just seeing it hurts my eyes.
From a philosophical standpoint, I would have to say this is a bad practice. html belongs in the html and that's it.
That said there are several different ways of adding html to the page via javascript.
<div id="template">
<div class="mycontent">
<!-- stuff -->
</div>
</div>
Then
$('#target').append($('#template').html());
will give you the same results without having html code in your javascript.
But if you must (and sometimes you do) the most performant way is to create dom elements in native js and operate on them:
var template = document.createElement('div');
template.className = "mycontent";
// do more stuff to template
document.getElementById('target').appendChild(template);
The native js method while offering the best performance is hard on you as a developer. So if you wish to work with it as an html string, doing the append once would be best:
var template = "<div class='mycontent'>";
template += // add more string to build the template
template += "</div>";
$('#target').append(template);
While ajax has a performance hit, as some suggested it is also an excellent way of managing your html code, allowing you to put the template in its own file. jQuery also has a shortcut to accomplish this:
$('#target').load('/template.html');
or if you wish to operate on the template:
$.get('/template.html', function(template){
//do stuff to html
$('#target').append(template);
}, 'html');
multiple append statements are with out a doubt the worst possible way to go, of all the less than great ways to go. Personally the first option I provided is my preference, and can easily be paired with libs like http://handlebarsjs.com/
Good luck!
Well, since you're new, it's a good thing you went to confirm your suspicions before taking action. That said, I'm pretty sure this is a case of lazy coding. In fact, there are actually even shorter ways of writing the code you posted, and those shorter ways won't delay the browser immensely.
For one thing, my favored way of writing large portions of the page is with a templating system - you put flat HTML files in your web directories, or in some sort of undisplayed portion of your page, and then import them when you need them to Javascript. A number of libraries can help with this.
But for goodness' sakes, even if you're too lazy to do it that way, do NOT do this with multiple append functions. That means the browser is figuring out new HTML elements and unclosed tags on each call of the function, often rewriting its own work. At the very least, append the HTML strings together bit by bit before calling jQuery.append ONCE.
var newHtml = "<div" +
" <div class='info'>" + ...
$(targetDiv).append(newHtml);

Javascript js file encoding [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How can I obfuscate JavaScript?
Hi I need to Encode my js file to upload my host when save my page i dont want user see my js and my javascript code any body idea
you can't encrypt or encode your JS as the browser needs to run it.
The only thing you can do is to minify it, so it gets hard do read. But someone with the right tools and time will be able to reconstruct the code.
Hi there is no way to encript a js page, but there are a few tricks you can do to obscure te code.
First, you obscure the code, by changing the variable to value that do not make much sense. If you do that, keep a original copy.
ie.:
var firstname = 'Paul'; // change it to var fn = 'Paul'; or var 00110011 = 'Paul';
function returnFirstname(){} // change it for rtnFN011010(){}
In order to do that, you would need to program a script that does it for you.
Second, minify your code : http://fmarcia.info/jsmin/test.html
Good luck
The is no definitive way to do this, the best you can do is minify your js file. Search Google for "JavaScript Minify", there are plenty of tools out there...

Categories

Resources