<html> <head> <script src="http://code.jquery.com/jquery-1.9.1.js"></script> <script src="js/adminScript.js"></script> </head> <body> <form action="/save" id="saveMeal"> <select name="course"> <option value="starter">starter</option> <option value="entree">entree</option> <option value="dessert">dessert</option> </select> Name: <input id="name" name="name" type="text"> Price: <input name="price" type="text"> Date: <input id="datepicker" name="date" type="text"> <input id="saveMealButton" type="submit" value="Check"> </form> <div id="result"></div> </body> </html>After this, we add a new template for the async response:
var entriesTemplate = template.Must(template.New("entriesHTML").Parse(entriesHTML)) const entriesHTML = `{{range .}}<div id="content">{{.Course}}{{.Name}}<input type="checkbox" name="checkbox" value="{{.Id}}"/></div></br>{{end}}`
And comment the saveHTML out.
After all we modify the Food struct, so we can save an Id (for us the actual timestamp, it is enough for our purpose) and we change saveTemplate to entriesTemplate
Now we do some JQuery, only easy stuff. Here is the script:
$( document ).ready(function() {$("#saveMeal").submit(function(event){ // Prevent from Default behavior, also submit event.preventDefault(); var formData = $("#saveMeal").serializeArray(); var URL = $("#saveMeal").attr("action"); $.post( URL, formData, function(data) { $('#result').html($(data).filter("#content")); }); }); });
We wait until the Document is ready or loaded, then we catch the #saveMeal form and serialize the form to an array. After that we get the URL in our example "/save". And than the magic happened. The server get our request for the URL and we put the formData. Then we use a callback function, which populate us the content do the "result" div.
Easy going, what?! At the end we have to modify our app.yaml.application: mycanteen version: 1 runtime: go api_version: go1 handlers: - url: /js static_dir: js - url: /.* script: _go_app
We added a static_dir, so the app engine finds the scripts.
P.S. Checkout my repository on Bitbucket for the latest code! https://bitbucket.org/loose11/mycanteen
No comments:
Post a Comment