cwhisperer
cwhisperer

Reputation: 1926

ZF ajax general how to

I have some trouble with zend framework and ajax.

In a view I have a div with tabs. When I click on the UnitTab "#tabUnits" the Unit view is displayed with a list of items. There is also a link to add new Units, so the add view is loaded into the tab.

The link to add an unit is:

<a id="addUnit" href="idBuilding/<?= $this->idBuilding ?>" href="#"><img width="16" height="16" src="/images/icons/fugue/plus-circle-blue.png"></a>

and the ajax call is :

$(document).ready(function(){

    var url = '/unit/add/'+$("#addUnit").attr('href');

    // ADD
    $("#addUnit").click(function(event){
        event.preventDefault(); // link is not executed

        $.ajax({
            url: url,
            type: 'GET',
            success: function(data) {
                $("#tabUnits").html(data);
            },
            error: function(){
                alert('An error occurred, please check before continue...');
            }
        });

    });

});

When no error occurred the units are added and the list is displayed again.

How can I now do the same when I want to edit an Unit, knowing that the id is changing?

Upvotes: 0

Views: 297

Answers (1)

BartekR
BartekR

Reputation: 3977

It has not much in common with ZF, it's more just jQuery. If you want to use the same AJAX call for more elements, just change url variable. Something like (not tested):

<a class="link" data-url="add" id="addUnit" href="idBuilding/<?= $this->idBuilding ?>" href="#"><img width="16" height="16" src="/images/icons/fugue/plus-circle-blue.png"></a>
<a class="link" data-url="edit" id=editUnit" href="idBuilding/<?= $this->idBuilding ?>" href="#"><img width="16" height="16" src="/images/icons/fugue/plus-circle-blue.png"></a>


$(document).ready(function() {

    var url;

    // ADD
    $(".link").click(function(event){
        event.preventDefault(); // link is not executed

        url = '/unit/' + $(this).data('url') + '/' + $(this).attr('href');

        $.ajax({
            url: url,
            type: 'GET',
            success: function(data) {
                $("#tabUnits").html(data);
            },
            error: function(){
                alert('An error occurred, please check before continue...');
            }
        });

    });

});

More about data parameters: http://api.jquery.com/data/#data-html5

Upvotes: 1

Related Questions