Christine268
Christine268

Reputation: 732

How to update my $scope after adding new data to SQL database

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.

Upvotes: 0

Views: 116

Answers (2)

Ganesh Devkate
Ganesh Devkate

Reputation: 119

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 
})

Upvotes: 1

Ralf B&#246;nning
Ralf B&#246;nning

Reputation: 15415

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);
         }
      );
}

Upvotes: 0

Related Questions