Last active
March 15, 2017 16:55
-
-
Save nix1947/8e9925141aa757e1f45c418db83f5513 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def course_ajax_search(request): | |
if request.method == "POST": | |
search_text = request.POST.get('search_text') | |
# Full text search | |
if len(search_text) < 2: | |
return HttpResponse(" ") | |
courses = Course.objects.filter( | |
course_name__contains=search_text | |
) | |
print(courses) | |
courses = serializers.serialize( | |
'json', courses, fields=('slug', 'course_name',) | |
) | |
return HttpResponse(courses, content_type="application/json") | |
else: | |
return HttpResponseRedirect("/courses") | |
$(document).ready(function(){ | |
$("#navbarSearchForm").click(function(){ | |
// Display search modal box. | |
$('#navbar-search-modal').modal('show'); | |
// Initially set the search result to empty value. | |
$("#navbar-search-result").html(""); | |
// On click keyup modalSearchForm do ajax search | |
$("#modalSearchForm").keyup(function(){ | |
// Check for empty input and value less than 3 character. | |
console.log("Keyup is pressed with value"+ $("#modalSearchForm").val().length); | |
if($("#modalSearchForm").val().length <=2 || $("#modalSearchForm").val() == ""){ | |
// set the result to empty. | |
$("#navbar-search-result").html(""); | |
return; | |
} | |
// If the value length > 3 and not empty | |
if($("#modalSearchForm").val().length >2 && $("#modalSearchForm").val()){ | |
// do the ajax search | |
var searchText = $("#modalSearchForm").val(); | |
$.ajax({ | |
url: 'http://localhost:8000/courses/ajax/', | |
method: "POST", | |
beforeSend: function() { $('#animation').addClass('loader'); }, | |
complete: function() { $('#animation').removeClass('loader'); }, | |
data:{ | |
'search_text': searchText, | |
'csrfmiddlewaretoken': '{{csrf_token}}', | |
}, | |
success: function(data){ | |
// If the data length is empty, set the value to no data found | |
if(data.length <= 0 ){ | |
$("#navbar-search-result").html("No Courses found"); | |
return; | |
} | |
var links = "" | |
$.each(data, function(index, course){ | |
// update the result | |
links += "<a href=/course/" + course.fields.slug + ">" + course.fields.slug+ "</a><br>"; | |
$("#navbar-search-result").html(links); | |
}); | |
}, | |
error: function(){ | |
$("#navbar-search-result").html("Oops ! Can't found courses"); | |
} | |
}); | |
} | |
}); | |
}) | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment