I'm re-developing a very simplistic javascript include I made a while back to be used in several similar html sites. We use a lot of footers on our pages but they tend to be the same copy used over and over but with different dates and other small variations. So, on each page I create an array of variables. These match up with variables found in an external .js file containing a for loop to match up the requested variables that contain paragraphs of footer copy. This eventually is put together to make a div full of footer copy.
My question is this, is it better to send in the specific dates and other variable changes within the copy along with the variable array as one object or should i continue to just send in the variable array alone, create the footer in the html and then insert the dates/changing data in a separate .js file (this is how I've been doing it till now). One way keeps all the data together and seems pretty clean, but the other separates out the different steps (ie step one is creating the footer, the second step puts in the varying info like a date or bonus amount, etc).
sorry if this is confusing, hope i got the basic idea across. Just trying to explore my options since I have the unique opportunity of previous usage of this script and getting a clean slate to make a fresh version.
I think the best way to do this is on the server-side code.IF you are using php use could include the file directly like this.What include does is it pull code from other files and shows it on the page where the include is written.
include('name of file');
Since you have different pages with different footers you could edit this footer file to show different results for different pages.This is a standard way to doing things.Popular frameworks like Wordpress do something similar to this to display the footer
Related
I am building a Qualtrics survey in which each respondent is supposed to see a subset k (e.g. 30) of a larger set of n questions (e.g. 60). These questions all have the same format but a different text, which I will have stored in a local .csv (or similar) file.
EDIT 2: Explicitely looking for a solution that does not require inserting all the n texts manually in the Qualtrics interface.
What is the best way to import these contents into the questionnaire?
1) One way from the Qualtrics documentation is to import a survey as a .txt file or Qualtric's .qsf format, as described here: https://www.qualtrics.com/support/survey-platform/survey-module/survey-tools/import-and-export-surveys/#PreparingASimpleFormatTXTFile
The problem with building a .txt file from scratch is limited in functionality, and you cannot go back and forth between changing things in the Qualtrics editor (e.g. add more functionality) and in the .txt.
The problem with .qsf is that it is hard to understand and manipulate, as detailed in this post: https://stackoverflow.com/a/47381526/10483692
2) Qualtrics' "Loop and Merge" function allows you to loop over (and randomly select) a large number of inputs. But as far as I can see, one has to insert those contents manually.
3) I suspect that there might be another way with via embedded variables, which one might be able to set with Javascript that can be included in "Look and Feel" > "General" > "Footer". But I am not sure whether it is worth going down that road given limited knowledge of Javascript.
P.S. I am assuming the best way is to include all n questions in the questionnaire when building it and then randomly select k questions when a respondent enters the survey. Let me know if there's a way of importing k questions while a respondent is doing the survey.
EDIT 1:
As I currently do not have API access, this is unfortunately not an option.
You can probably do it with one question in a loop & merge block. Generally, you would copy and paste your csv data into the loop & merge field setup and pipe the loop & merge fields into your question.
EDIT 1:
In response to updated question, there are two ways to make the n texts dynamic.
Use a web service to populate embedded variables from an external
source (e.g., a database), then pipe the embedded variables into the
loop & merge setup.
Populate the n texts as embedded data fields in a contact list, then
pipe the embedded variables into the loop & merge setup (would
require use of email invites, personal links, or authenticator). n
texts would be defined on a per respondent basis.
Approach (1) is more likely what you would want to do. In either approach it becomes a bit trickier to process the resulting response data since you would have to cross-reference the question answers with the embedded variables.
I am trying to write a program which can automatically fill in and submit a form in a web in particular time slot.
But i have no idea how and where to start. i searched this in google, but only resulting very general answer like using JavaScript, python. Can anyone tell me which languages should i learn first?
Despite the fact that the generic advice on this thread is quite good, it's pretty broad. I have tackled this problem myself, and despite the fact that I posted a fully functional example, it was deleted by a moderator, despite "theoretically answering the questions".
So, for anyone else looking to solve this problem, you will want to do the following:
Use Selenium and openpyxl, these are two modules that are relatively straight forward and will perform this task perfectly.
You will use selenium to open your web page, and retrieve the relevant html elements that you wish to populate. I suggest finding elements by xPath if you aren't well versed in HTML. The Xpath finder google chrome addon will make this very easy to do.
The driver.get() and driver.find_element_by_xpath() will be the functions that you need.
We will use openpyxl to work with our excel sheet. 'load_workbook()' will load a workbook. We will then use the 'sheet = workbook.active' function to access a sheet from within the workbook.
We now have the functionality to open our website and select an excel sheet.
Now we need to assign cell values to variables, so that we can then populate the HTML form. We assign a variable to each COLUMN in the workbook. So if column A contained first_names we could assign that to by a variable by writing 'FNAME = sheet['A']. Now that we have a way of referring to cells within columns we can begin feeding the data into our HTML form.
We populate our form by using the .send_keys() function in Selenium.
first_name.send_keys(FNAME.value)
the .value makes sure that the correct value is displayed, as sometimes selenium will print the cell function rather than value, we do not want this to happen.
Now that we can print values to our HTML forms from our excel sheet we will need to iterate through each row. We do this with a simply while loop:
i = 1
x = 1
while x <= 50:
first_name.send_keys(FNAME[i].value)
i+=1
x+=1
driver.quit
Once the loop occurs 50 times, the driver will quit, closing the browser and stopping the script.
Some other misc stuff you may find useful when trying to automate this:
driver.back()
time.sleep()
If you would like to see an actual working example feel free to PM me, as apparently posting it here doesn't contribute to the discussion.
The answers you found, as general as they are, are correct. I'll try to explain it to you.
As you are trying to automatize some activity, you have to use a script language to basically
Get stuff references (like getting indexes, forms/fields IDs, etc)
Insert/change stuff (like filling a field, following the field references)
Save stuff (prepare a file, with field references and it's content, that can be injected to the specific system or website)
One example of script language is Python.
So you already have your script. Now you need to inject it on the page. The programming language that can do it for you is Javascript, or JS. It allows you to talk with the webpage, GETting data/references or POSTing data.
I suggest you to write a Python script using a library called Selenium Webdriver.
It will be easy to implement what you have in mind.
I am creating a product overview page via PHP and want to add detail information via AJAX. I am using the jQuery .load-function. The thing is I want to add detail information at three different places, each having a different format, while the detail data being about the same.
I wanted to be smart and created one PHP page where the database connection and query for the details are established and the three different kinds of information formats are created and then referenced each information format using the load function's ability to address page fragments, i.e. something like
$("#123").load(bestprice.php?id=123 #part1")
$("#123").load(bestprice.php?id=123 #part2")
$("#123").load(bestprice.php?id=123 #part3")
It works, but of course my hope that some sort of cache would arrange for the page to be loaded only once was disappointed. It loads three times for each id.
So, my questions are:
a) Is there a better way for reaching my goal, i.e. creating an array in the loaded page containing the data that I can use in my original page with doing the formatting there? How would I hand it over?
b) Would it be possible to load the page only once and address the parts with some kind of processing in my original page?
Please, don't answer only yes. Consider me a newbie who needs as much explanation as possible. Code samples are greatly appreciated!
We have an 8,300-line Javascript application, which implements an interactive diagram for a hand of bridge. It's currently written with about 250 top-level variables, 250 functions, about 130 lines of driver code outside of functions, and 30 hard-coded element IDs referenced in various places; it's entirely self-contained, no libraries are used. It gets its parameters from the URL query string. So the way we use it on web pages is to load it in an iframe.
This is implemented as 3 files:
handviewer.html - This is the page we point to in iframes. It contains about 70 lines of HTML with all the required DIVs, and loads the CSS and JS (called handviewer-old.html in the test below)
hvstyles.css - The CSS for the page
handviewer.js - The Javascript code described above
In handviewer.html, the active elements have inline onclick attributes that call functions in handviewer.js.
The problem is that when we embed lots of these on a page, performance suffers. Iframes are a pain to begin with, and lots of them all pointing to the same server run into connection limits. And even though they're all pointing at the same script, the parameters in the query string act as a cache-buster. Loading a page with 12 of these diagrams takes 3-5 seconds with reasonably fast browsers. Looking at the timeline, you can see that the loads are staggered. So I'd like to convert it to a widget that can be applied to a DIV, with the parameters as inline arguments.
A test page with these 12 iframes is at:
http://dev.bridgebase.com/barmar_test/many-hv-old.html
I'm preparing to do this by hand -- I'll wrap a function around the whole thing, replace the IDs with classes, so that document.getElementById(x) becomes theDiv.getElementsByClass(x)[0], and rewrite the function that extracts query string parameters to get them from an options argument. But I wonder if there are any tools around that can assist in the process. If anyone has done a conversion like this, do you have techniques that help?
I took a look at your code ...
if(cardDivs[seat][suit][i].innerHTML=="") ...
Don't do that. Make a classic JS array of booleans to mark "empty items".
And generally, don't access DOM too much. It seems, that your whole "model" (from MVC terminology) and application state is stored in DOM.
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.