Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 234
  • Last Modified:

PHP, AngularJS and Ajax Calls

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
wint100
Asked:
wint100
  • 2
1 Solution
 
Ray PaseurCommented:
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
 
wint100Author Commented:
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
 
Ray PaseurCommented:
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

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now