External JS file engine -- manipulating db using node.js? PHP? - javascript

Admittedly, I'm new to some of this...
Building a website on a local server. It has a ton of JS function in an external JS file.
Site has a MYSQL DB. (I am still learning this).
As part of my calculations from functions in that external JS file, I want to update and/or read from that DB.
I have been trying to read up on node.js and trying to read up on PHP (still learning both), but I'm not sure if I'm sniffing in the right direction.
Do I somehow invoke functions from node.js from the external JS file? Do I somehow invoke the PHP (in the form of a function, I suppose) from the external JS file?
How does one typically do this?
I have definitely learned that this in the external JS file does not do the trick. First window appears, but second doesn't:
// Activate the node.js library for MYSQL access
alert("got here 1");
var mysql = require('./mysql');
alert("got here 2"); // nope, this never pops up
Higher-level advice might be more useful than detailed in-the-weeds advice...? Still very new to this.
Thank you kindly!
-=-=-=-=-
self-muttering thoughts... I am using the external JS file to hold a bunch of functions that do all kinds of manipulation and conformation to the data that I collect on the front end:
<button class="ButtonOperation" onclick="DataLog(document.getElementById('DataWindow').value,'NE_AssembleOrder')">Log Data</button>
Am I eventually going to discover that I should instead port all of these functions over to a big PHP file instead?
-=-=-=-=-

Okay, took a while before I better understood this. So, this is the answer that would have gotten me moving in the right direction (for any future reference):
The thing to understand is that for this project, you want to manipulate data to and from a database, which means that (at least for now, for the sake of simplicity), the key is to get your data into a package and send it up to the server, and then have a function running on the server take up the yoke from there.
The way to do that (old school), is with a form.
When you SUBMIT a form, all that data on the form is bundled up and sent to the server.
In this instance you have an index.html page, and that page will open a new page for each of the functions you're trying to track. Use JavaScript to pop open the window and then when you include the URL for the window, pop in a Popup_SpecificFunction.php file. (change SpecificFunction as needed)
So far, so good. ;)
Now, in that Popup_SpecificFunction.php, you will collect all your data under a single form. A good ol' HTML form, with a [SUBMIT] button. That very same Popup_SpecificFunction.php file also has a reference in the header, referring to the big main library of PHP functions -- which is a file sitting on the server.
That [SUBMIT] button invokes a ProcessAllThisData function -- which is on the server-side PHP file. In doing this, it sends all the data from the form -- including a lot of data you include in hidden controls -- to the serverside function.
And at that point, you are basically "on the server" with all your data, and then you can just code that function in PHP and manipulate the database and other stuff as needed.
Using the form was the thought-jump you needed, because prior to this, you've generally thought of forms as standalone data, but they can have actions associated with the entire forms.
You can still use JavaScript to do client-side stuff, but here's another thing that can trip a person up:
There is a difference between these two HTML items as far as whether or not you should use them to send data to and from the server, or whether or not you are just going to JavaScript something on that button:
<button></button>
and
<input type="button"></input>
You might have to experiment a bit to figure out which is which.
This was everything you needed to get you moving in the right direction.
Sincerely,
Future Me. :)

Related

Using a form to save/update settings in a db and build a HTML with those settings from a template

My limited experience in web development as a self-taught led me to hit a wall while trying to figure out how to deal with this problem.
I need a form (map_settings.php) where the user should enter some inputs. Those inputs must be saved in a database table (MAPS) and then used to create the final HTML file (e.g. map1.html) for that specific user/inputs.
I know how to deal with using forms and saving submitted data to a database.
What is completely obscure to me is how can I use those inputs to automatically generate the final HTML.
My idea is to have a template HTML (template.html) and each time a user saves new settings via the form, I copy the template and replace some variables inside it with the actual data the user has input in the form.
If this might matter, the variables I need to replace in the template are also JavaScript variables within a <script> tag.
Can anybody help me suggesting one viable way to do this? I am mostly using JavaScript and PHP, without frameworks. I've also red about JavaScript templating engines, but I sincerely did not get if those are useful to me in my case.
Anyway, here is an illustration of what I would need to do, to hopefully clarify better my point.
Creating a static HTML file per user is not the way to go. Instead just have a PHP script like mapdisplay.php or similar.
Make the script so that if you type mapdisplay.php?map=1 in the browser then it will read the map ID, get the relevant settings from the database for the map in question and then generate some HTML to display them - of course you can have most of the HTML ready made like a template, and just use PHP to fill in the details from the database. This idea of getting data on the fly when requested, and plugging it into some HTML is how most web applications work.
If you create a static HTML for each user it quickly becomes unmanageable with a large number of users, plus it's hard to introduce changes or improvements to the template because instead of just updating one script file, you have to back and re-do every existing page. There are other disadvantages to your approach too, but I won't continue here - you get the idea I hope.
If I were you I'll make that in this way:
Don't use template.html
Don't get data from database to new file, but from form
Make database test before make file
To make template use
$template_text = "text...text...html...text...".$php_varible."text...text...html...text";
For other things about php see w3schools

