Skip to main content

How to insert form in url and read data from url without refresh page?

Insert form in  url and read data from url without refresh page


<html>
    <head>
    <script src="https://code.jquery.com/jquery-3.6.3.min.js" integrity="sha256-pvPw+upLPUjgMXY0G+8O0xUf+/Im1MZjXxxgOcBQBXU=" crossorigin="anonymous"></script>
    </head>
    <body>
        <Form action="" method="get" id="search_form">
            <input type="text" name="first_name" value="demo">
            <input type="text" name="last_name" value="tester">
            <input type="text" name="city" value="sangrur">
            <input type="submit" name="submit" value="Submit">
        </Form>
    </body>
    <Script>
        jQuery("document").ready(function($){
            $('#search_form').submit(function(e){
                e.preventDefault();
                var search_form = $(this).serialize();
                var refresh = window.location.protocol + "//" + window.location.host + window.location.pathname + '?arg=1&' + search_form;    
                window.history.pushState({ path: refresh }, '', refresh);

                var current_url = window.location.href;
                var url_data = parseURLParams(current_url);
                console.log(url_data);
                console.log(url_data['first_name']);
                
            })


            function parseURLParams(url) {
                var queryStart = url.indexOf("?") + 1,
                    queryEnd   = url.indexOf("#") + 1 || url.length + 1,
                    query = url.slice(queryStart, queryEnd - 1),
                    pairs = query.replace(/\+/g, " ").split("&"),
                    parms = {}, i, n, v, nv;

                if (query === url || query === "") return;

                for (i = 0; i < pairs.length; i++) {
                    nv = pairs[i].split("=", 2);
                    n = decodeURIComponent(nv[0]);
                    v = decodeURIComponent(nv[1]);

                    if (!parms.hasOwnProperty(n)) parms[n] = [];
                    parms[n].push(nv.length === 2 ? v : null);
                }
                return parms;
            }
        });
    </Script>
</html>

Comments

Popular posts from this blog

How to check date format in PHP?

Check date format in PHP function isCorrectDateFromat($date){     if(!empty($date)){         $dateString = $date; // Replace this with your date string         $format = "Y-m-d"; // Replace this with your expected date format         $dateTime = DateTime::createFromFormat($format, $dateString);         if ($dateTime === false) { /*             echo "The date is not in the correct format."; */         } else {             $errors = DateTime::getLastErrors();             if (empty($errors)) { /*                 echo "The date is in the correct format."; */                 return true;             } else { /*                 echo "...