I’ve been sifting through many jQuery ajax tutorials and attempting to incorporate it with my Play! app but I’m not quite understanding a few things. Is it possible someone could explain how to do the following through Ajax calls:
1) Suppose I want to retrieve a list of Contacts from a controller (each Contact has name, phone, email). Does the controller need to “build” the proper response for the template? What does the controller look like? What does the javascript look like to retrieve it?
2) For adding/updating a new Contact through an ajax call, what does the javascript look like?
Here is code for an example of the explanation above (not using ajax):
Controller:
public static void list() {
List contacts= Contact.fetchAll();
render(contacts);
}
public static void add(String name, String phone, String email) {
Contact contact = new Contact();
contact.name = name;
contact.phone = phone;
contact.email = email;
contact.save();
}
public static void update(Long id, String name, String phone, String email) {
Contact contact = Contact.findById(id);
contact.name = name;
contact.phone = phone;
contact.email = email;
contact.save();
}
Template (lists all contacts):
#{list contacts, as:'contact'}
${contact.name}
${contact.phone}
${contact.email}
#{/list}
Template (add contact):
#{form @Contacts.add(), id:'form'}
<input type="text" name="name" />
<input type="text" name="phone" />
<input type="text" name="email" />
<input type="submit" value="Add" />
#{/form}
I’m not familiar with the Play side of things but if you wanted to retrieve some JSON data via an Ajax call the controller might look something like:
The jQuery to retrieve the JSON data would look something like:
To add/update a contact you might do something like:
You’d obviously want to add in lots of error handling. The
$.getJSONand$.postfunctions are shortcuts for the more flexible $.ajax. Look that up for more options.