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!
Related
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. :)
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.
I am developing my first website. At this time i am generating a new html design that would be a ticket.
From my main page, i will load this html when the user clicks the "See ticket" button. This html has a table which is filled on document.ready with javascript. The data used is a JSON created in the main page.
I coded a working solution using localStorage. The problem is that the next step is to convert that HTML website to PDF and the software i am using does not work properly with localStorage, so i need to pass the JSON from main page to the ticket page. I can't neither use URL encoding cause string could be sometimes longer than 2000 characters and it is not productive.
So i thought that maybe i could do and $.get call from the ticket.html to index.html and get the needed JSON. Is this approach correct, or is there any better solution?
Regards
As suggested earlier comments, you need to use serverside code to accept post params and you need to do a ajax post to send the data. This is very good approach. I have one more idea for implementing this.
Let say you open ticket.html in a window.open. And have a JS function ( say GetValue) in index.html, that returns JSON . So you need to get JSON in ticket.html.
You need to define a JS function in ticket.html , using windown.opener.GetValue() , you can get JSON value.
Hope, i am in same direction, which you need. If not, please clarify.
Other way, would be use iFrame and use message communication to pass large data between them, you are interested in this, please read this - https://developer.mozilla.org/en-US/docs/Web/API/Window.postMessage
I have an ASP.NET MVC3 app that features a form with a nested-table input
(Ie on each row I can add a sub-table, with no limit on depth)
To handle this for my MVC app, I've created 2 javascript classes(using this term loosely with js:) that mirror my MVC3 model and post the data to an action method. Everything works great...Except that right now the only way that I know how to do this is with jquery $.ajax or $.post --- How can I do a postback in javascript?
I have the URL, and the custom JSON data, and want to do a page postback... Any suggestions? I can't use the normal form submit due to the nested table scenario described above.
Also, I just want to say, that MVC has made this so simple to render! :) For rendering a recursive view did everything without any script required, only on the saving did I need to screw around with json.
Update:I guess another solution would be -- can I change the contents of my form data on submit? My method takes a JSON object, is there any way I can stuff that in my request while my form submit is happening normally?
You can use the XML Http Request to do this. This is eventually what jQuery and other JS libraries use.
But why don't you just stick to jQuery AJAX or POST?
Maybe I'm misunderstanding your question, but it seems like what you want to do is post to the same page you are on, which means if you have the URL (and it sounds like you do), you just need to specific that in the $.ajax method? Maybe you can clarify what you mean a little bit for us.
Edit: Per comment suggested looking at http://jquery.malsup.com/form/
Well, I found that with the MVC3 binding, the table in my form could be normally bound if I named the fields such as Item[0].Children[1].Children[0].FieldA... etc, everything matched up fine without having to convert to javascript objects/json. I changed my code to fix this naming before a form submit, and it binds pretty well without having to do any json calls at all. Less elegant, but I guess it works.
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.