Posts

Showing posts with the label jQuery

Submitting Form Data with AJAX and jQuery

We will send form data without reloading the page using jQuery. We will not consider processing the server part. Sample form: <form id="test_ajax_form" method="post" action="test_handler_form.php"> <input type="text" name="name" placeholder="Name"> <textarea name="message" placeholder="Message"></textarea> <input type="submit" value="Send" name="submit"> </form> JS $(function(){ $('#test_ajax_form').on('submit', function(e){ e.preventDefault(); let data = $(this).serialize(), url = $(this).attr('action'); $.ajax({ method: "POST", url: url, data: data }).done(function(){ alert('Success!'); }).fail(function(){ alert('Error!'); }); }); });

How to create a custom jQuery plugin

The convenience of the jQuery plugin is that you can use the same code several times for different objects. In this case, copy-paste code is not needed. In addition, you can change the behavior of the plugin with different parameters. To write your jQuery plugin, you need to expand the $.fn object In general, it looks like this: $ . fn . MyPlugin = function ( ) { //plugin code } We write a plugin that will add a paragraph with the class "paragraph" after the selected object by clicking on it. By default we will set the red color of the text of our paragraph. ( $ => { $ . fn . myPlugin = function ( options ) { let settings = $ . extend ( { //set default parameters color : 'red' } , options ) ; //write the logic of our plugin $ ( this ) . on ( 'click' , function ( ) { let par = '<p class="paragraph">An added paragraph</p>' ; ...