Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

PHP, AngularJS and Ajax Calls

Posted on 2015-02-05
3
Medium Priority
?
218 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
3 Comments
 
LVL 111

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 111

Accepted Solution

by:
Ray Paseur earned 2000 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

On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

Question has a verified solution.

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

There are times when I have encountered the need to decompress a response from a PHP request. This is how it's done, but you must have control of the request and you can set the Accept-Encoding header.
Originally, this post was published on Monitis Blog, you can check it here . In business circles, we sometimes hear that today is the “age of the customer.” And so it is. Thanks to the enormous advances over the past few years in consumer techno…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

721 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