AJAX url and controller

For form submission I use an AJAX call that posts data to a page like form.ajax.php. At this page I check if '_POST' is set and then process the form by validation, and then save the data using my database class. Depending on the result, the ajax-page return a status message back to the form-page which fires an alert message with the status.
My question is how and where should I put my AJAX files. Should I use one file for all kinds of AJAX requests or multiple and how does AJAX fit into web MVC? I have tried to search for it but there seems to be many different opinions.
I usually find it manageable to make ajax calls from the views files which load ajax(js) functions as needed. This way all the functionality related to the front end display is contained in one place and easier to debug later on. I also create common utility ajax functions so minimize code repetition.It goes something like this:
view.php( callController(ajax function) ) --ajax call--> controller.php( return value)---> view.php(updateView(ajax function))
You could, for clarity, use one file per AJAX action, and put them all in the same directory, like /AJAX/logout.ajax.php, /AJAX/login.ajax.php etc. If you only have a couple of actions you can just use one file to serve them all.
This is just a matter of convention between you and the people you work with (including your future self, say 6 months later, when you will have no idea what you did in that project).
As long as everyone is in the same page, you can't really go wrong.
Also, I hope you sanitize your _POST inputs properly so little Robert won't be able to harm your database.

angularJS & web2py: calling python from ng/javascript/html

I'm using AngularJS (mainly the client side) and web2py (mainly the server side)together in an app.
I have an issue now.
At a point of the program, I use AngularJS to get some data from the client and these data are store in an AngularJS variable. I planed to use $http.post to submit these data to database directly, but it didn't work due to cross-orign problem.
Right now I'm trying to pass these data(they are in JSON format) back to web2py and let web2py insert these data to database.(similar to submitting a SQLFORM).
Is there anyway I could pass these data as an argument to an web2py function and invoke that function within javascript code?
Possible approach in my mind:
1) Since I could write python in html using {{}}, and I could write html in javascript, could I write python code within javascript using something like: document.write({{python code}}) ?
I tried this but whatever html I write it goes to a brand new html page. I also tried document.getElementById('testDiv').write("<p></p>"); But it doesn't work.
2)use ajax, I'm not familiar with ajax, any example will be really appreciated!
Any thoughts?
Thank you all!
ok so you got me lost for a second there, lets see if i got it right
1- angular as your frontend
2- python as your backend
3- you are rendering an html document in python and delivering it to the browser
4- since python template language uses {{}} as delimiter am assuming you changed the angulars delimiters too
either using ajax or reload you'll need to provide a python post handler script. that takes your data and makes the DB update. if this is going to be a pattern and you are going to be making AJAX CRUD operations, you should use angular resources ngResource if not a simple
$http.post(url,data).success(function(response){})
https://docs.angularjs.org/api/ng/service/$http#post
where url would be your form submission handler url.
if you where to use a form you'll need to set the target to an iframe hidden in your page and the response should a script tag that gets the scope pertinent to your controller and let him know the result of the operation. this is an old approach, but handy when it comes to send information to sites that don't allow CORS which by the way might be the solution to your problem, when storing data directly to your db, you might just need to enable CORS headers in your storage engine API and that should allow you to submit information even when coming from a different domain
After hours of struggles and countless google, here's my workaround solution:
Main problem: the data are stored in AngularJS but AngulatJS could not submit data to database through API due to cross-orign issue. But Web2py could submit data to database using sqlform.
My approach:
1.)When the user click the submit button, invoke 'ng-click="submitBtn()"'.
submitBtn() is a function of the ng-controller, which has access to the data.
2.)In submitBtn(), the function first write data into web2py's sqlform through
document.getElementById('inputId').value=$scope.data;
then the function click the sqlform submit button through
document.getElementById('submitBtn').click();
It took me a lot time to figure out those element ids of fields in web2py's auto-generated sqlform. The way to find them is using developers' inspect element tool in a browser and see the source code directly.
Hope this will help someone will face the same issue!

HTML that's both server-side and javascript generated - how to combine?

