Anoop
Anoop

Reputation: 543

Call Ajax call with two difrent urls

I am having a search box

                <div id="" class="col-10 pt-2  page-title">
                    <label>
                        <input type="search" id="search" class="form-control form-control-sm " placeholder="Search">
                    </label>
                </div>

My requirement is when I am pressing any character and click the enter button it need to be search

var x = document.getElementById("search");
x.addEventListener("keyup", function(event) {
  if (event.keyCode === 13) {
   var search = document.getElementById("search").value;
    console.log(search)
  }
});

This will print the word that I have typed in console ....

I am having a Ajax call

     $.ajax({
        dataType: "json",
        url: "{% url 'some url name' %}?limit=10",
        },

This will load the 10 records ....

The same API will work with search also .... In this we need to pass one extra param ....

     $.ajax({
        dataType: "json",
        url: "{% url 'some urn name' %}?limit=10?q="+seach,
        },

But the search value becomes undefined at the time of calling the url

How do I call the same Ajax call for the first load with url = "{% url 'some url name' %}?limit=10" and if the user search something same ajax call with url "{% url 'some urn name' %}?limit=10?q="+seach,

Upvotes: 0

Views: 47

Answers (3)

Rezaa91
Rezaa91

Reputation: 510

Just do a conditional check to make sure the search input has a value and is not undefined before building the url, something like this should cut it:

function makeApiCall() {
    const searchValue = document.querySelector('#search').value;
    const url = searchValue ? `http://myapi.com?limit=10&q=${searchValue}` : 'http://myapi.com?limit=10';
    
    $.ajax({
      dataType: "json",
      url
    }
  }

Upvotes: 0

Barmar
Barmar

Reputation: 780798

Get the value of the input before the AJAX call, not in the event listener.

var search = document.getElementById("search").value;
$.ajax({
    dataType: "json",
    url: "{% url 'some urn name' %}?limit=10&q="+encodeURIComponent(search),
    ...
});

Also, you need to separate multiple query parameters with &, not ?. And you should call encodeURIComponent() to ensure that the search string is encoded properly in the URL.

Upvotes: 1

Musa
Musa

Reputation: 97672

Wrap the ajax call in a function that takes the search term as a parameter.
If the search term is not blank add it to the URL properly encoded otherwise leave it out.
When calling it the first time pass a blank string.
In the key-up event call the function with the search variable as the parameter.

Upvotes: 0

Related Questions