Trigger polling using htmx.trigger - htmx

I'm trying to trigger a polling behavior on a div using JavaScript.
This is the div.
<div id="myId" hx-get="https://xxxx" hx-swap="innerHTML"></div>
This is the trigger function.
htmx.trigger(
htmx.find(`#myId`),
"every 300ms"
);
But it's not working. Is there a way to obtain this behavior?

You can have your JavaScript set up the polling interval. Then you can trigger a custom event and have your div listen for it.
To have the server stop the client polling, put a different custom event in the Response Headers and listen for it on the client. Included is how you would add the response header if your server was ASP.NET, since I'm not sure what you are running server-side. Also innerHTML is the default hx-swap target, so could be omitted.
HTMX:
<div id="myId" hx-get="https://xxxx" hx-trigger="myEvent"></div>
JS:
// start polling
function startpolling(){
var myPoller= setInterval(function () { htmx.trigger("myId","myEvent"); }, 300);
}
// stop polling
document.body.addEventListener("stopPolling", function(evt){
clearInterval(myPoller);
})
ASP.NET Server code:
HttpContext.Response.Headers.Add("HX-Trigger", "stopPolling");

Related

sending POST request to express route - after receiving form data, res.render is not triggered

I'm trying to create a simple app where a picture gets uploaded, and that picture is drawn on html canvas so that i can do some simple pixel manipulation.
Right now I have the GET method for root render an EJS template with a fileReader and a canvas.
With code attached at the bottom of the EJS file through script tags, I draw the uploaded image onto the canvas so I can read each pixel's rgb values.
I then tried to send those rgb values to the POST route in the app (through fetch), but it's not working as expected.
app.post("/", (req, res)=>{
console.log("inside post");
console.log(req.body);
res.render("test", {result: req.body});
console.log("after res.render");
});
All three of the console logs print correctly in the terminal, including the request body, but the test template is not being rendered. It just stays on the same "index" view the app launches with.
Can someone give me some insight as to why this is happening? I also included console logs inside the script tags in the ejs template, and these are only displayed in the browser, not in the terminal I launch the express app with. How can I render the view inside the post method?
First
If you use AJAX like Fetch API or XHR, browser will not render the test page.
Because it's asynchronous, and you could see Ajax in MDN web docs.
You need to use form post with following code.
<form action="/" method="post">
<button type="submit">go to another page</button>
</form>
But, if you use form post, your page which might be "index.ejs" will be replaced with "test.ejs".
In other words,
Browser uses the response from the forms POST request to load the new page.
But browser pass AJAX request's response to a callback and trigger callback in js.
Browser handle these two type request (Form Post and AJAX POST) with different ways.
In common, both are sending data to server.
So, in your case, res.render is triggered successfully.
Let me show you an example. Here is my server code.
const express = require('express')
const app = express()
app.set("view engine", "ejs")
app.get("/", (req, res, next) => {
res.render("test")
})
app.post("/test", (req, res, next) => {
res.render("other-test")
})
app.listen(3000)
<!-- test.ejs -->
<h1>this is test pages.</h1>
<!-- other-test.ejs -->
<h1>this is other test pages.</h1>
When I type url http://localhost:300, browser show me this.
And I open console in chrome and type following code.
fetch("/test", {
method: 'POST', // or 'PUT'
body: JSON.stringify({}), // data can be `string` or {object}!
}).then(res => {console.log("trigger response")})
Then go the network tab in chrome, you will see the request.
Here, this request trigger the express method.
But, what is the response?
Well, it's a html. That means res.render("other-test") is triggered correctly.
And you will find the console output show "trigger response" which callback is triggered in my fetch.
And, page still stay in "test.ejs".
Next, I add following code in my test.ejs
<form action="/test" method="post">
<button type="submit">Go to other page</button>
</form>
Page will be like this.
After you click, you will find out the browser show you "other-test" content.
That's a difference between form post and ajax post.
Second
You put script tag into ejs template.
Express will use ejs engine to render your ejs template become to html page.
After it become to html page, it means all script is running in browser not your nodejs terminal.

window.parent.postMessage to #Listener

We have a requirement that we load a separate page as a modal (yay, right?)
The embedded page uses window.parent.postMessage(messageString, '*') to signal actions have been completed.
I want to use stenciljs's #Listener
I have a working modal with an iframe to the other page, using the old school window.addEventListener('message', myMessageHandlingDelegate).
however, I really would like to use the #Listener attribute/decorator to handle the result of the posted message. I tried #Listener('message') but the code was not added....
is there away to get a stenciljs listener to catch messages posted from child Iframes?
The #Listen decorator is used to add listener to JavaScript custom events (https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent) or to events emitted by a Stencil child component. That means that you can't use Message API (using window.postMessage or listening to the message event) with that decorator. You can still use the addEventListener to the message event like you indicated in the question.
I used the following code in the stenciljs custom component to get this working:
#Listen('message', { target: 'window' })
handleMessage(ec) {
console.log("Event from iFrame triggered");
}

