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

Unlock the power of AJAX in your WordPress site

I've been exploring the realm of Javascript and AJAX lately. I feel like I'm so close to getting it right, but there's something off with how I'm integrating WordPress ajax functions. I've spent a lot of time going through the docu ...

User authentication using .pre save process

I have an API that accepts users posted as JSON data. I want to validate specific fields only if they exist within the JSON object. For example, a user object could contain: { "email" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" dat ...

Troubleshooting the Angular Fullstack + CORS issue: "XMLHttpRequest cannot load

I've been wracking my brain trying to figure this out. Utilizing the yeoman generator angular-fullstack, I created a simple Angular app on a NodeJS server with Express. The app makes remote service calls, so there are no API server side calls within ...

Vanishing Ionic Passwords

I attempted to achieve a similar result: https://i.stack.imgur.com/pG9ya.png by utilizing the following code: <div class="row" id="passwordRow"> <div class=".col-80"> <input type="password" id="password" placeholder=" ...

Change a camelCase string to ALL_CAPS while adding underscores in JavaScript

Currently, I'm dealing with a situation where I have a list of variables stored in a file that I need to convert into all capital letters and separate them with underscores using JavaScript. The variable pattern looks something like this: AwsKey Aw ...

Storing dropdown selection in database using Laravel form and AJAX

In my controller (FocalController.php), I have generated a dropdown list using the following code: $focalData = DB::table('role_users')->orderBy('users.id','DESC') ->leftJoin('users', function($j ...

The percentage height setting for a div is not functioning properly, but setting the height in pixels or viewport

Within a dialog box body, I am attempting to display a table and have applied a CSS class to the wrapping div. When specifying the height in pixels or viewport height units, it works as expected. However, when using a percentage like 50%, the height of the ...

Using jQuery to append text after multiple element values

I currently have price span tags displayed on my website: <div> <span class="priceTitle">10.00</span> </div> <div> <span class="priceTitle">15.00</span> </div> <div> <span class="priceTitle">20.0 ...

Having trouble getting the default NextJS template to work with TailwindCSS

Sysinfo: > Windows 11 > Node: v18.16.0 > Next: 13.4.13 > Tested Browser: Firefox, Chrome. Step to Reproduce To recreate the issue, I created a NextJS project using the command npx create-next-app tezz with specific options selected: Would you ...

Error: Attempting to update the value of 'ordersToDisplay' before it has been initialized in a re-render of React. This results in an Uncaught ReferenceError

Trying to dynamically update the document title to include the order number by clicking a button to display different numbers of orders from an array on the screen. The process involves importing a JSON file, filtering it based on user input, calculating ...

Should you make multiple API calls or just one?

Currently in the process of developing an application that combines NodeJS and VueJs. I have created an API endpoint that provides all the necessary data. For instance, it may include The top Football Team The bottom Football Team The team with the most ...

Executing multiple Ajax requests on CodeIgniter 3 from two separate pages

I am facing a critical need for a code review and unfortunately, I am unsure of where else to seek assistance besides here. Let me outline my current task: I am working on a user profile page that is designed to showcase users' comments. Users have t ...

When attempting to install an npm package from a local directory, I encountered a 404 Not Found error, despite the package existing in the node_modules directory

After installing an npm package from a local directory, I noticed that the package was successfully installed and is located in the node_modules directory. However, upon trying to access the package, I encountered the following error: 404 not found I a ...

Leveraging JavaScript for Validating Radio Buttons

I've been following a tutorial guide on this specific website , but I'm encountering some difficulties despite following the exact steps outlined. Can someone provide guidance? Here is what I have done: <html> <script> fu ...

What is the manual way to activate Ratchet's push feature?

I am facing an issue with a link that triggers a search function. Currently, the link is working as expected. However, I am having trouble getting the search to be executed by pressing the 'enter' button. Here is my code snippet: $('#sea ...

Creating a JSON body using a JavaScript function

I am looking to generate a JSON Body similar to the one shown below, but using a JavaScript function. { "events": [{ "eventNameCode": { "codeValue": "xyz api call" }, "originator": { "associateID": "XYZ", "formattedName": " ...

Switch on the warning signal using bootstrap

How can I make the alert below toggle after 2 seconds? <div class="alert alert-info"> <a href="#" class="close" data-dismiss="alert">&times;</a> Data was saved. </div> ...

Retrieve the array from the response instead of the object

I need to retrieve specific items from my database and then display them in a table. Below is the SQL query I am using: public async getAliasesListByDomain(req: Request, res: Response): Promise<void> { const { domain } = req.params; const a ...

No assets detected in sails.js

Recently, I began a new sails project using 'sails new project --linker'. Initially, everything was functioning correctly but today I encountered a problem. Every time I start the server with 'sails lift', I now receive a 404 error for ...

Tips for adjusting the width of columns automatically in exceljs

One of my challenges is to automatically adjust column width using exceljs. I want the Excel sheet to be dynamic, saving only the columns specified by the user in the request. Here is the code snippet that accomplishes this: workSheet.getRow(1).values = dt ...