What is the correct approach in utilizing AngularJS $http.post for PHP to update a MySQLi table?

I need assistance with updating a MySQLi table called "achievements" using PHP in an AngularJS app. The app calculates various statistics, and when a goal is achieved, I send the relevant information to a PHP script using AngularJS's "$http.post" method. My intention is for PHP to handle this information and update the corresponding table accordingly. However, despite receiving a success message from the $http.post request, the table does not actually get updated. I have double-checked and am confident that the database connection information is accurate.

Below is my AngularJS code for the "$scope.updatePhp" function using "$http.post":

$scope.updatePhp = function(table, column, value, whereColumn, whereValue) {
    $http.post(
        "update-data.php", {
            'table': table,
            'column': column,
            'value': value,
            'whereColumn': whereColumn,
            'whereValue': whereValue
        }
    );
}

Here is an alternative version of the "$scope.updatePhp" function without utilizing the ".post" shortcut:

$scope.updatePhp = function(table, column, value, whereColumn, whereValue) {

    console.log("Updating. Table: " + table + ", Column: " + column + ", Value: " + value + ", Where: " + whereColumn + ", WhereValue: " + whereValue);

    $http({
        method: 'POST',
        url: 'update-data.php',
        data: { table: table.toString(), column: column.toString(), value: value.toString(), whereColumn: whereColumn.toString(), whereValue: whereValue.toString() },
        headers: { 'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8' } 
    }).then(function successCallback(response) {
        console.log("Success.");
    }, function errorCallback(response) {
        console.log("Error.");
    });

}

Here is the content of my PHP file named "update-data.php":

<?php

    // Adding CORS header
    header("Access-Control-Allow-Origin: *");

    // Retrieve posted information in PHP
    $info = file_get_contents('php://input');

    // Connect to database and update the table
    $hostname_DB = "databaseHost";
    $database_DB = "databaseName";
    $username_DB = "databaseUser";
    $password_DB = "databasePass";
    $portnum_DB = "databasePort";
    $mysqli = mysqli_connect($hostname_DB, $username_DB, $password_DB, $database_DB, $portnum_DB ) or die(mysqli_error());

    $table = $info->table;
    $column = $info->column;
    $value = $info->value;
    $whereColumn = $info->whereColumn;
    $whereValue = $info->whereValue;

    $query = "UPDATE '$table' SET '$column' = '$value' WHERE '$whereColumn' = '$whereValue' ";
    $mysqli->query($query) or die(mysqli_error());  

?>

I am encountering an error when attempting to access the variables "table", "column", "value", etc. within the PHP script. Specifically, I receive the following notice for each variable: "PHP Notice: Trying to get property 'table' of non-object in /update-data.php on line 16". It appears that there may be an issue with how the information is being sent or retrieved, rather than with the SQL query itself.

Please provide any insight you may have into resolving this issue. Thank you in advance!

Answer №1

Avoid using the $.param() method when sending data; you can directly send the data object.

$scope.modifyPhp = function(table, column, value, whereColumn, whereValue) {

console.log("Modifying. Table: " + table + ", column: " + column + ", value: " + value + ", where: " + whereColumn + ", whereValue: " + whereValue);

$http({
    method: 'POST',
    url: 'modify-data.php',
    data: { 
        table: table.toString(),
        column: column.toString(),
        value: value.toString(),
        hereColumn: whereColumn.toString(),
        whereValue: whereValue.toString() 
    },
    headers: { 'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8' } 
}).then(function successCallback(response) {
    console.log("Success.");
}, function errorCallback(response) {
    console.log("Error.");
});

}

Answer №2

It's possible that the issue lies within the $.param() function.

        data: $.param({ table: table.toString(), column: column.toString(), value: value.toString(), whereColumn: whereColumn.toString(), whereValue: whereValue.toString() })

$.param() is a JQuery method worth investigating.

Take a look at: AngularJSParamSerializer

You can also try omitting json encoding/decoding to test its effectiveness.

EDIT (comment by replier): "In your php, attempt to

echo file_get_contents('php://input') ;
. Then, in your javascript code within the request's callback function, include the line console.log(response); to check if any data is being successfully sent."

Answer №3

I encountered a problem with the formatting of the data. Let me show you how I printed the $info variable:

{"table":"achievements","column":"Goal","value":1,"whereColumn":"id","whereValue":"1"}

The string obtained from file_get_contents('php://input') was enclosed in curly braces and had each value separated by commas. I had to remove these formatting elements.

In addition, I needed to eliminate the quotes around each key-value pair. Since I only required the values, I also removed everything before the colon (:) which represented the "key".

Ultimately, this is the (arguably unconventional) solution that worked effectively:

//PHP posted info
    $info = file_get_contents('php://input');
    $dataArr = explode(',',$data);

    $dCount = 0;
    foreach ($dataArr as $datum) {
        $newDatum = substr($datum, strpos($datum, ":") + 1);
        $newDatum = str_replace(array('}', '{', '"'), '', $newDatum);
        $dataArr[$dCount] = $newDatum;
        $dCount++;
    }

    $table = $dataArr[0];
    $column = $dataArr[1];
    $value = $dataArr[2];
    $whereColumn = $dataArr[3];
    $whereValue = $dataArr[4];

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

