0

So I'm using angularjs/SQL technique to retrieve data from a database like so:

$http.get("retrieveData.php").then(function(response){
    $scope.tasks = response.data.tasks;
})

Then I have a function that allows me to use a form to insert new data into a database:

$scope.submitTask = function(){
    var description = document.getElementById("typeDescription").value;
    var todayDate = document.getElementById("todayDate").value;

    try{
        reminder = document.getElementById("reminder").value;
    }
    catch(err){
        reminder = "NONE";
    }

    var status = document.getElementsByName("selectStatus");
    var statusValue;

    for(i=0;i<status.length;i++){
        if(status[i].checked){
            statusValue = status[i].value;
        }
    }

    var xhttp = new XMLHttpRequest();

      xhttp.onreadystatechange = function() {
           if (this.readyState == 4 && this.status == 200) {
                document.getElementById("msg").innerHTML = this.responseText;
            }
      };
      xhttp.open("POST", "enterTask.php");
      xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhttp.send("desc="+description+"&status="+statusValue+"&reminder="+reminder+"&todayDate="+todayDate);
}

I'm sure my first problem is that I'm using JavaScript's AJAX instead of Angular's? But I don't know how to convert it.

Even so, I don't know how to then update the $scope.tasks.

I've looked online how to POST using Angular and haven't been able to find much. Just the tutorial on how to get.

Please don't give any JQuery. I am using pure JavaScript, thank you.


Thanks to some help I've restructured my code a bit (still mixing JavaScript but I plan to research Angular forms). Here is what I have now.

$http.get("retrieveData.php").then(function(response){
        $scope.tasks = response.data.tasks;
    })

    $scope.submitTask = function(){
        var description = document.getElementById("typeDescription").value;
        var todayDate = document.getElementById("todayDate").value;

        try{
            reminder = document.getElementById("reminder").value;
        }
        catch(err){
            reminder = "NONE";
        }

        var status = document.getElementsByName("selectStatus");
        var statusValue;

        for(i=0;i<status.length;i++){
            if(status[i].checked){
                statusValue = status[i].value;
            }
        }

        var task = {
            desc:description,
            status:statusValue,
            reminder:reminder,
            todayDate: todayDate
        }
        $http.post('enterTask.php', task).then(
            function(response){
                $scope.tasks.push(task);
            }
        );
    }

});

For some reason though, my $scope.tasks is still not updating after I add to the element. If I add an element to an empty database I get an angular error in my console.

TypeError: Cannot read property 'push' of undefined

Sooo. Not sure why this is.

When I alert the $scope.tasks after the push, it alerts 1 less than it should actually contain after push (once there is 1 or more elements in database to not produce above error).

Here is my HTML, maybe it has something to do with it?

<ul>
    <li ng-repeat="x in tasks" ng-bind="x.Description"></li>
</ul>
<form>
        <input type="text" value="{{today}}" id="todayDate">
        <textarea rows="15" cols="100" name="typeDescription" id="typeDescription"></textarea>
        <input type="checkbox" ng-model="setReminder" name="setReminder">Set Reminder
        <input type="date" name="reminder" id="reminder" ng-if="setReminder"><br>
        <input type="radio" name="selectStatus" value="CR">Client Response
        <input type="radio" name="selectStatus" value="IR">Internal Response
        <input type="radio" name="selectStatus" value="BD">BD Control
        <input type="radio" name="selectStatus" value="OC">On Calendar<br>
        <input type="submit" ng-click="submitTask();">
    </form>

Also my php...

<?php

/*$description = json_decode($_POST['desc']);
$reminder = json_decode($_POST['reminder']);
$todayDate = json_decode($_POST['todayDate']);
$status = json_decode($POST['status']);*/

$data = json_decode(file_get_contents("php://input"));

$description = $data->desc;
$reminder = $data->reminder;
$todayDate = $data->todayDate;
$status = $data->status;

require 'databaseConnect.php';

      $query="INSERT INTO TaskTracker (DATESTAMP,STATUS,DESCRIPTION,REMINDER) VALUES ('$todayDate','$status','$description','$reminder')";

      mysql_query($query) or die(mysql_error());

?>

The commented out part wasn't working so then I used the file_get_contents bit.

2
  • Mix of angular and javascript! i think you have to restructure your code Commented Oct 8, 2016 at 17:17
  • this can be reduced down to just a few lines of code by using ng-model to bind form controls to scope model. Study some tutorials on angular forms Commented Oct 8, 2016 at 17:34

2 Answers 2

1

In angular js posting data is very easy and it can be done in just 2 to 3 lines of code.

//first lets collect your data in an Object

var data = {
  desc: description,
  status: statusValue,
  reminder: reminder,
  todayDate: todayDate
}

//then send collected data using $http service

$http.post('enterTask.php',data).then(function(response){
    $scope.tasks.push(data);//After successful HTTP request you push the data  to your $scope.task array 
})
Sign up to request clarification or add additional context in comments.

Comments

0

You have to "tackle" some points to get the submitTask function into an angular way of thinking.

  • Use ng-model data binding from the input elements to the $scope. There are several tutorials out there. By using this you can get rid of the whole getElementById stuff.

  • Use $http.post to send the data over the wire.

  • Update the $scope.tasks array by simply adding/removing elements. The two way data bindung of angular will do the update for you in e.g. via ng-repeat

For the last to points I sketched the JavaScript code for you.

    $scope.submitTask = function(){
    var description = document.getElementById("typeDescription").value;
    var todayDate = document.getElementById("todayDate").value;

    try{
        reminder = document.getElementById("reminder").value;
    }
    catch(err){
        reminder = "NONE";
    }

    var status = document.getElementsByName("selectStatus");
    var statusValue;

    for(i=0;i<status.length;i++){
        if(status[i].checked){
            statusValue = status[i].value;
        }
    }

      var task = {
          desc: description,
          status: statusValue,
          reminder: reminder,
          todayDate: todayDate
      }
      $http.post('enterTask.php', task).then(
         function (response) {
           $scope.tasks.push(task);
         }
      );
}

8 Comments

My $scope.tasks is being used in ng-repeat. And the contents are being repeated just fine, however when I add a new element, it gets successfully added to my database but it is not being added to the ng-repeat until I refresh the page. What am I missing?
@Christine268 - the ´$scope.tasks´ is not changed in the code you have posted. So after submit it contains the same elements and only a page refresh (after the $http.get) shows the elements including the new one. Therefore after a successful $http.post command the first function in the .then function is executed (it is a so called fulfilled promise). This changes the $scope.tasks array by pushing the new element to the list.
I forgot to mention that I successfully implemented the $http code you posted, that replaces the JavaScript AJAX. The code is working as normal, but the $scope.tasks is not being updated. Is this what you mean by its not changed in the code I have posted?
I get it I get it. $scope.tasks.push(task) is adding the new elements to the "array" hmm. It's just still not updating the ng-repeat until I hit refresh.
@Christine268 - it is hard for me to tell, without the HTML part, why you see no refresh. Perhaps the task object with desc, status, reminder and todayDate properties is the right structure for the post, but the retrieveData.php function returns other properties and in the HTML other properties are used.This would lead to some "empty" item in your HTML. Another explanation is that enterTask.php returns an error code. Then the function is not executed - here you can set a breakpoint to check, if the $scope.tasks.push statement is executed.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.