How to set an error message with Javascript?
The drupal_set_message() works by storing the messages into a session and displays when the page is reloaded.

If you want to show an error message through javascript, include js in your module (if working with some module).

You could simply append an error message on some event

    jQuery(document).ready (function(){
    jQuery(".error-message").append('&lt;div class="messages error"&gt;Error message to be displayed&lt;/div&gt;');
});


It will simply display an error message. You can apply further Js code as desired output.