Why is my `$http` data not being sent in Angular JS?

Within my controller, I am initiating an http request as shown below:

var postData = { action: 'getTasksByProjectSlug', slug: 'inbox' }

$http({
    url: 'http://localhost/toodloo/api/kernel.php',
    method: 'POST',
    data: postData,
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).success(function( data, status, headers, config ){
    console.log( data );
}).error(function( data, status, headers, config ) {
    console.log( status );
});

Furthermore, in the file kernel.php, the following snippet exists:

class Kernel
{
    function __construct( $requestData )
    {
        if ( ( isset( $requestData ) === false ) || empty( $requestData ) ) {
            die( 'No data received!' );
        }

        $this->findRoute( $requestData );
    }

    public function findRoute( $requestData ) {
        ...
        } else if ( ( $requestData['action'] === 'getTasksByProjectSlug' ) && isset( $requestData['slug'] ) ) {
            $this->getTasksByProjectSlug( $requestData['slug'] );
        } else {
        ...
    }

    public function getTasksByProjectSlug( $slug ) {
        $project = new Project;
        $tasks = $project->getTasksByProjectSlug( $slug );

        $json = json_encode( $tasks );
        echo $json;

        return $json;
    }
}

$kernel = new Kernel( $_POST );

The issue at hand is that when console.log( data ); within the success section of the $http call only logs 'No data received'. This indicates that the API responds with this message when the condition

( isset( $_POST ) === false ) || empty( $_POST ) )
is met. Therefore, it seems like the server is receiving the request but not the associated data
var postData = { action: 'getTasksByProjectSlug', slug: 'inbox' }
.

If anyone could provide insight into what might be causing this issue or why the postData is not reaching the server side, I would greatly appreciate it.

P.S: I have attempted using data: JSON.stringify(postData) to no avail.

Answer №1

By including the code snippet below at the beginning of the Kernel class initialization, I was able to solve my issue:

$requestData = json_decode(file_get_contents('php://input'));
$requestData = (array) $requestData;

After implementing this change, the variable $requestData functioned in a similar manner to $_POST.

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

How can I safeguard my app from crashing when the initial state is set by undefined props?

What is the best way to prevent the state from crashing if props native_languages[0] does not exist? This is my attempt at protecting the app, but it still crashes when native_languages[0] does not exist: this.state = { language: props.currentDocu ...

positioning a window.confirm dialog box in the center of the screen

I'm currently facing an issue with a dialog box that I have implemented successfully. However, I can't seem to get it centered on the page: <Button variant="danger" onClick={() => { if (window.confirm('Delete character?')) handle ...

Sending an array of items to an MVC controller through an AngularJS post request

I am currently working on an action method that looks like this: [HttpPost] public ActionResult Ask(Question question) { if (ModelState.IsValid) { TempData["NewQuestion"] = question; return RedirectToAction( ...

Observing changes in Angular.js components when binding values from services to HTML

Is there a way to bind the changing HTML value from a service in my component? The value from the service is dynamic, but my component does not observe it. I simply want to display this variable as text in my component's HTML. Here is an example setu ...

Can Tescafe be used to simulate a login process?

Scenario: Testing the features of an app built with Testcafe and Vue requires being logged in, as being logged out redirects to the login page. Roles have been utilized to streamline the login process, but is there a way to simulate logging in without actu ...

Tips on positioning content beneath a fixed header or navigation bar when viewed in a web browser

Hi, I'm having an issue with creating a fixed header using HTML and CSS. When I set my header to be in a fixed position, it covers up the content below it. I want the content to be positioned under the header when the page is loaded. Additionally, I&a ...

How can I reverse the names displayed in ng-repeat when I click?

When utilizing the orderby filter in angularjs, I want to be able to sort the data only when the button is clicked. If the button is not clicked, the sorting order should not be displayed. <tr ng-repeat="tools in toolsfilter | orderBy:orderByField:reve ...

Stop users from typing inside a newly inserted element in contenteditable mode

Currently, I am developing a straightforward syntax highlighter that transforms text into DOM elements with specified classes. For example, consider the following: <div contenteditable="true"> Some text. | And some other text. </div> Assum ...

Troubleshooting issue with password validation not functioning correctly within the Joi schema in React

I am working on developing a password change form using React. Below is the code snippet of my component: import React, { Component } from "react"; import Joi from "joi-browser"; import "./Login/Login.css"; import { UAA } from ...

Updating JavaScript files generated from TypeScript in IntelliJ; encountering issues with js not being refreshed

Struggling with a puzzling issue in IntelliJ related to the automatic deployment of changes while my server is running (specifically Spring Boot). I've made sure to enable the "Build project automatically" option in my IntelliJ settings. Whenever I ...

Storing text containing < and > symbols in a PHP Database

I am facing an issue trying to save a string from my web application into the database I'm connected to. The JavaScript successfully passes the string to PHP using AJAX, but when the insertion is performed, everything after the "<" or ">" symbo ...

Looking for assistance in extracting images from Craigslist

After exhausting all my options, I've managed to retrieve postUrl, date, title, price, and location. By visiting and running the code snippet below in the console, all the images are returned successfully. However, when I attempt to access it in my c ...

Utilizing the Jquery hover feature to reveal or conceal an element

My Hover function is designed to display and hide sub menus when a person hovers on them. The issue I'm facing is that the menu disappears when I move the mouse down towards it. Can someone help me identify what I am doing wrong here? ...

What strategies can be implemented to minimize the use of if-else statements?

Is there a more efficient way to simplify this if-else statement? This code dynamically changes the picture based on integers retrieved from the database. I am looking for ways to optimize this code. if (val["soil_h"] < 21){ $("#ground").att ...

Guide on access a PDF file in Angular through a URL

I am currently working on a project that involves displaying a list of PDF files with links to their locations. However, I am facing an issue where clicking on the link opens a new tab with a blank page instead of showing the PDF file. Is there a way to do ...

Troubleshooting: AngularJS routing issue

I'm facing an issue with my AngularJS routing code. Here is the code snippet: /// <reference path="C:\Users\elwany\documents\visual studio 2015\Projects\spaapplication\spaapplication\scripts/angular.js" /& ...

I need help figuring out how to navigate between different pages in my Vue-cli app that has multiple pages configured

After following the guide on https://cli.vuejs.org/config/#pages, I successfully configured vue-cli3 to build a multiple page application. My project consists of 2 static pages, and I set up the vue.config.js file as shown below. However, when running the ...

The Blender model imported into Three.js appears to have been rendered in a lower resolution than expected

I recently brought a gltf model into my Three.js project, which was exported from Blender. The model appears perfectly rendered in , but in my Three.js project, it seems to have lower quality as depicted in these screenshots: https://ibb.co/qrqX8dF (donm ...

Is there a way to customize the color of a React component from a different source?

I am currently utilizing a React component library called vertical-timeline-component-react. <Fragment> <Timeline> <Content> <ContentYear startMonth="12" monthType="t ...

What is the best way to create a tree structure using JavaScript with nodes that contain two arrays nested within an array?

Hey there, I don't have much experience with Javascript (I'm more familiar with C programming) but I need to create a tree structure where each node contains two arrays inside another array. Here are some C structures that might help: struc ...