why are use jQuery serialize()?

1 votes
40 views
Ethan Karla asked 28-Jul-2021 in Web Application by Ethan Karla

 jQuery serialize()? 

1 Answer

1 votes
Ravi Vishwakarma answered 02-Aug-2021 by Ravi Vishwakarma

We use jQuery serialize() method to take data from tag, by calling serialize(), complete data of form comes in URL form. It takes data from input, textarea, select tags and converts it to URL format. It is used in Ajax. So that the data can be sent easily. Earlier we had to take data one by one from the form tag. 

Syntax:
$ (selector).serialize()
return the form data in URL form 

Example

<!doctype html>

<html lang='en'>
<head>
    <!-- Required meta tags -->
    <meta charset='utf-8'>
    <meta name='viewport' content='width=device-width, initial-scale=1'>
    <!-- Bootstrap CSS -->
    <link href='https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css' rel='stylesheet' integrity='sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC' crossorigin='anonymous'>
    <script src='https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js'></script>
    <title>Login Page</title>
    <script>
        $(document).ready(function () {
            $('button').click(function () {
                $('p').text($('form').serialize());
            });
        });
    </script>
</head>
<body>
    <div class='jumbotron d-flex justify-content-center flex-column align-items-center'>
        <h1 class='py-4'>Login</h1>
        <form class='d-flex flex-column' action='' method='get'>
            <input type='email' class='form-control my-1' placeholder='Enter your email' name='emial' value=''/>
            <input type='password' class='form-control my-1' placeholder='Enter your password' name='password' value=''/>
            <input type='submit' class='btn btn-primary my-1' id='submit' />
        </form>
        <button class='btn btn-primary my-1'>Get Value</button>
         <p class='py-4'>Your are enter</p>
    </div>
    <script src='https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js' integrity='sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM' crossorigin='anonymous'></script>
</body>
</html>

Output:

why are use jQuery serialize()?