0

I have a search function in my django app using ajax. It displays all results from a model.

I want to limit the number of results the search returns on the page though, so when the queryset is so large the user should click on a 'see all results', rather than having heaps of results in the search box.

I'm trying to do this by adding a HTML form below, but when I click on the href it is creating a GET request. I'm not totally sure what I need to fix up here to pass the data to the view and render the new page.

resultsBox.innerHTML += `
    <a href="${url} ${'results'}" class="item">
        <form method="POST" class="post-form" input type="submit"
            {% csrf_token %}
            <action="${url} ${'results'}">
        </form>
        <div class="row mt-2 mb-2">
            <div class="col-2">
                img placeholder
            </div>
            <div class="col-10">
                <h5>See all results for "${quote}"</h5>
            </div>
        </div>
    </a>
`           `
M. Phys
  • 139
  • 15

1 Answers1

1

You are wrapping the entire form in the href, you probably just want See all results to be the link?

resultsBox.innerHTML += `
    
        <form method="POST" class="post-form" input type="submit"
            {% csrf_token %}
            <action="${url} ${'results'}">
        </form>
        <div class="row mt-2 mb-2">
            <div class="col-2">
                img placeholder
            </div>
            <div class="col-10">
                 <h5>
                   <a href="${url} ${'results'}" class="item">
                      See all results for "${quote}"
                   </a>
                 </h5>
            </div>
        </div>`

Alternatively (as noted in the comments below): to avoid a GET and have a POST instead, you want to submit a form, not follow a hyperlink: How to submit a form with JavaScript by clicking a link?

artoonie
  • 822
  • 5
  • 14
  • Clicking on the link is still sending a GET request though. How do I change this to a post request and send all the search data with it? – M. Phys Apr 06 '22 at 17:20
  • I see - you don't want a link, you want to submit the form. This is the answer you're looking for: https://stackoverflow.com/questions/6799533/how-to-submit-a-form-with-javascript-by-clicking-a-link – artoonie Apr 07 '22 at 18:58
  • Accepted your answer as the link you shared did the trick! I have an onclick button now that renders a new page. – M. Phys Apr 08 '22 at 07:06