Search code examples
htmx

Handle connection errors in htmxjs


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>)


Solution

  • 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 occurred')">
     ...
    </body>