0

I'm trying to build an email scraper on Django and that when you enter a URL, the result should be outputted in the same page. For now, the result is outputted in another page but I want it to be in the same one. I don't know how should I do this.

I know I should be using an AJAX request but don't know how to make the form take the action of the AJAX request.

Any help I would really appreciate it!

form:

<form class="card card-sm" action="{% url 'emailsearcher' %}" id='InputSearch' method="GET">
    <div class="card-body row no-gutters align-items-center">
        <div class="col-auto">
            <i class="fas fa-search h4 text-body"></i>
        </div>
        <!--end of col-->
        <div class="col">
            <input type="text" class="form-control form-control-lg form-control-borderless" placeholder="Introduce URL" name="Email" id="InputSearch" value="{{ Email.get }}" aria-describedby="searchHelp">
        </div>
        <!--end of col-->
        <div class="col-auto">
            <button class="btn btn-lg btn-success" type="search" onclick="total()">Find Email Address</button>
        </div>
        <!--end of col-->
    </div>
</form>
godtrianglefd
  • 179
  • 2
  • 12
  • for ajax form does not take an action, you would have to write javascript https://stackoverflow.com/questions/8567114/how-to-make-an-ajax-call-without-jquery – Sudhanshu Kumar Jan 11 '21 at 17:30

2 Answers2

1

instead of submitting the form use Javascript and The XMLHttpRequest Object to send data to your API and receive and view the results. you can learn more about AJAX here. there are some examples too.

For the backend of your requests, you have to implement some APIs which likely you want to use django-rest-framework. you are lucky because I have an awesome document to learn the Django REST Framework in Minutes.

mahyard
  • 1,230
  • 1
  • 13
  • 34
0

Don't use html form's submit event, instead create an async function that uses Javascript's fetch method. You can check the Mozilla's Docs here. The following snippet is an example of how post a json payload with your input to your python api:

<script>
function submitURL() {
  const url = document.querySelector("#InputSearch").value;
  const data = { url };

  fetch('https://my-api.com', {
    method: 'POST'
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(data),
  })
  .then(response => response.json())
  .then(data => {
    console.log('Success:', data);
  })
  .catch((error) => {
    console.error('Error:', error);
  });
}
</script>

And call the function at the submit button, as an "onclick" event, like this:

<button class="btn btn-lg btn-success" type="search" onclick="submitURL">
  Find Email Address
</button>