Dynamically / iteratively build up page content - javascript

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

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

AJAX - Sending html-fragments ok?

I want to create a website where the user enters data in a formular and a php-script uses this data to create html-code which shall be inserted in a div-element. Using AJAX seems to be the right way to do this, but there is one thing that bothers me. in my opinion a script should always generate a whole document (doctypt-declaration, head, body etc.), but if i use AJAX i have to send only a fragment of a whole document, because i would have to write something like this:
document.getElementById("mydiv").innerHTML = ajaxObject.responseText;
So i would like my PHP-script to send a whole document, but i cannot assign a whole document to the inner html of an element. is there a way that javascript can process a whole document, and insert the documents body in a div or should i maybe use iframes instead?
in my opinion a script should always generate a whole document
A big no to that! Have a look on other data formats such as json which is widely spread, or xml. Some formats do not even follow certain document structures that say: here my document starts, title belongs here, that must be like that, the other thing has to be like this and here the document ends. There's just bare data (of course under the accordance of the syntax).
The server doesn't need to return HTML at all (if you don't want it to). The opposite is the case. Provide as many output formats as you can.
Think of other client applications that would use your script, such as non-js applications or applications outside the browser that can't even handle HTML.
Would you always write a new script or change your existing whenever you need another output data format, or would you rather have a strong serverside application structure that can handle the output of several data formats?
Think of your server as an interface. It returns the data that you request. How you handle the data is absolutely up to the client (the server should not even care) in this case.
Also returning HTML chunks is absolutely okay in your case. That's what I would do here too.
What I want to point out is that you absolutely don't need your script to return a whole HTML document (isn't exactely that even a big advantage that came up with AJAX?)
If you don't mind using a bit of jQuery,
$('html').html(ajaxObject.responseText);
If you just want change whatever's in the body,
$('body').html(ajaxObject.responseText);
As suggested in the comment below, it without using jQuery,
document.body.innerHTML = ajaxObject.responseText;

Where to render Ajax search results in an object oriented approach using Coldfusion?

I'm updating a Coldfusion8/MySql site with a fairly complex search from "spaghetti to object" (= separate view, controller and process - no framework, everything handled by Jquery Mobile).
I need to run the search query through Jquery-AJAX and am now posting the search form to my searchProcess.cfc, which does the database queries.
Question:
I'm not sure where to render the results?
The results will be fairly complex (database with a few million records, rows of 40 fields) and should end up in a single result layout or a multiple result layout file.
I was thinking of constructing the files inside the cfc and handing them back via cfsavecontent, but I'm reading everywhere this is a no-no...
What are the alternatives then?
I could set up a template_single.cfm and template_multi.cfm, pass back pure search results as AJAX response and then fire another AJAX call from the success handler to call the template and then render the output of this 2nd call. This seems awfully complicated, plus I don't see where I can fit my pagination in there without passing around large datasets.
So I'm looking for some advice on how to handle search-results in an object-oriented-way?
Thanks for input!
EDIT:
After a few more hours of googling, I'm currently looking at the following option:
1.) run a single database query to return paginated results - as per here
2.) send data with 0-25 records back to AJAX in JSON
3.) trying to use a template cf/js in a loop (length 1 or length 25) - as per here
This would mean data-transfer only for 1-25 raw records in JSON. If I try to render in the success handler, I'm not having to http-request another template.
Does this approach make sense?
First off, I see nothing wrong with putting display logic in a .cfc that is specifically for display logic. I know it's not strict MVC, but depending on what you're doing, it can work just fine. What I don't like is .cfc's that do any sort of output within the function. I always hand back any data from the function.
/end opinion
For this particular problem, I second EDIT idea of setting up the view to be almost all HTML/jQuery with AJAX calls for paginated recordsets. As far as the single/multiple results, I'd go with separate jQuery functions depending on which one you needed. The nice thing about this is that you could have the multiple recordset display call the single record display to view a single record (while still retaining the full recordset in the Dom).
In both cases, I highly recommend getting a Javascript Dump function (helps so much in visualizing the DOM data.)
PS. If anybody finds any newer/better JS Dump functions that work like cfdump, please, please, please let me know!

Passing data between elements in UI

I'm new to web applications and am trying to understand the best way to work with data in HTML. I'm using Appengine (Python) and have managed to load a bunch of data to the view. In the simplest form, it's a set of movie names and each name has associated details with it (e.g. year, rating etc). Now how do I pass data between the movie link and then a div where all the details will be displayed? I'll be using jQuery for some controls in my application so I'm wondering if there's a way to do data binding to controls with that?
Additionally, can anyone tell me what're the standards around this i.e. if I load all this data to the UI in one call (assuming it's not a lot of movie titles), wouldn't it make it easy for people to screen scrape this information? Or is there some obfuscation that's typically used here?
Sorry if I'm not very clear but I really am an absolute beginner with web development!
Update1:
I found the jQuery data() api. It seems like this'll work. Comments?
Update2:
Some testing later and it turns out that data() actually attaches the data to the elements rather than showing it in a div itself.
There's a few ways to do it but the basic idea is to put the data in the HTML in a way that is not visibly rendered, then use Javascript to parse the HTML and pull the data out when you need it.
The easiest way on modern browsers is to use data- attributes. These are any attribute that start with data-, and you can name the rest yourself. For example:
Czar Wars
In this case, the user will only see a link called "Tsar Wars" but your javascript can easily access the data- attributes to get the data it needs. The other benefit of this approach is that jQuery will automatically make data- attributes accessible by the data() api.
Another way to do it is to have a hidden HTML list element with all your data elements in the list, but you'll have to parse this all yourself.
There's no standard obfuscation. You'll need to obfuscate yourself on the server side, and unobfuscate in your JS. It's not too difficult to figure out any obfuscation algorighm in js, so this is not worth your while.
If the data really is private, then you would have to architect it as to do all the processing on the server. For example, only show tokens (like 1234), and use AJAX calls to pass the token to the server so the server can do the data processing and spit back publicly safe results to the script.