Vue prerender flickering

I have the following solution now:
<template>
<section id="prod-main">
<prod-preview v-for="prod in products" :id="prod.id" :key="prod.id"/>
</section>
</template>
export default {
...
computed: {
products: function () {
return this.$store.getters['products/getPreview']
}
}
...
}
Vuex store will receive info after some delay from my backend. So at first call it will be empty. Now I want to use vue spa prerender and here I see a flickering.
As I understood it works like:
1. Browser loads HTML with products
2. Execute js that replace products with nothing because the store is empty.
3. After some delay shows it again with backend info.
How can I fix it? I should left prerender for indexing and I can't hardcode the backend reply.
You can use the setting captureAfterTime to wait for your async call to complete, before saving the html of the page.
Other settings are available :
// NOTE: Unless you are relying on asynchronously rendered content,
// such as after an Ajax request, none of these options should be
// necessary. All synchronous scripts are already executed before
// capturing the page content.
// Wait until a specific event is fired on the document.
captureAfterDocumentEvent: 'custom-post-render-event',
// This is how you would trigger this example event:
// document.dispatchEvent(new Event('custom-post-render-event'))
// Wait until a specific element is detected with
// document.querySelector.
captureAfterElementExists: '#content',
// Wait until a number of milliseconds has passed after scripts
// have been executed. It's important to note that this may
// produce unreliable results when relying on network
// communication or other operations with highly variable timing.
captureAfterTime: 5000,
Another issue can be related to how the prerendered HTMl gets hydrated, i've openned an issue on github, but they still haven't addressed it (and are not willing to ?)
https://github.com/chrisvfritz/prerender-spa-plugin/issues/131
The solution is to add data-server-rendered="true" to your vuejs parent node in the prerendered html, like this:
<div id="root" data-server-rendered="true">...
You can use the option postProcessHtml to do so.
I don't know if I understand your problem here but have you tried to add a v-if to avoid flickering:
<template>
<section id="prod-main">
<prod-preview
v-if="products.length > 0"
v-for="prod in products"
:id="prod.id"
:key="prod.id"/>
</section>
</template>

Press submit on Ajax Form from javascript / jquery timer

