Solved

PHP, AngularJS and Ajax Calls

Posted on 2015-02-05
3
174 Views
Last Modified: 2015-07-12
I'm starting to learn PHP and AngularJS. I've downloaded John Papa's Angular Template and with the datacontext.js I'm trying to make the following Ajax call from a Zend framework PHP controller, but I get an undefined error when trying to run the app.

http://www.johnpapa.net/hot-towel-angular/

The error isn't really the question I need answering. I'm looking for advice on the best method from an AngularJS JS script to call this Zend Framework PHP controller(web service). In the datacontext.js file I need to make a call to get the data to populate an array. Very simple but I'm not sure (as I'm still learning) if there is a better solution available.

// make the request
    $.ajax("<?=$this->baseUrl('/wsalarm/active')?>", {
        data: {
            dbQuery: "{}",
            filterIds: "[]",
            filterQuery: JSON.stringify(alarmQuery),
            query: "",
            start: pageStart,
            limit: pageLimit,
            sort: JSON.stringify(alarmSort)
        },
        dataType: "xml",
        error: function(xhr, textStatus, errorThrown) {
            // handle error
            var msg = "Unknown Error: "+JSON.stringify(xhr);
            if (xhr.status && xhr.responseText)
              {
                msg = "Error "+xhr.status+": "+xhr.responseText;
              }
            showError("Load Alarm List: "+msg);
            clearAlarmList();

            // clean up after load
            postAlarmLoad();
        },
        success: function(data, textStatus, xhr) {

            clearAlarmList();

            // update total count
            pageTotal = $(data).find("TotalAlarmCount").eq(0).text();
            pageTotal = (pageTotal == "") ? 0 : pageTotal;
            $("#activeAlarmCount").text(pageTotal+" active alarm"+((pageTotal == 1) ? "" : "s"));

            // update indicator
            setAlarmIndicator(pageTotal);

            // update paging text
            pageCurrent = 1 + Math.floor(pageStart/pageLimit);
            pageLast = 1 + Math.floor(pageTotal/pageLimit);
            $("#pagingStatus").text("Page "+pageCurrent+" of "+pageLast);

            // add rows
            var counter = 0;
            $(data).find("Alarm").each(function() {

                // find the alarm attributes
                var needsAck = false;
                var objectName = "<strong>"+$(this).find('Property[name="InputName"]').text()+"</strong>";
                var eventId = $(this).find('Property[name="EventId"]').text();
                var groupColor = $(this).find('Property[name="GroupColor"]').text();
                var evcText = "<span class='alarm-class'>"+$(this).find('Property[name="CategoryName"]').text()+" ("+$(this).find('Property[name="Priority"]').eq(0).text()+")</span>";

                // add transition data
                $(this).find('Transition').each(function() {
                    objectName += "<br/><span class='row-transition'>"+$(this).find('Property[name="AlarmText"]').text()+"</span>";
                    var tranDate = $(this).find('Property[name="TimeStamp"]').text();
                    evcText += "<br/>"+Delta.DateTime.getPrettyDateTime(tranDate);

                    // additional actions if it needs to be acknowledged
                    if ($(this).find('Property[name="Acked"]').text() == "0")
                      {
                        needsAck = true;
                        if (ackList[eventId] === undefined)
                          {
                            ackList[eventId] = [];
                          }
                        ackList[eventId].push({
                            "ProcessID": $(this).find('Property[name="ProcessId"]').text(),
                            "Timestamp": $(this).find('Property[name="RawTimeStamp"]').text(),
                            "ToState": $(this).find('Property[name="ToState"]').text()
                        });
                      }
                });

                // update count of alarms needing ack
                needAckCount += (needsAck == true) ? 1 : 0;

                // build up the row content
                var str = "<tr>";
                str += "<td class='row-group-highlight' style='background-color: "+groupColor+"'></td>";
                str += "<td class='row-object-name'>"+objectName+"</td>";
                str += "<td><span class='evc-text'>"+evcText+"</span></td>";
                str += "<td><div class='row-ack-button"+((needsAck) ? '' : ' disabled')+"' rel='"+eventId+"'>";
                str += ((needsAck) ? 'Acknowledge' : 'Acknowledged')+"</div></td>";
                str += "</tr>";

                // add to content div
                $("#alarmTable").append(str);

                // increment result counter
                counter++;
            });

            if (counter == 0)
              {
                var str = "<tr><td class='no-alarm-row' colspan='4'>No active alarms to display</td></tr>";
                $("#alarmTable").append(str);
              }

            // clean up after load
            postAlarmLoad();
        }
    });

Open in new window

0
Comment
Question by:wint100
  • 2
3 Comments
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 40593409
This has no AngularJS in it at all -- the signature of Angular is "ng-" used in ng-app and ng-controller as well as other tags, and none of these are shown here.  It may be jQuery?

If you're looking for ways to learn AngularJS, I can recommend these from personal experience:
http://tutorials.jenkov.com/angularjs/index.html (some typos, but well organized)
http://campus.codeschool.com/courses/shaping-up-with-angular-js/intro
https://thinkster.io/a-better-way-to-learn-angularjs/

You probably want to learn about the $http service, or maybe the $resource.
0
 
LVL 1

Author Comment

by:wint100
ID: 40595294
Thanks Ray. The sample I posted was from a phtml file that was being used on another project. I just need to know if Ajax calls are the way to go in Angular or if there is a better method to get data from the server. I'll have a look at the tutorials you posted.
0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 40595629
Angular calls with AJAX are a good design pattern.  They are typically implemented via the $http service ("service" is a term of art in Angular).  You use JSON to communicate, a very flexible and efficient transport mechanism.  Here are some additional resources that look good...
https://docs.angularjs.org/api/ng/service/$http
http://www.bennadel.com/blog/2612-using-the-http-service-in-angularjs-to-make-ajax-requests.htm
http://fdietz.github.io/recipes-with-angular-js/consuming-external-services/requesting-json-data-with-ajax.html

You will also want to learn about "promises."  They make callbacks nearly obsolete for many AJAX activities.
https://docs.angularjs.org/api/ng/service/$q
http://fdietz.github.io/recipes-with-angular-js//consuming-external-services/deferred-and-promise.html
http://markdalgleish.com/2013/06/using-promises-in-angularjs-views/

HTH, ~Ray
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

OverviewThis article demonstrates a simple search form using AJAX. The purpose of the article is to demonstrate how to use the same code to render a page and javascript (JQuery) and AJAX to make subsequent calls to refine the results. The princip…
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now