Solved

PHP, AngularJS and Ajax Calls

Posted on 2015-02-05
3
185 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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Things That Drive Us Nuts Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this.Insanity!  It's not EE's fault - that's just the way reCaptcha works.  But it is …
These days socially coordinated efforts have turned into a critical requirement for enterprises.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

911 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

21 Experts available now in Live!

Get 1:1 Help Now