Ajax 2
Ajax 2
searched.
To develop a search application in Django using AJAX that displays courses enrolled by a student,
you'll need to follow these steps:
If you haven't already set up your Django project and app, follow the steps mentioned earlier to
create a new Django project (`enrollment_project`) and a new app (`enrollment`).
```python
class Student(models.Model):
name = models.CharField(max_length=100)
class Course(models.Model):
name = models.CharField(max_length=100)
```
```python
```
Define views in `enrollment/views.py` to handle rendering the home page and processing AJAX
requests:
```python
def home(request):
def search_student_courses(request):
if request.is_ajax():
if student_name:
try:
student = Student.objects.get(name__icontains=student_name)
courses = student.courses.all()
except Student.DoesNotExist:
else:
```
Create templates to render the search form and handle AJAX responses.
- **Template `enrollment/templates/enrollment/home.html`**:
```html
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<form id="searchForm">
<button type="submit">Search</button>
</form>
<div id="courseList">
</div>
<script>
$(document).ready(function() {
$('#searchForm').submit(function(e) {
e.preventDefault();
$.ajax({
type: 'GET',
url: '/search/',
data: {
'student_name': studentName
},
success: function(response) {
$('#courseList').empty();
if ('error' in response) {
} else {
if (courses.length > 0) {
});
html += '</ul>';
$('#courseList').html(html);
} else {
}
},
error: function(response) {
});
});
});
</script>
</body>
</html>
```
### Explanation:
- **Views (`enrollment/views.py`)**:
- `home`: Renders the home page (`home.html`) which contains the search form.
- `search_student_courses`: Handles AJAX GET requests to search for courses enrolled by a student
based on their name. Responds with JSON containing course names.
- **Template (`enrollment/templates/enrollment/home.html`)**:
- Uses jQuery for AJAX submission and updates the `#courseList` div based on the response from
the server.
Include your app's URLs in the project's `urls.py` (`enrollment_project/urls.py`), and make sure to
include `'enrollment'` in your `INSTALLED_APPS` in `settings.py`.
```bash
```
Navigate to `http://localhost:8000/` to see the search form. Enter a student's name and click
"Search" to see the courses enrolled by that student displayed dynamically without page refresh
using AJAX.
Adjust the code as per your application's requirements and design preferences.