Wednesday, December 11, 2013

Part VII: Now save and show asynchronous

Great stuff I have to told! We gonna make our app a little bit fancy. :-)
After this post, you got this:



We have to enhance our Javascript file and have to add a new function "show" to the go-code.
I also adjust the code a little bit, so we can save and receive a message if the storing was successful.


Our modified HTMLConstants + the template
// Parse the HTMLTemplate, despite it is not neccesary yet.
var adminPanelTemplate = template.Must(template.New("adminPanelHTML").Parse(adminPanelHTML))
var saveTemplate = template.Must(template.New("saveHTML").Parse(saveHTML))
var entriesTemplate = template.Must(template.New("entriesHTML").Parse(entriesHTML))

const saveHTML = `
Saved to Datastore!
` const entriesHTML = `{{range .}}
{{.Date}} {{.Course}}: {{.Name}} costs {{.Price}}$
{{end}}`

By the way we added to the adminPanelHTML a new form, so we can submit the button "save"

After that we add the new http.HandlFunc("/show", show) and the new show-function.
func show(w http.ResponseWriter, r *http.Request){

   allMeals := getAllEntries(r)

 if err := entriesTemplate.Execute(w,allMeals);err != nil{
    http.Error(w, err.Error(), http.StatusInternalServerError)
 }
 
}
Finally the Jquery-Code. It is very similiar to the function before, but we don't pass data via the ajax request.
$( document ).ready(function() {
 $("#saveMeal").submit(function(event){
  
   event.preventDefault();
   
      var formData = $("#saveMeal").serializeArray();
    var URL = $("#saveMeal").attr("action");
   
    $.post( 
              URL,
              formData,
              function(data) {
                 $('#result').html($(data).filter("#content"));
              }); 
      
    }); 
 $("#showMeal").submit(function(event){
  event.preventDefault();

  var URL = $("#showMeal").attr("action");
  $.post(
   URL,
   function(data){
    $('#result').html($(data).filter("#content"));   
   });
 });   

});



So thats all for this evening. Tommorow I will show you, how to delete some entries.

P.S. Checkout my repository on Bitbucket for the latest code!  https://bitbucket.org/loose11/mycanteen

No comments:

Post a Comment