简体   繁体   中英

Call Materialize javascript from Node.js

I have a form for a user to fill out. On the server-side, I'm using mailgun to send an email once the form has been submitted.

Upon an error, I want to display a toast dialog ( Materialize.toast("Error", 2500); in Javascript). Since the error checking happens on the server side, I'm not sure how to call that method.

I happen to be using a <script> inside the HTML to stop the page from refreshing upon a submission though--but I couldn't figure out how to handle errors in this <script> . Here it is:

<script type="text/javascript">
$("#contact-form").submit(function(e) {
    e.preventDefault(); // Prevents the page from refreshing
    var $this = $(this); // `this` refers to the current form element
    $.post(
        $this.attr("action"), // Gets the URL to sent the post to
        $this.serialize(), // Serializes form data in standard format

        function(data) {
        },
        "json" // The format the response should be in
    );
    Materialize.toast("Toasty McToastface!", 1000);
    $('#contact-form').trigger('reset');
});
</script>

I appreciate any and all help.

Upon an error, I want to display a toast dialog (Materialize.toast("Error", 2500); in Javascript). Since the error checking happens on the server side, I'm not sure how to call that method.

You'll have to return the error from your server-side script, and check the data from the success callback to see if there was an error or not.

The $.ajax() methodhas an error callback ( $.post() doesn't) but that will only be called when there is a timeout, a parse error, etc.

You could do it like this on the client :

$.post(
    $this.attr("action"),
    $this.serialize(), 
    function(data) {
       if(data.error) {
          Materialize.toast("Toasty McToastface!", 1000);  
       }
    },
    "json" 
);

Of course, for this to work, the server will need to respond with a JSON object that has an error property, set to true or false depending on wether or not the email was sent.

If you want the server to be able to communicate with the client outside of this callback, then you can use websockets (something like socket.io)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM