Reputation: 339
I have the following django template and I have defined a button in it so that it calls the javascript function which I added to the page like below. I have the below issues:
1) If I bring the script tags to the header section nothings shows up.
2) If press the button I get the undefined error message. (Uncaught ReferenceError: postData).
What am I mssing here?
Thank you very much, Mike
newproduct.html
{% load staticfiles %}
<!DOCTYPE html>
<html>
<head>
<title>New Product</title>
</head>
<body>
<p>Hellow</p>
<a href="/">Back</a>
<h2>Please enter product details:</h2>
<button onclick="postData();">Send Post</button>
<form action="http://127.0.0.1:8000/newproduct/" method="post">
<p>{{ message }}</p>
{% csrf_token %}
{{ form.as_p }}
<input type="submit"/>
</form>
<script src="bower_components/jquery/src/jquery.js" type="text/javascript"/>
<script src="scripts/main.js" />
</body>
</html>
main.js
function postData ()
{
$.post('/newproduct', {name:'New Product JS', price:555, });
};
Upvotes: 2
Views: 1821
Reputation: 166
Maybe you're getting trouble handling the path url, instead use the full path, try something like:
{% static ‘path/to/file’ %}
In your settings.py
STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),)
Remember that your static file dir is setted in the same level of your project.
Upvotes: 1
Reputation: 600059
You've hard-coded the reference to postData
in your HTML, but you've used it before you've defined it, since the JS isn't loaded until the end of the page.
You could fix this by moving the script to the top of the HTML, but it is better not to use JS directly in HTML like this. Rather, your script itself should use the jQuery dom-ready functionality to bind itself to the button event.
html:
<h2>Please enter product details:</h2>
<button id="my_button">Send Post</button>
main.js
$(function() {
$('#my_button').click(function() {
$.post('/newproduct', {name:'New Product JS', price:555, });
});
});
Upvotes: 6