I am getting this error message when trying to submit a form in django using ajax and I cannot really tell what is bringing up this error. I have tried many solutions but they don't seem to be working as expected. This is the exact error showing up in my console:
csrfmiddlewaretoken=tHTBQbePA8SQrkk9SL18uCsPCIYLE5rey9dFd8vKUhlQDYbh2vLNC5Y5gl3QNXue&full_name=&bio=&email=&phone=:39 Uncaught ReferenceError: $ is not defined
at ?csrfmiddlewaretoken=tHTBQbePA8SQrkk9SL18uCsPCIYLE5rey9dFd8vKUhlQDYbh2vLNC5Y5gl3QNXue&full_name=&bio=&email=&phone=:39:7
index.html
<title>Django Form Submission</title>
</head>
<body>
<div >
<h1 >Create Profile</h1>
<h5 ></h5>
<form id="post-form">
{% csrf_token %}
<div >
<input type="text" id="full_name" name="full_name" placeholder="Full Name">
</div>
<div >
<input type="text" id="bio" name="bio" placeholder="Bio">
</div>
<div >
<input type="email" id="email" name="email" placeholder="Email Address">
</div>
<div >
<input type="text" id="phone" name="phone" placeholder="Phone">
</div>
<button type="submit" >Submit</button>
</form>
</div>
<script type="text/javascript">
$(document).on('submit', '#post-form', function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '/create',
data: {
full_name: $('#full_name').val(),
bio: $('#bio').val(),
email: $('#email').val(),
phone: $('#phone').val(),
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
},
success: function (data) {
("h5").html(data)
}
})
})
</script>
</body>
</html>
views.py
from django.shortcuts import render
from core.models import Profile
from django.http import HttpResponse
def index(request):
return render(request, 'index.html')
def create(request):
if request.method == 'POST':
full_name = request.POST['full_name']
bio = request.POST['bio']
email = request.POST['email']
phone = request.POST['phone']
new_profile = Profile(full_name=full_name, bio=bio, email=email, phone=phone)
new_profile.save()
success = 'Profile Created Successfully for ' full_name
return HttpResponse(success)
CodePudding user response:
Your snippet clearly uses the JQuery library, which uses $
as its namespace. You need to "import" this library, for example through the use of a CDN and an appropriate <script>
tag in your HTML:
<script
src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj 3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
crossorigin="anonymous"></script>