Ways to refresh my $scope once new data is inserted into the SQL database

As I implement the angularjs/SQL technique to fetch data from a database, the code snippet below demonstrates how it is done:

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

In addition, there is a function that enables the insertion of new data into the database using a form:

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

The main issue lies in the usage of JavaScript's AJAX instead of Angular's. However, it appears challenging to make the conversion.

Moreover, updating the $scope.tasks after the insertion process remains a mystery.

Although attempts were made to explore Angular's POST method online, limited resources were found compared to GET functionality.

To clarify further, only pure JavaScript solutions are preferred over JQuery plugins.


After adjusting the code structure with assistance and planning to delve deeper into Angular forms, here is the updated version:

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

});

Despite these updates, an error persists where $scope.tasks fails to reflect newly added elements. An angular-related console error occurs when interacting with an empty database.

TypeError: Cannot read property 'push' of undefined

This peculiar behavior needs further investigation.

Upon inspection post-push operation, the quantity within $scope.tasks alerts one less than anticipated after the update (assuming at least one element exists in the database to avoid previous errors).

The provided HTML code may hold significance in understanding this anomaly:

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

Additional insights might be gleaned from inspecting the accompanying PHP script:

<?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());

?>

Troubleshooting efforts have led to utilizing the file_get_contents method due to issues faced with JSON decoding.

Answer №1

When working with AngularJS, sending data is a simple task that can be accomplished in just a few lines of code.

//Start by organizing your data into an object

var userData = {
  name: username,
  email: userEmail,
  address: userAddress,
  age: userAge
}

//Next, use the $http service to send the collected data

$http.post('addUser.php', userData).then(function(response){
    $scope.users.push(userData); //Upon successful HTTP request, add the data to your $scope.users array
})

Answer №2

To fully integrate the submitTask function into an angular framework, certain steps need to be taken.

  • Utilize ng-model data binding for input elements to link them with the $scope. Numerous tutorials exist to guide you through this process, eliminating the need for cumbersome getElementById operations.

  • Implement $http.post to transmit data over the network.

  • Update the $scope.tasks array by adding or removing elements directly. Angular's two-way data binding, such as with ng-repeat, will handle the updates for you automatically.

For the last two points, I have provided a basic outline of the JavaScript code below:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering problem while exhibiting server's response message within a modal popup in Angular 6

I have implemented two custom dialog modals in an Angular component. The objective is to open the appropriate modal and display the response message. The component receives two values as Observables from my services: The name of the modal that needs to ...

Populating dropdown menu with data from redux state upon component mounting

I am new to working with react-redux and have successfully implemented dependent dropdown functionality in a react component (Country => State => City). My goal now is to dynamically update the dropdown values based on data received from the redux s ...

The AngularJS initiation process

Currently, I'm working on managing the bootstrap process for a large AngularJS/Grails application. After experimenting with different methods, I have put together a plan that works, but I feel like there may be room for improvement in terms of cleanli ...

What is the proper way to handle postMessage events from a Streamlit iframe within a Next.js app?

I'm currently in the process of integrating a Streamlit app into a Next.js application by embedding the Streamlit within an iframe. My main goal is to send data from the Streamlit app to the Next.js parent using window.postMessage, specifically focusi ...

What is the best way to start data in an Angular service?

I'm currently navigating my way through building my first Angular application. One of the services I am using needs to be initialized with a schema defined in its constant block, but the schema/configuration is not yet finalized. Therefore, I am perfo ...

Tips on utilizing controllers within AngularJs directives?

In order to utilize a controller in my directive, what is the best way to access all controller functions within the directive? directive.js angular.module('App').directive('deleteButtons', function (prcDeleteFactory,$rootScope) { & ...

Converting Callbacks to Promises in Node.js

I am facing a challenge with my node js application as I am attempting to promisify multiple callback functions without success. It has reached a point where I am unsure if it is even feasible. If you can assist me in promisifying the code provided below, ...

Understanding how the context of an Angular2 component interacts within a jQuery timepicker method

Scenario: I am developing a time picker component for Angular 2. I need to pass values from Angular 2 Components to the jQuery timepicker in order to set parameters like minTime and maxTime. Below is the code snippet: export class TimePicker{ @Input() ...

Instructions on activating the standard scrolling function for a specific DIV element

I'm struggling to achieve a specific scrolling effect on my one-page website. I want the initial section to be displayed as a full page, and when the user scrolls down, it should transition to the next section with a full page scroll. However, once th ...

Using dynamic classes within a v-for loop

Edited How can I dynamically assign classes to multiple elements within a v-for loop? Since I cannot utilize a computed property due to the presence of v-for, I attempted using a method by passing the index of the element, but that approach did not yield t ...

What is the process for triggering a function event on click (or any other function) within a browser's activation?

Some time ago, I was trying to figure out why the onclick event wasn't working when I clicked on a specific area of the browser. After consulting a guide, I discovered the issue and fixed it. It turns out that the problem was quite simple, and now I u ...

Modify the text and purpose of the button

I have a button that I would like to customize. Here is the HTML code for the button: <button class="uk-button uk-position-bottom" onclick="search.start()">Start search</button> The corresponding JavaScript code is as follows: var search = n ...

What causes my code to break completely when I import something?

My chrome extension has a simple function that retrieves a user's selected text using the Chrome Tabs API. I am looking to integrate a Hugging Face API in the future, but I am facing an issue. Whenever I try to import the necessary model, the Chrome T ...

Difficulty establishing audio calls with Internet Explorer using PeerJS

I successfully implemented a user-to-user audio call system by following the steps outlined in this guide: The system is up and running flawlessly on my website while using Google Chrome. However, I encountered an issue when trying to connect to a user o ...

What are the benefits of pairing Observables with async/await for asynchronous operations?

Utilizing Angular 2 common HTTP that returns an Observable presents a challenge with nested Observable calls causing code complexity: this.serviceA.get().subscribe((res1: any) => { this.serviceB.get(res1).subscribe((res2: any) => { this.se ...

Is it necessary for the Angular route URL to match the Node Express route in order to communicate with the backend?

Angular: I have a question regarding the URLs in my Angular route and backend. In Angular, the URL is '/auth/login', while on the backend it's just '/login'. Surprisingly, everything works, but I'm curious as to how the fronte ...

I prefer not to have the entire URL visible to me

function updateDate(day, month, year) { month += ""; if (month.length <= 1) month = "0" + month; document.location.href = "<?php $_SERVER['PHP_SELF'];?>?page=events&day=" + day + "&month=" + m ...

Can object methods be called using inline event attributes in an HTML tag?

Exploring the depths of core JavaScript has been my latest obsession. It's fascinating how we can easily trigger functions within the global context using events like this. HTML <span class="name" onclick="clicked()">Name</span> JavaSc ...

Obtaining information from a intricate string input

{JSON.stringify(walletData.transactions, null, 2)} My goal is to extract backend data and display it as a table. The response has been converted into an array as shown below. [ { "date": "Nov 07, 2023", "description" ...

Tips for effectively using the parseInt function to access and verify a span element from inside a chrome extension

Trying to utilize parseInt to ascertain if a span element is greater than or equal to 1 within my Google Chrome Extension. Attempting to monitor this "0" for changes and trigger a specific URL upon change - Refer to the Image View of the "inspect" option ...