I would like to automatically click the submit button of an Ajax enabled form, so that the user does not have to click the button (but can optionally).
Right now, I'm working on the first boundary, which is to call the form from Javascript, so that at the very least, once i build my timer, I will have this part figured out.
I've tried many ways to do this, and NONE work. Please keep in mind that this is an ASP.NET MVC 4 Mobile application (which uses jquery.mobile) but I do have the jquery.mobile ajax disabled so that my button works at all (creating manual ajax based forms with updating divs, does not work in a jquery.mobile app because it hooks on the submit of all ajax forms).
So my current button works fine, I just can't seem to fire it programmatically.
I have my form:
<% using (Ajax.BeginForm("SendLocation", null, new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "result", HttpMethod = "POST" }, new { #id = "locationForm" }))
{ %>
<ul data-role="listview" data-inset="true">
<li data-role="list-divider">Navigation</li>
<li><%: Html.ActionLink("About", "About", "Home")%></li>
<li><%: Html.ActionLink("Support", "Support", "Home")%></li>
<li data-role="list-divider">Location</li>
<%: Html.HiddenFor(model => model.GPSLongitude)%>
<%: Html.HiddenFor(model => model.GPSLatitude)%>
<li><input type="submit" id="submitButton" value="Send" /></li>
</ul>
<% } %>
I have tried to do this in javascript:
$.ajax({
type: "POST",
url: action,
success: function () {
alert('success');
}
});
And I do get the server code firing that normally would. However, the DIV is not updated and also, the model was not intact either (it existed with all internal values null, so i assume newly instantiated).
I have also tried different ways to fire the form:
var form = $('#locationForm', $('#myForm'));
if (form == null) {
alert('could not find form');
} else {
alert('firigin on form');
form.submit(function (event) { eval($(this).attr("onsubmit")); return false; });
form.submit();
}
This did not work either:
var f = $('#locationForm', $('#myForm'));
var action = f.attr("action");
var data = f.attr("data");
$.post(action, data, function() { alert('back'); });
Which were all ways to do this that I found throughout the web.
None of them worked to fire the form and have it work the way it would normally as if a user had pressed the submit button themselves. Of course, once this fails, if I hit my submit button, it works perfectly...
Using Chrome Developer Tools, I found that the $.ajax call needs to have valid data before it will even attempt to function.
I was getting a silent Internal 500 Error on the post. But of course because of AJAX it was silent and the controller was not firing because it didn't get past IIS.
So I found out that the data I was sending, saying its JSON, was not and the .serialize() does not use JSON formatting. I tried to incorporate the JSON Javascript libraries to convert the object into JavaScript, however, this does not work either, because the Data Model object (or the form object) seems to not be compatible with those libraries. I would get errors in the JavaScript console and those libraries would crash when trying.
I decided to actually just pass the object I want manually:
var encoded = '{ GPSLongitude: ' + $('#GPSLongitude', $('#myForm')).val() + ',GPSLatitude: ' + $('#GPSLatitude', $('#myForm')).val() + '}';
Which passed the hidden fields i wanted to send (GPS LON/LAT) to the controller, and the model was intact in the controller call!
Now, for anyone that is reading this answer. the actual AJAX update process that is supposed to update the view, failed to work. Although for my purpose, I did not actually need the view to update correctly. Eventhough a partial view is returned, the special AJAX call seems to break the linkage between the form's div to update.
However, since the data was passed to the controller intact, this basically passed the GPS data that I needed to the server which was my ultimate goal.
make sure you are including the proper js libraries.
you need. jquery.js, jquery.unobtrusive-ajax.js
make sure unobtrusivejavascriptenabled = true in the web.confg
<appSettings>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
please try $('#locationForm').submit();
does it give error message?
if you're using i.e. you can look use the develper tools to look at network traffic to make sure nothing is sent.

How to use jQuery's .on with Rails ajax link?

I'm having a bunch of problems getting jQuery's .on to work with my Rails ajax link.
Specifically, I've got this link:
<div id="item_7_tools" class="item_tools">
<a rel="nofollow" id="book_item_7" data-remote="true" data-method="post" class="book_link" href="bookings">Book this item</a>
</div>
I've trimmed some of the text in the HTML, but suffice to say that that, and my controller response work.
I click "Book this item", it goes off to the controller, the controller does its magic, and sends back my partial that replaces the contents of that div.
So I'm now trying to replace the contents with an ajax spinner while the loading is working, and that's where its going pear-shape.
I'm trying this initial bunch of jQuery code just to make sure I've got my javascript working:
$('div.item_tools')
.on('click', 'a', function() {
console.log("clicky click")
})
.on('ajax:beforeSend', "a", function() {
console.log('the a in div.item_tools is sending its ajax command');
})
.on('ajax:complete', "a", function() {
console.log('ajax request completed');
})
My understanding of that, is that when I then click any link (a) that lives within an element with the item_tools class, it will bubble up to this function, and then log the message into the console. Similarly, a link that has triggered an ajax request will get the same treatment...
(And assuming I can get that to work, then I'll go to work doing the ajax loader spinner).
The behaviour I'm seeing instead, is that when I click the link, there are no messages appearing in my console (trying this on both firefox and chrome), and my ajax link goes off and does its stuff correctly. Just completely ignoring the javascript...
Is this because my clicking the ajax link somehow has blocked the click event from bubbling up? I know that there's a way to do that, but I don't think I've done it anywhere knowingly. Unless OOTB rails/ujs does that?
So my questions:
Is there a way to tell what has had a binding attached to it?
What am I doing wrong with my javascript?
Thanks!
I use this all the time... and it seems to work fine.
Have you tried adding one that's .on('ajax:success')?
Besides that try putting the . for each line on the previous line...? It's possible that it gets to $('div.item_tools') and then auto-inserts a semi-colon as per javascript's standard... Although if that were the case I'd expect it to give you a JS error about the . on the next line. In any case try changing it to:
$('div.item_tools').
on('click', 'a', function() {
console.log("clicky click")
}).
on('ajax:beforeSend', "a", function() {
console.log('the a in div.item_tools is sending its ajax command');
}).
on('ajax:complete', "a", function() {
console.log('ajax request completed');
})
If worse comes to worse try just doing:
$("a").on("ajax:success", function(){
console.log('ajax:success done');
})
And see if it works without the event delegation...
Then change it to this:
$(document).on("ajax:success", "a", function(){
console.log("ajax:success with delegation to document");
})
And see if delegation works all the way up to document instead of just your item_tools
Are you sure that you've named everything right? it's div.item_tools a in your markup?
Turns out that the javascript was being triggered before the DOM had loaded, which meant that stuff weren't being bound...
$(function () {
$('div.item_tools')
.on('click', 'a', function itemToolsAjaxy() {
console.log("clicky click");
})
.on('ajax:beforeSend', "a", function() {
console.log('the a in div.item_tools is sending its ajax command');
$(this).closest('div').html('<img src=/assets/ajax-loader.gif>');
})
});
Added the $(function()) right at the beginning and it delayed the binding until after the DOM had loaded, and then it started working.
Figured this out by using the Chrome developer tools to stick a break on the div.item_tools selector and watched as the browser hit that even before the DOM had been loaded. /facepalm
(I removed the .on('ajax:complete') callback, because it turns out that there's a known limitation where the original trigger element no longer exists because it had been replaced, so there's nothing to perform the callback on. Not relevant to my original problem, but I thought I'd mention it.)
As far as i'm aware, you can either do ajax stuff 2 ways:
By using :remote => true
By using jQuery's $.ajax (or $.post).
With number 2, make sure to change your href='#'
My suggeston is to remove the :remote => true and manually make a jQuery ajax call. That way you can use beforeSend, complete, etc.
If i'm way off track here, someone please help clarify things for me as well.