Best practices for returning and displaying data from AJAX calls

I have some jquery/php interaction set up on a page. It submits some data to the server and gets back records of data which are then to be aligned on the page for comparison and possible action beyond that.
My question is what is the best practice for returning the info and then displaying it?
Return JSON object and then create
html on the fly with js and display
the data?
Return JSON object and then
put that data in already created
containers for the data on the page?
Return pure html from the server and
just put that on the page?
I was rolling these through my head last night and couldn't really figure out if one way would be better for any particular reason.
I'm not a js guru so wasn't really sure the pros/cons and caveats to these different methods.
I think it ends up depending on your app.
Pure HTML is the easiest, you just drop in in place and viola. JQuery makes it a breeze to add the proper events and what not.
However, whenever I've used AJAX it's always evolved into returning JSON and building elements on the fly. If you are populating a tree for example, it may become messy to get the proper nesting. This forces you to have to do client side code anyway at which point simply using JSON from the start is cleaner.
Also, If you plan to use the data calls from other pages then using JSON is the way to go because the HTML will bee fixed.
This completely depends on the way you have things set up in your application. I, for one, prefer to return JSON (second approach in your list), because I have an 'error code' parameter that I check in onSuccess function before updating the content on the page, and if it's not zero then I notify the user of the error, including the error message that came back from the server (server-side validation, database timeout, etc.).
I think you're missing a perfectly valid option, one which I use often. This is my typical schema and it has yet to fail me... :-)
Here's the basic jQuery template I use:
$(function() {
$.getJSON('/some/page',{foo:bar,bar:foo},function(json) {
if(json.outcome == 'success') {
$('body').prepend(json.html);
} else {
// Somehow let the user know why it didn't work
alert(json.error);
}
});
});
Here's the basic backend (PHP in my case) structure I use:
<?php // Page: '/some/page'
/* Blah Blah Blah... do whatever needs to be done... */
// If everything turns out okay (assuming '$output' is the HTML
// you want to display...
echo json_encode(array('outcome'=>'success','html'=>$output));
// If something goes wrong... just do:
echo json_encode(array('outcome'=>'error','error'=>'Uh oh... something is broken'));
Naturally, you'll want to be more specific with your error by putting them into some variable or something. But, you should get the idea. Also, of course you can add more information to the json output. You can have some pre-made HTML and also some other information like a 'success notice' or a new class name for some element, I dunno... whatever... the possibilities are endless.
Anyways, the reason I choose this route is because it's usually faster (based on my experience) to append pre-made HTML to the DOM rather than looping over JSON and inserting the stuff unless it's just, like, a bit of text to replace into an element. But, the method I've shown is, IMO, the best of both worlds. You can attach HTML as a string to one of the JSON properties.
Happy jQuerying :-)
The "possible action beyond that" part of your question makes a big difference. If you need to do other things with the data besides display it, returning as JSON is a clearly better option because you can work with the data as a native JavaScript object instead of having to traverse the HTML DOM. If all you ever intend to do is display it, I don't see any reason to go through the trouble of building that display in JavaScript; just build the HTML in your presentation layer on the server.
This came up recently and possible a dupe: The AJAX response: Data (JSON, XML) or HTML snippet?.
If you are going to be creating HTML then you may as well be returning HTML directly and inject it into the DOM. However, there are times you need to work with objects which is where JSON comes in handy.
If you return a Person object for example then you can greet Person.Name and show Person.Preferences which is really handy. It depends on your design but the general considerations should be to keep HTML out of Javascript unless you're building RIA.
I have used all three and have come to the conclusion that returning HTML is better when introducing new elements to a page.
My experiance is that when building HTML with javascript I am usually replicating work that will have already have been done for the non javascript user journey.
I still prefer parsing json for updating existing elements or creating javascript only functionality. I tell myself this for bandwidth, but I think it just because I love javascript.
As a forth option, I read a great post about how Flickr deal with vast quantities of data with string concatination. Basically just parse a big o' string down the pipe and chop it up on the client. This significantly reduces the on the server, with only a marginal increase on the client.
Returning pure HTML is the best solution. For the most part gzip should neutralize any difference in bandwidth, and rendering via javascript on the client can be slow if the client is a crappy machine. Finally, writing javascript to render HTML is hard to work with compared to using something nice like a view if you use MVC.

Categories