I'm usually a creative gal, but right now I just can't find any good solution. There's HTML (say form rows or table rows) that's both generated javascript-based and server-sided, it's exactly the same in both cases. It's generated server-sided when you open the page (and it has to stay server-sided for Google) and it's generated by AJAX, to show live updates or to extend the form by new, empty rows.
Problem is: The HTML generation routines are existing twice now, and you know DRY (don't repeat yourself), aye? Each time something's changed I have to edit 2 places and this just doesn't fit my idea of good software.
What's your best strategy to combine the javascript-based and server-sided HTML generation?
PS: Server-sided language is always different (PHP, RoR, C++).
PPS: Please don't give me an answer for Node.JS, I could figure that out on my own ;-)
Here's the Ruby on Rails solution:
Every model has its own partial. For example, if you have models Post and Comment, you would have _post.html.erb and _comment.html.erb
When you call "render #post" or "render #comment", RoR will look at the type of the object and decide which partial to use.
This means that you can redner out an object in the same way in many different views.
I.e. in a normal response or in an AJAX response you'd always just call "render #post"
Edit:
If you would like to render things in JS without connecting to the server (e.g. you get your data from a different server or whatever), you can make a JS template with the method I mentioned, send it to the client and then have the client render new objects using that template.
See this like for a JS templating plugin: http://api.jquery.com/category/plugins/templates/
Make a server handler to generate the HTML. Call that code from the server when you open the page, and when you need to do a live update, do an AJAX request to that handler so you don't have to repeat the code in the client.
What's your best strategy to combine the javascript-based and server-sided HTML generation?
If you want to stay DRY, don't try to combine them. Stick with generating the HTML only on the server (clearly the preferable option for SEO), or only on the client.
Make a page which generates the HTML on the server and returns it, e.g.:
http://example.com/serverstuff/generaterows?x=0&y=foo
If you need it on the server, access that link, or call the subroutine that accessing the link calls. If you need it on the client, access that link with AJAX, which will end up calling the same server code.
Or am I missing something? (I'm not sure what you mean by "generated by AJAX").
I don't see another solution if you have two different languages. Either you have a PHP/RoR/whatever to JavaScript compiler (so you have source written in one language and automatically generated in the others), or you have one generate output that the other reads in.
Load the page without any rows/data.
And then run your Ajax routines to fetch the data first time on page load
and then subsequently fetch updates/new records as and when required/as decided by your code.

How to save the input values of an HTML page?

Now, this requirement may seem weird. But i would like to know how to achieve this?
I am having an HTML file, which is having few input box, check box, radio button etc. I would like to retain the changes a user [ actually i ] performs on this page. Like if the user has ticked a checkbox then next time anybody open that file should see that checkbox as ticked.
This thing can be done easily using HTTP cookies. But i don't want to use cookies.
The answer can be as simple as "No you can not do that" :)
Edit
That's the problem with not phrasing the question correctly.
I guess i can't use DB as if i will send my HTML page to someone then he/she will not be able to see my changes. I want my changes to be reflected on other systems also. [ thats the reason i was not going for cookies ]. Other solution what i was thinking was, using FileSystemObject. Any other solution ? again the answer can be "No you can not do that" :D
You could bind the change events of your form elements to an AJAX submit, log the submits to the db and then on any page load grab the latest states from the db for rendering.
Edit
If you want these changes to appear "simultaneously" for other users then you could use jQuery polling to update the page - have the page periodically poll the server for the latest state.
Having said that, if you give them a server link and not the actual file they will see your db changes.
However, it sounds like you want to actually send the file (not send someone to a web server) in which case you could do something like one of these approaches:
Your PHP/whatever file (can possibly even do this with javascript) outputs a HTML file with appropriate checked="checked", selected="selected", value="blah" etc. You send this file.
Your PHP/whatever file outputs a static reference file. Your HTML file has javascript referencing and using the values stored in this file. You send both of these files around (although value updates only require a changed static reference file).
I sounds like you want to change the actual file using Javascript - this should be rather difficult. Javascript was designed from scratch as a web scripting language and as such it doesn't have any built in file/IO functionality.
What you can do in Javascript is load ActiveX objects and plug ins. How this works depends a lot on which browser you're using. For instance in IE you could load an ActiveX object (written in VB or whatever) that could edit your file:
var fileWriter = new ActiveXObject("My.FileWriter");
fileWriter.Update("myFile.htm", "inputName", "newValue");
You'd have to write your FileWriter utility though.
Alternatively you could use HTML5's new data storage stuff - but then you're still limited on browser.
You need some method to identify the user when he or she visits again. A browser cookie is useful, because it is stored on the user's computer, which serves as identification. The other serious option is to store the user's preferences in a database. This would, at least, require a server-side language. In addition, you need some way to identify the user, such as username, or, less reliably, IP address.
I hear other options may exist in HTML5, but I don't think those can be used seriously at this time. You can read about it here in Offline Web Applications. It seems to me like something very similar in spirit, although much more powerful, than cookies.

Categories