Home > front end >  How to navigate to a new link from the search box results in Django template with ajax?
How to navigate to a new link from the search box results in Django template with ajax?

Time:05-23

I am creating a chat application in Django. I am using ajax to get search results to show up after each character is typed in the input box. It works fine. But now I am trying to add a link to the search results(which are just a name) so that if I click on one of the search results it goes to that link and views.chat_from_search is called where I handle all the logic of creating a chat and the rendering the page. I tried to add an event listener and then redirect to the new link (the code I tried to add the link is inside ** ** tags) but it results in this error Reverse for 'chatSearch' with arguments '('',)' not found. 1 pattern(s) tried: ['chat/search/(?P<chat_user_name>[^/] )/\Z'] My code for the ajax search and where I create the div that holds the search results (and my failed attempt to add a link) is inside sendSearchData (which is below). the ajax returns an array of objects which only has a username attribute. This is the structure of the objects (I am creating this and appending it to a list which I return)

indiv_user = {
                    'name': user.username,
                }



const sendSearchData = (contact_name) => {
  $.ajax({
    type: 'POST',
    url: '/search/',
    data:{
      'csrfmiddlewaretoken': csrf,
      'contact_name': contact_name,
    },
    success: (res) =>{
      const data = res.data;
      document.getElementById('search_result_box').innerHTML = ""
      if (Array.isArray(data)){

        data.forEach(contact => {
          document.getElementById('search_result_box').innerHTML   =
            " <div id ='" contact.name "'class='search-person'><h5 class='search-name'>" contact.name "</h5></div>";

          **document.getElementById(contact.name).addEventListener('click',function(){
            location.href= "{% url 'chatPage:chatSearch' contact.name %}"
          });**
        });

      }
    },
    error: (err)=>{
      console.log(err)
    }
  })
}

My urls.py is

from django.urls import path
from chatPage import views
app_name = "chatPage"
urlpatterns = [
    path('', views.homepage, name='homepage'),
    path('chat/<int:chatID>/', views.home, name='chat'),
    path('chat/search/<str:chat_user_name>/', views.chat_from_search, name='chatSearch'), #noqa
    path('search/', views.search_result, name='search')
]

Can anyone tell me why this isn't working? Also, how can I add a link inside the div after getting the result from ajax or should I approach this in a different way? I have been trying to figure this out for 2 days and any help would be appreciated. Thank you very much.

CodePudding user response:

The template formatting language (eg the {{ code }} and {% code %} parts) are evaluated before Djano delivers the page for the first time. It can't evaluate those after the page has been delivered to the browser, so it can't take your ajax results and format those. The error you are getting is because it is trying to perform the evaluation before the user has even gotten the page, and so it has no contact.name to use.

You'll have to construct your URL differently, using the ajax data and javascript alone. Thankfully, the URL construction seems simple in this case, and you already have the necessary variable so you should be able to use something like

location.href= "/chat/search/"   contact.name

The other option would be to update your post request to also include the chat search URL as part of the response, eg,

 contact { "name": user.name,
           "url" : reverse('chatsearch', kwargs={"chat_user_name": user.username]
         }

Then you could simply refer to

location.href= contact.url
  • Related