Reputation: 351
I am building a web application using Django. I have a search function on my index page. When a user submits the form an AJAX call should be executed. This AJAX call should take all the needed data from the form and pass it over to a completely separate views.py template that will make API GET requests using that data and build a new page using that separate template.
As of right now it is not loading the separate views.py template, I am unsure if I am passing the data correctly however I do see /searchresults?searchType=data1&executeLocation=data2
in my console because my AJAX call is returning on success
currently. It is safe to assume that I have all the data needed in the data1 and data2 variables, I just need help redirecting to the new page and passing the data along with the redirect.
My code:
urls.py
# The home page
path('', views.index, name='home'),
# Search results page
path('searchresults', views.search_results, name='searchresults'),
AJAX
function getSearchResults(searchType,executeLocation,csrf_token)
{
$.ajax(
{
type: $(this).attr('method'),
url: "searchresults", //The URL you defined in urls.py
data :
{
searchType: searchType,
executeLocation: executeLocation,
csrfmiddlewaretoken: csrf_token
},
dataType: 'text',
success: function(response) // currently executes success (but not correct outcome)
{
console.log(response);
alert('winner winner chicken dinner');
},
error: function(response)
{
console.log(response);
alert('failure');
}
}).done(function(data)
{
console.log(data)
});
}
index.html
<form method="POST" action="{% url 'searchresults'%}">
...
<button type="submit" onclick="getSearchResults('data1','data2','{{csrf_token}}')">Submit</button>
</form>
views.py
def search_results(request):
context = {}
context['requestData'] = request.POST
html_template = loader.get_template('search/searchresults.html')
return HttpResponseRedirect(html_template.render(context, request))
An acceptable solution should be able to do the following tasks:
Upvotes: 0
Views: 34
Reputation: 351
After assistance from @AminMir I was able to get a working solution. It turns out I do not need AJAX but I did need a forms.py file.
view.py
def index(request):
context = {'segment': 'index'}
context['SearchForm'] = SearchForm()
return HttpResponse(html_template.render(context, request))
forms.py
from django import forms
class SearchForm(forms.Form):
searchType = forms.CharField(max_length = 100)
executedLocation = forms.CharField(max_length = 100)
searchValue = forms.CharField(max_length = 100)
index.html
<form method="POST" action="{% url 'searchresults'%}">
{% csrf_token %}
{{ SearchForm.as_ul }}
<input type="submit" value="submit">Search</button>
</form>
This form will then post my data to my views.py for my search_result page which is left unchanged.
Upvotes: 1