Click here to Skip to main content
15,887,477 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have a page where I want to load the search results when user inputs keywords in the input field. I've a search button when clicked on search button an search-body div appears In the search-body there's an Input field and user inputs the keywords to search and now after the user inputs the keywords I want to display the search results through extracting the keywords and Perform an xhr request to this url "https://[REDACTED]/ajax/movie/search?keyword=" and in the place of the keyword={input-keywordoftheinputfield} and through xhr request the contents should be loaded inside
HTML
<div id="block-result"></div>

also after making the request the content of "https://[REDACTED]/ajax/movie/search?keyword=" this page should be loaded without including the header and body, like this is
HTML
<body> 
<!--rest content-->
</body> 

and after body there's rest of its content like other div section etc all the contents should be loaded all things but just without including the body header and html. Here's the Code

HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Search</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">

   <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css" integrity="sha512-z3gLpd7yknf1YoNbCzqRKc4qyor8gaKU1qmn+CShxbuBusANI9QpRohGBreCFkKxLhei6S9CQXFEbbKuqLg0DA==" crossorigin="anonymous" referrerpolicy="no-referrer" />
  
<link rel="stylesheet" href="https://[REDACTED]/css/group_1/theme_4/styles.min.css?v=0.6">
</head>
<style>
    @import url('https://fonts.googleapis.com/css2?family=Neucha&display=swap');


*{
    margin: 0;
    padding: 0;
    font-family: 'Neucha', cursive;
}
html,body {
    background: rgb(248, 246, 246);
}
.srch{
    display: flex;
    justify-content: center;
    margin: 16px;
}
#sch{
    font-size: 22px;
    border-radius: 15px;
    width: 5em;
    font-weight: bold;
    color: black;
    background-color: rgb(121, 106, 95);
}
</style>

<body>
    <div class="srch">
        <button id="sch">Search</button>
    </div>

    <div id="search-body" style="display: none;">
        <div class="close-overlay" title="Close" id="close-button"></div>
        <div class="search-body-wrap xscroll">
            <div class="b-container">
                <div id="block-input">
                    <form class="search-content" id="search-form" action="/search">
                        <input autofocus="" autocomplete="off" name="keyword" required="" type="text" class="form-control search-input s-keyword" id="inpt" placeholder="Enter keywords...">
                        <div class="is-icon">^__i class="fas fa-search"></div>
                    </form>
                </div>
                <div class="loading-wrap text-center p-5" id="search-loading" style="display: none;">
                    <div class="d-flex justify-content-center">
                        <div class="spinner-border" role="status">
                            Loading...
                        </div>
                    </div>
                </div>
                <div id="block-result"></div>
            </div>
        </div>
    </div>
    <script>
        document.addEventListener("DOMContentLoaded", function () {
            let searchBody = document.getElementById("search-body");
            let closeButton = document.getElementById("close-button");
            let searchButton = document.getElementById("sch");

            searchButton.addEventListener("click", function () {
                searchBody.style.backgroundColor = "black";
                searchBody.style.display = "block";

            });
    
            closeButton.addEventListener("click", function () {
                searchBody.style.display = "none";
            });
        });
        
    </script>
    <script>
        let inputField = document.getElementById('inpt');
        let searchLoading = document.getElementById('search-loading');

       function checkInputValue() {
        // Check if the input field is not empty
        if (inputField.value.trim() !== '') {
            // Display the search loading element
            searchLoading.style.display = 'block';
        } else {
            searchLoading.style.display = 'none';
        }
        }

        // Check input value when the page loads and on every input change
        document.addEventListener('DOMContentLoaded', checkInputValue);
        inputField.addEventListener('input', checkInputValue);
    </script>
</body>
</html>


What I have tried:

I searched for it alot but couldn't find exact solution for this and I am not that familiar with xhr request thing and js although I can manage a bit to survive with js only a bit. So, anyone with the help would be very appreciated and Thank You.
Posted
Updated 8-Aug-23 23:19pm
v2
Comments
Richard Deeming 9-Aug-23 5:07am    
I have removed the site name from your question, since it is not relevant to your question, and could make this look like spam.

We get a lot of "streaming movie site" spam, so anything that even vaguely resembles that could result in the more trigger-happy members reporting you and your question.
Nischal Shar 9-Aug-23 10:41am    
cheers and thank you mate I've some more questions and doubt to clear about this can we connect other than this plattform would be helpful
Richard Deeming 9-Aug-23 10:42am    
No. Help happens on the site, or it doesn't happen at all.
Nischal Shar 9-Aug-23 11:02am    
okay the doubts
const url = new URL("https://[REDACTED]/ajax/movie/search?keywords={the keyword}");
url.searchParams.set("keyword", keyword);

I didn't understand this like you're doing this and
const url = new URL("https://[REDACTED]/ajax/movie/search");
url.searchParams.set("keyword", keyword);

this does not get the results https://[REDACTED]/ajax/movie/search
there should be this https://[REDACTED]/ajax/movie/search?keyword={the user's input}
and then when do the request and then only you can get the results of the content of this page https://[REDACTED]/ajax/movie/search?keyword={the user's input} and load it in.
THANK YOU
Richard Deeming 9-Aug-23 11:10am    
Once again: DO NOT post the URL of that site! You are starting to look like a spammer.

The line:
url.searchParams.set("keyword", keyword)

will append the value of the keyword variable to the URL's querystring.

Demo[^]
URL - Web APIs | MDN[^]

If you're not getting the user's input in the URL, then you're not getting the user's input in the keyword variable. You need to debug your code to find out why.

1 solution

XHR is an older technique. All modern browsers support the Fetch API[^], which is much nicer to work with. Especially if you combine it with async/await[^].

For example:
JavaScript
let abortController = null;

async function loadSearchResults() {
    if (abortController) {
        abortControler.abort("Reload");
    }
    
    const keyword = inputField.value.trim();
    if (keyword.length === 0) {
        // TODO: Tell the user to enter the keyword...
        return;
    }
    
    abortController = new AbortController();
    searchLoading.style.display = "block";
    try {
        const url = new URL("https://[REDACTED]/ajax/movie/search");
        url.searchParams.set("keyword", keyword);
        
        const response = await fetch(url, {
			credentials: "same-origin",
			signal: abortController.signal
		});
        
        if (!response.ok) {
            const responseText = await response.text();
            console.error(response.status, response.statusText, responseText);
            // TODO: Display an error message to the user...
            return;
        }

        const searchResults = await response.json();
        // TODO: Display the search results to the user...

    } catch (e) {
        console.error(e);
    } finally {
        abortController = null;
        searchLoading.style.display = "none";
    }
}

document.getElementById("sch").addEventListener("click", loadSearchResults);

Now you just need to fill in the "TODO" blocks. You might want to consider using a templating language like Handlebars[^] to transform the search results into an HTML fragment.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900