Question

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}
Was it helpful?

Solution

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:

public static void getContacts() {
    List<Contact> contacts = // get contacts here...
    renderJSON(contacts);
}

The jQuery to retrieve the JSON data would look something like:

// the getJSON function automatically parses the returned JSON
// data into a JS data structure
$("#retrieve_contacts").click(function(event) {
    $.getJSON("/url/which/calls/controller/", function(contacts) {
        // do something with contacts list here...
    });
});

To add/update a contact you might do something like:

// call the controller to add the relevant contact with
// the info in the second param:
$("#add").click(function(event) {
    var newcontact = {
        name: $("input[name='name'").val(),
        phone: $("input[name='phone'").val(),
        email: $("input[name='email'").val(),
    };

    $.post("/url/which/adds/new/contact/", newcontact, function(data) {
        alert("Contact added!");
    });
});

You'd obviously want to add in lots of error handling. The $.getJSON and $.post functions are shortcuts for the more flexible $.ajax. Look that up for more options.

OTHER TIPS

hereis the simple example of using ajax with json in play using scala

here the code of json using ajax

@(list: List[User])(implicit session:play.api.mvc.Session)


@main(""){

     @if(list.size>0){
        @for(i<-list){
            <h1> welcome on ur Profile page </h1>
    your id is             @i.id <br>
    your first name is     @i.fnm <br>
    Your Last Name Is      @i.lnm <br>      
    Your password is       @i.pwd <br>
    And your address is    @i.res <br>
    and ur contact no. is  @i.num <br>      
        }       
    }else{
    Sorry, Please insert data in list before watching this page
    }
    }
<h4> want to know the details of other user click here  </h4><br>
<input type="button" value="FriendRequestList" onclick="friendList()">
<br/>
<br/>
<script>

function friendList() {
    $.ajax({
        type : "POST",
        url : "/userDetail",
        //data : "sender_id=" + id,
        success : function(data) {
            var d=JSON.parse(data);
            var inn="";
            for(var i in d){
            inn+="<label>"+d[i]["fnm"]+"</label>";
            inn+="<input type='button' value='SendRequest' onClick ='sendRequest(\""+d[i]["id"]+"\")'>";
            inn+="<br/>";
            }
            document.getElementById("output").innerHTML = inn;
        }
    });
}

function sendRequest(id) {
    $.ajax({
        type : "POST",
        url : "/sendRequest",
        data:{"receiver_id":id},
        success:function(){
            alert("hi");}
    });

} 
</script> 

<input type="button" value="YourRequest" onclick="RequestList()">
<br/>
<br/>
<script>
function RequestList() {
    $.ajax({
        type : "POST",
        url : "/requestList",
        //data : "sender_id=" + id,
        success : function(data) {
            var d=JSON.parse(data);
            alert(d[0])
            var inn="";
            for(var i in d){

            inn+="<label>"+d[i]+"</label>";
            inn+="<input type='button' value='AcceptRequest' onClick ='AcceptRequest(\""+d[i]["id"]+"\")'>";
            inn+="<br/>";
            }
            document.getElementById("output").innerHTML = inn;
        }
    });
}
function AcceptRequest(id) {
    $.ajax({
        type : "POST",
        url : "/acceptRequest",
        data:{"friend_id":id},
        success:function(){
            alert("request accept succcessfully ");}
    });
}
    </script>
<div id="output"></div>

For Logout Click Here <a href="/logout" >Logout</a> 

Download play and look at their booking example which seems to do pretty much exactly what you are looking for and is a great example of their use of jsaction....(plus you can run it yourself).

http://www.playframework.org/documentation/1.2.3/tags#jsaction

Basically, looks to me like they have an html file and they just insert the returned html into the div of the page which on the target html page that div is empty and they fill it in with another html file from play. (it's all in the booking example).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top