I want to create external JS file for the form and post that data using AJAX.
The simplified HTML looks like:
<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 that 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 this Jquery code be put in an external JS file and then called like:
$(document).ready(function(){
myexternalfunction();
});
To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file. This script tag should be included between the <head> tags in your HTML document.
Your JavaScript file ( scripts. js ) must be included below the jQuery library in the document or it will not work. Note: If you downloaded a local copy of jQuery, save it in your js/ folder and link to it at js/jquery. min.
Step 1: Firstly, we have to open that Html file in which we want to add the jQuery using CDN. Step 2: After then, we have to place the cursor between the head tag just before the title tag. And, then we have to use the <script> tag, which specify the src attribute for adding.
yes you can...
you can do it by linking the js file to 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);
}
});
}
I would wrap your jQuery code in the $(document).ready(function() code throw all of the jquery code into a .js file, then use standard html to include it.
When the page is loaded by the browser, your JQuery code will be included as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With