Navigating through a URL to grab a specific JSON object: a step-by-step guide

When I receive a json from a URL containing numerous objects, how can I extract only the slugs provided in the json below? I am open to solutions using either PHP or JavaScript. On one hand, I need to understand how to specifically retrieve the desired ob ...

How can I ensure that "echo" is only displayed once in a foreach loop while also including

Here is the JSON data I have: { "order_id":"#BCB28FB2", "salutation":"Mr", "name":"Testing Data", "cart":[ { "id":13, "name":"tes1", "tre ...

Watch for changes in a nested collection in Angular using $scope.$watch

Within my Angular application, there is a checkbox list that is dynamically generated using nested ng-repeat loops. Here is an example of the code: <div ng-repeat="type in boundaryPartners"> <div class="row"> <div class="col-xs- ...

Populating hidden fields in Javascript with mouseover event trigger - Pre-click action

Seeking a solution for another issue, I stumbled upon the capability to execute JavaScript on mouseover. Here is what I want to execute: $(document).ready(function(){ function myPayment() { var value = document.mortgagecalc.value_input.value; var rate ...

When using `$destroy` in Angular, an error may occur indicating that the element is not defined

I need to cancel the $interval event in my directive when changing routes or states in the application. I tried using this code snippet to act on the destroy event: element.on('$destroy', function() { console.log("Canceling interval"); ...

Maximizing the potential of $urlRouterProvider.otherwise in angular js

I am encountering an issue with redirecting to the login screen when there is no UABGlobalAdminId in my storage. I have tried using $urlRouterProvider.otherwise but it doesn't seem to be functioning properly. When I attempt to debug, the console does ...

In PHP, extract placeholders from a variable

I am working on a method to replace "place holders" within a variable with database information for the purpose of creating generic emails. Let's take a look at an example of the variable: $emailBody = "Dear [-first_name-] [-last_name-]"; The next ...

HTML counterpart to PHP's include for JavaScript components

I am searching for a Javascript alternative to a method I have been using in PHP. Specifically, I want to streamline the basic setup of my pages: <!DOCTYPE html> <html lang="en"> <head> <meta ch ...

Leveraging the framework's event dispatcher to trigger a domain event

When I need to trigger domain events, should I utilize the framework's specific Event Dispatcher or create my own custom Event Dispatcher that is implemented by the framework's Event Dispatcher? Despite the fact that the framework provides a robu ...

How can I make the Bootstrap navbar drop-down menu disappear automatically when a link is clicked in an Angular application?

When viewing the Bootstrap navbar on smaller screens, it appears as a panel of buttons that cover the page content. While there are many solutions for hiding this panel when clicked on, my question pertains to hiding the panel when links within the main bo ...

Jasmine spying on a standalone function that is not a method of an object

What is the best way to spy on a function that is not a method of an object? In my specific case, the function callMe is not defined on the window object - it is a dependency loaded through angular. if (X) { callMe('hello'); } ...

Interact with Excel-VBA drop down button using IE (SPAN NG-IF) in an AngularJS application

Is it possible to make a button click work with the SPAN NG-IF feature? Am I approaching this issue incorrectly? The name "Lõuna port" changes when something else is clicked in the drop-down menu. I have a list of all the names but can't figure out h ...

When implementing jQuery $.ajax with Angular, the DOM fails to update

Based on the value retrieved from an XHR call to the server, I am looking to display different content: <div class="container"> <div class="header" ng-controller="MyController"> <div ng-switch on="myScopeVar"> <d ...

Pagination does not refresh when conducting a search

HTML Code: The following HTML code displays a table with a search filter. . . <input type="search" ng-model="search.$" /> <table class="table table-striped table-bordered"> <thead> <tr> <th><a href ...

Having trouble receiving values sent through AJAX POST requests to PHP

Can anyone help me figure out why my AJAX POST method is not sending the specific section of my URL string to my PHP file? I've checked everything and can't seem to find where the issue lies. When I var_dump the POST variable in my PHP file, it s ...

Is there a way to process the output of phantom.js in PHP efficiently?

I have successfully retrieved output from a phantom.js request via the command line and it meets my expectations. Now, I am interested in invoking phantom.js from a php script and then analyzing the output for specific content. My phantom.js script appear ...

Executing a PHP file with a PDO connection in the terminal is failing to establish a connection

When running a certain PHP file in the browser, everything works perfectly fine. However, when I try to execute it in the terminal, php /opt/lampp/htdocs/xampp/site_name/update_db.php the PDO include and connection don't seem to function properl ...

There has been no change in Vue2 compatibility with Laravel 5.4

I'm currently experimenting with Vue within a Laravel project. However, I've encountered an issue where after modifying the example.vue file and adding it to the view, the changes are not reflected in the view. The code snippet below showcases th ...

Could someone help me understand the following PHP script?

Could someone please explain this condition to me? I'm having trouble understanding it. The code is functioning correctly, but I can't remember the logic I used to return the value. $chkBlock = Blocked::where("block_username", "=", Auth::user()- ...

Obtaining encrypted data in json format

Received some JSON encoded data. How do I access each of the individual elements? Here's an example: $ticket $customer $user {"ticket":{"id":"10909446","number":"152"},"customer":{"id":"3909381","fname":"","lname":"","email":"<a href="/cdn-cgi/l ...