With the power and elegance of HTMXJS and its companion _hyperscriptJS is a matter of few lines to write a code that selects, uploads (POST) multiple files shows a progress bar and then display them:
<form hx-encoding="multipart/form-data"
_="on htmx:xhr:progress(loaded, total) set #bar.value to (loaded/total)*100">
<input type="file" name="fileToUpload[]" multiple
hx-post="upload.php"
hx-target="#image-src"
hx-swap="innerHTML">
<button type="button">Select</button>
<progress id="bar" value="0" max="100"></progress>
</form>
<div id="image-src"></div>
and upload.php:
$countfiles = count($_FILES['fileToUpload']['name']);
for($i=0;$i<$countfiles;$i++){
$filename = $_FILES['fileToUpload']['name'][$i];
move_uploaded_file($_FILES['fileToUpload']['tmp_name'][$i], $filename);
echo '
<div>
<img src="'.$filename.'">
</div>
';
}
but now I would like to add network error handling. I know that HTMX fires
htmx:sendError, but I don't understand how to add it into my code above so that if there's a network error it pops-up a Alert (or swaps/shows the error into a <div>)
You are on the right track, the way to handle this is to hook into the htmx:sendError event.
If you wanted to do this with hyperscript, you could add the following code to your body tag (or any enclosing element of the element issuing the request):
<body _="on htmx:sendError call alert('A network error occured')">
...
</body>
Related
Page source (only iFrame part which contains to form i need to fill)
<iframe title="Form 0" id="hs-form-iframe-0" >
#document
<html>
<body>
<form id="hsForm_405e4c3f-98da-4eb1-bd27-c1886a1f811e">
<div>
<label placeholder="Enter your Vorname">Vorname</span>
<div class="input">
<input name="firstname">
</input>
</div>
</div>
</form>
</body>
</html>
</iframe>
Code i tried:
cy.get('#hs-form-iframe-0').its('0.contentDocument').should('exist')
cy.get('input[name="firstname"]').type( 'Smith') //failes as never found. Is the iFrame the cause of it? Of the form?
TLDR The correct way would be to use .find() on the iframe contentWindow.
cy.get('#hs-form-iframe-0').its('0.contentWindow').should('exist')
.its('body').should('not.be.undefined')
.find('input[name="firstname"]').type( 'Smith')
Example from Working with iframes in Cypress
const getIframeWindow = () => {
return cy.get('iframe[data-cy="the-frame"]')
.its('0.contentWindow').should('exist')
.its('body').should('not.be.undefined')
}
cy.getIframeBody().find('#run-button').should('have.text', 'Try it').click()
There are other potential problems, such as delayed loading of the iframe source. The .should('exist') check on the iframe window does not cover all situations, nor does performing visibility checks on the input.
The cypress-iframe package has a lot more checks built in, so it's a safer way to handle iframes.
You have found the iframe and access its contents but then you search for the input at the root of your DOM instead of the iframe. You can continue the chain of commands by removing the second cy.
cy.get('#hs-form-iframe-0')
.its('0.contentDocument')
.should('exist')
.get('input[name="firstname"]')
.should('be.visible') // always good to check before action
.type( 'Smith')
I've got a hidden file input field like this:
<input type="file" id="fileToUpload-1827" multiple="" onchange="angular.element(this).scope().setFiles(this)" data-upload-id="1827" class="hidden-uploader">
I'd like to be able to upload files to this. The normal way to do this in protractor would be to do:
ptor.findElement(protractor.By.css('.file-upload-form input')).sendKeys('/path/to/file')
But because the input element isn't visible, I get an error.
I tried:
ptor.driver.executeScript("return $('.file-upload-form input')[0].removeClass('hidden-uploader');").then(function () {
ptor.findElement(protractor.By.css('.file-upload-form input')).sendKeys('hello');
})
But got the error
UnknownError: $(...)[0].removeClass is not a function
It seems ridiculous to have to use executeScript to make an element visible so that I can upload a file, is there a better way? If not, how do I unhide the element?
The full html for the input form is:
<form class="file-upload-form ng-scope ng-pristine ng-valid" ng-if="ajaxUploadSupported">
<strong>Drag files here to upload</strong> or
<label for="fileToUpload-1953">
<div class="btn btn-info select-file-btn">
Click to Select
</div>
</label>
<div>
<input type="file" id="fileToUpload-1953" multiple="" onchange="angular.element(this).scope().setFiles(this)" data-upload-id="1953" class="hidden-uploader">
</div>
</form>
The only way I could find to do this in the end was to use javascript to make the input element visible.
So I have a function unhideFileInputs:
var unhideFileInputs = function () {
var makeInputVisible = function () {
$('input[type="file"]').removeClass('hidden-uploader');
};
ptor.driver.executeScript(makeInputVisible);
}
This contains the function 'makeInputVisible' which is executed in the browser when I call ptor.driver.executeScript(makeInputVisible). Because I know my page contains jQuery I can use the jQuery removeClass method to unhide my file input element.
To see more on how to execute javascript in the browser using webdriver, see the answer to this question (although the answer uses executeAsyncScript rather than executeScript).
To add on user2355213s answer for the more current releases of protractor. ptor is obsolote and instead browser should be used. Also, executeScript() expects a string as parameter. So I ended up using
browser.executeScript('$(\'input[type="file"]\').attr("style", "");');
as my visibility setting was directly applied to the element. Of course, you can also use
browser.executeScript('$(\'input[type="file"]\').removeClass("hidden-uploader");');
depending on your HTML/CSS.
I am programming a server side script on an Apache machine with cgi. I am using C for the cgi programming. I am a total noob and learning from online examples(I must say except the basics I didn't come across more web sources for detailed learning!).
I am having a simple HTML page where the username(input) is added to a list which is a file I have in my system and then the updated list should be displayed in the SAME PAGE.
I am not able to "print" the results of both the script and http link on the same page so therefore in the code below, you will only see buttons. Please help.
Here is what I have:
Html:
<html>
<head><title>Home</title></head>
<body>
<h1>REGISTER</h1>
<form action= "/cgi-bin/mycgi.cgi" name ="create user" method ="get">
Enter name:<input type="text" name="user">
<br>
<input type="submit" value="add">
</form>
<FORM action="http://localhost:8000/getusers/" method="get">
<P>
<input value="Display Users" type="submit">
</P>
</FORM>
</body>
Here is the cgi Code:
#include<stdio.h>
#include<string.h>
int main(){
char *tmpStr;
char *user;
printf("Content-Type:text/html\n\n");
printf("<html><head><title></title></head><body>");
tmpStr = getenv("QUERY_STRING");
while(tmpStr && *tmpStr != '='){
tmpStr++;
}
user = tmpStr+1,
printf("Adding %s to User Database",user);
//system("wget http://localhost:8000/newuser/");//call script to add user?
printf("</body></html>");
return 0;//return user?
}
Could you please tell me how I can realize these? How can I display the user list without opening a new html site? Also in the above C code, I have to call the link "http://localhost:8000/newuser/" which returns a success or failure value. How can I return it to the parent form?
Thanks.
You could add an iframe to your html:
<iframe id="theiframe" name="theiframe"></iframe>
And then setting the target of your form to the iframe:
<form action= "/cgi-bin/mycgi.cgi" name ="create user" method ="get" target="theiframe">
Anyway, it is not clear to me if the updated list should be displayed when you click on the first or second button.
I've got a very simple function, of replacing the innerHTML of a element. I've been trying to debug this for hours but simply can't, and it's infuriating.
When called from a button press the JavaScript (as follows) works well, but when called from another function it doesn't work. I am totally lost as to why this might be, and its a fairly core part of my app
// This loaded function in my actual code is a document listener
// checking for when Cordova is loaded which then calls the loaded function
loaded();
function loaded() {
alert("loaded");
changeText();
}
function changeText() {
alert("started");
document.getElementById('boldStuff').innerHTML = 'Fred Flinstone';
}
Button press and HTML to replace
<div id="main">
<input type='button' onclick='changeText()' value='Change Text'/>
<p>Change this text >> <b id='boldStuff'> THIS TEXT</b> </p>
</div>
It is also here in full on JSFiddle
You are already changed the innerHTML by calling the function loaded(); on onLoad.
Put this in an empty file and same as .html and open with browser and try. I have commented the function loaded();. Now it will be changed in onclick.
<div id="main">
<input type='button' onclick='changeText();' value='Change Text'/>
<p>Change this text >> <b id='boldStuff'> THIS TEXT</b> </p>
</div>
<script>
//loaded();
function loaded() {
alert("loaded");
changeText();
}
function changeText() {
alert("started");
document.getElementById('boldStuff').innerHTML = 'Fred Flinstone';
}
</script>
The problem here is, that the element you're trying to manipulate is not yet existing when you are calling the changeText() function.
To ensure that the code is only executed after the page has finished loading (and all elements are in place) you can use the onload handler on the body element like this:
<body onload="loaded();">
Additionally you should know, that it's very bad practice to manipulate values by using the innerHTML property. The correct way is to use DOM Manipulations, maybe this can help you.
You script loads before the element (boldStuff) is loaded,
Test Link - 1 - Put the js in a seperate file
Test Link - 2 - put the js at the very end, before closing the <body>
I'm working on a website that has a “Sign up” page which should be callable from anywhere in the site.
I have the following dummy interface and implementation for the “user” product:
Interface:
##
## located in bahmanm/sampleapp/interfaces.py
##
class ISampleAppUser(Interface):
"""
"""
Implementation:
##
## located in bahmanm/sampleapp/implementation/SampleAppUser.py
##
class SampleAppUser:
"""
"""
implements(ISampleAppUser)
# Note that this method is outside of the implementation class.
#
def manage_addSampleAppUser(self, id, title):
# ...
Now, for the moment, let's assume there's a link on the index page which leads to the following template (Sign up template):
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns="http://xml.zope.org/namespaces/tal">
<head><title>Add a new User</title></head>
<body>
<h2>Add a user instance</h2>
<form action="#" method="POST"
tal:attributes="action python:'manage_addSampleAppUser'">
<p>Id: <input type="text" name="id"/></p>
<p>Title: <input type="text" name="title"/></p>
<input type="submit" value="Add"/>
</form>
</body>
</html>
However I haven't been able to find the right value for action property of the form; all I get is a “resource not found”.
Honestly, I believe it's a problem of understanding Zope's mechanisms on my side. I'd really appreciate any hints/clues on where should I go digging for the solution, configure.zcml or the implementation or the template itself. TIA,
You really want to create a view for that; you can call a Product factory like that from a URL too, but it is not recommended.
With a view, you can combine the form and the code to create the new user in one place:
from zope.publisher.browser import BrowserPage
from sampleapp.implementation.SampleAppUser import manage_addSampleAppUser
class NewUserSignup(BrowserPage):
def __call__(self):
# called when the view is being rendered
if 'submit' in self.request:
# form was submitted, handle
self.addUser()
return self.index() # render the template
def addUser(self):
# extract form fields from self.request.form
# validation, error handling, etc.
if someerror:
self.error = 'Error message!'
return
user = manage_addSampleAppUser(self.context, id, title)
# add things to this new user if needed
# all done, redirect to the default view on the new user object
self.request.response.redirect(user.absolute_url())
then register this view with something like:
<browser:page
for="*"
name="signup"
class=".signup.NewUserSignup"
template="signup.pt"
permission="zope.public"
/>
When your new page is registered, the named template is added as a index attribute on your NewUserSignup class, so the __call__ method can invoke it (self.index()) and return the results.
Because you combined the signup handling and the template together, you can now easily incorporate error handling. When someone loads the page for the first time self.request.form will be empty, but as soon as someone hits the submit button, you can detect this and call the addUser method.
That method can either create the user and then redirect away from this page, or set an error message and return, at which point the form is re-rendered.
This makes the action easy to set; you could just leave it empty, or you can set it to the current context URL plus the name of the view. Together, the template then becomes:
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns="http://xml.zope.org/namespaces/tal">
<head><title>Add a new User</title></head>
<body>
<h2>Add a user instance</h2>
<div class="errormessage" tal:condition="view/error|nothing" tal:content="view/error">
Conditional error message appears here
</div>
<form action="#" method="POST"
tal:attributes="action string:${context/absolute_url}/##${view/__name__}">
<p>Id: <input type="text" name="id"
tal:attributes="value request/form/id|nothing" /></p>
<p>Title: <input type="text" name="title"
tal:attributes="value request/form/title|nothing" /></p>
<input type="submit" value="Add" name="submit"/>
</form>
</body>
</html>
Note how the form inputs are pre-filled with existing data from the request as well, making it easier for your visitor to correct any errors they may have made.