How to create an external jQuery file?

I want to create an external JS file for the form and publish this data using AJAX.

Simplified HTML looks like this:

<form action="" id="message" name="message" method="post">
<input name="message_subject" type="text"  id="message_subject" class="message_wall" />
<textarea cols="50" rows="5" id="message_text" class="message_wall"></textarea>
<button type="submit" id="mess" class="mess">send</button>

The jQuery I'm currently using for this form:

$("form#message").submit(function() {
  var message_subject = $(".message_subject").attr('value').replace(/\n/g,"<br/>").replace(/\n\n+/g, '<br /><br />').replace(/(\<\/?)script/g,"$1noscript");
  var message_text= $(".message_text").attr('value').replace(/\n/g,"<br/>").replace(/\n\n+/g, '<br /><br />').replace(/(\<\/?)script/g,"$1noscript");
  $.ajax({
    type: "POST",
    url: "mess/somefile.php",
    contentType: "application/x-www-form-urlencoded;charset=ISO-8859-2",
    data: "message_subject="+ message_subject + "&message_text=" + message_text,
    success: function(){
      $(".message_field").html('Thanks!');
    }
  });
  return false;
});

Can I include this jQuery code in an external JS file and then call:

$(document).ready(function(){
  myexternalfunction();
});
+3
source share
4 answers

Yes, you can...

you can do this by linking js file with html like

<html>
<head>
<script>
//.........
// script calling some external js func
//.........
</script>
<body>
<!-- other tags -->
<script src="test.js" type="text/javascript"></script>
</body>
</html>

//test.js

$(document).ready(function()    {
        $('#arrow img').click(function()    {
            transferEmp('test');
        });
});

function transferEmp(postData)  {
    $.ajax({
        url: url,
        type: 'POST',
        data: postData,
        success: function(msg){
               //alert(msg);
        }
    });

}
+7
source

I would wrap your jQuery code in $ (document) .ready (function () code, which threw all the jquery code into a .js file, and then use standard html to include it.

When the page is loaded by the browser, your jQuery code will also be included.

+1
source
0

:

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="common.js"></script>

common.js :

function initialize()
{
    // Your jQuery code goes here
}

// Now you have to call this code
$(initialize);
0

Source: https://habr.com/ru/post/1754603/


All Articles