Home > Software engineering >  How to call HTMX in a single html page
How to call HTMX in a single html page

Time:12-06

I'm new to HTMX and I have made this sample:

<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <script src="https://unpkg.com/[email protected]" integrity="sha384-wg5Y/JwF7VxGk4zLsJEcAojRtlVp1FKKdGy1qN OMtdq72WRvX/EdRdqg/LOhYeV" crossorigin="anonymous"></script>

        <form>
            <button hx-get="https://google.com/">Click Me!</button>
        </form>
    </body>
</html>

So I tried loading the htmx script firstly and then used hx-get to make a GET request for button.

But now the problem is, it does not work out at all!

It's like adding a button with no action and nothing also appears in the Console bar as js error!

So if you know how to call this htmx properly, please let me know..

Thanks.


UPDATE

I removed the <form> tags and it looks like the htmx is now calling but retrieves these errors:

enter image description here

How to call htmx properly

CodePudding user response:

When you click the submit button, the JS runs but you also trigger submission of the form.

Since Ajax is asynchronous, the form submits before the Ajax is complete. The browser then navigates to a new copy of the same page (killing the existing script, as a side effect, before the Ajax request completes).

Remove the form element from the document. You aren't using it for anything.


Your next problem is that Google does not give you permission to access it cross-origin.

CodePudding user response:

Please refer this answer

You are making a Request to a different domain than your page is on. So, the browser is blocking it as it usually allows a request in the same origin for security reasons. You need to do something different when you want to do a cross-domain request.

  • Make a request from same domain!!
  • Related