Using axios to pass parameters in a post request

In my webpack project, I am currently using vue-resource for ajax calls. Everything works perfectly with "get" calls, but when I try a post request, my PHP file does not receive any parameters. Even when I use var_dump($_POST), it just gives me an empty array. Here is the basic code snippet I am working with:

let data = {req: 'req_tipe', ch: 001 };
this.$http.post('compute.php', data).then(response => {
    // handle response if successful             
    },
    response => {
    // deal with errors
    });

I can't seem to figure out what I might be missing.

UPDATE: I tried the same approach with axios and vue-axios, but I still face the issue of missing post parameters:

let data = {req: 'req_tipe', ch: 001 };
this.axios.post('compute.php', data).then(response => {
    // handle response if successful            
    },
    response => {
    // deal with errors
    });

Answer №1

Perhaps you could consider making the following adjustments:

let formData = new FormData();
formData.append('request','type of request');
formData.append('channel','001');
this.axios.post('compute.php', formData).then(res => {
//handle response if successful             
},
res => {
//handle error
})

Give it a shot, or check out issue 318 for more details.

Answer №2

The issue arises from sending a POST request with the Content-Type "application/json" in Axios, which is the default behavior when an object is sent as data.

PHPS $_POST functionality only works if the request is sent with the content type application/x-www-form-urlencoded and the data is formatted as a query string.

If using a library like qs, the code snippet below should be effective:

var qs = require('qs');
axios.post('/foo', qs.stringify({ 'bar': 123 });

Axios will automatically use the appropriate content type when the input data is formatted as a query string.

Alternatively, you can still send JSON data but would need to adjust the PHP backend code as follows:

$data = json_decode(file_get_contents('php://input'), true);
print_r($data);

Some frameworks such as Symfony are able to handle this conversion seamlessly.

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

Can you target an 'input' field that is within a component conditionally rendered using 'v-if'?

Imagine this vue.js template code: <div v-if="y===0"> <input ref="textbox">{{textbox}}</input> </div> In the scenario where y is data retrieved asynchronously, Is there a way to direct focus to the 'input' element onc ...

Ways to retrieve a concealed DOM element from a background window

I have been struggling to display a button that is located in the background window using the jQuery code below, but unfortunately it's not functioning as expected. On my webpage, I have a hidden button that should only be visible when a user adds a ...

Another network request within the ng-repeat loop

My Angular application needs to call web services from two different URLs. The first URL abc.com/student/3 provides a list of students, while the second URL abc.com/parent/idofStudent3 gives the parent's first name when passed the student ID. I have ...

Why is ng-change not functioning properly, especially in conjunction with the Select element?

HTML <select ng-model="selectedName" ng-change="retrieveSelectedClass()" ng-options="(item.name||item) group by item.groupName for item in names" class="code-helper" id="code-helperId"> <option value="">Select Option</op ...

Using VueJS and Jest: A guide to testing and spying on methods triggered by watchers

Here is a snippet of code showcasing VueJs components. It includes a watcher and a method implementation. computed: { ...mapGetters({ resourceLinks: `tools/${storeGetters.resourceLinks}`, }), }, m ...

Exploring the connection between two MongoDB collections

I currently have two collections in my MongoDB database: Category and Book Here is the category.js code: var mongoose = require("mongoose"); var Schema = mongoose.Schema; var categoryModel = new Schema({ catName: String, menuKey: String }); module.ex ...

I keep receiving multiple header errors from ExpressJS even though I am positive that I am only sending a single header

Can someone please help with the issue I'm facing in the code below: router.put("/:_id", async (req: Request, res: Response) => { try { // Create the updated artist variable const artist: IArtist = req.body; const updatedArt ...

Utilizing Chessboard Positions in an if-else Statement with the Chessboard.js Library

I have been attempting to develop a function that utilizes an if-statement to verify whether a chessboard is positioned in a specific arrangement (the one I am using as the starting position) with the assistance of the chessboard.js library I experimented ...

What techniques can I employ in Angular to develop engaging widgets using plain HTML, without any Angular-specific elements?

I am currently developing a cutting-edge Angular application that serves as a training platform to offer online courses to users. Each course is essentially a set of "slides," which are HTML partials through which the user can navigate in order. These sli ...

The history.push function seems to be leading me astray, not bringing me back

Issue with History.Push in Register Component App function App() { const logoutHandler = () =>{ localStorage.removeItem("authToken"); history.push("/") } const [loading, setLoading]= React.useState(true) useEffect(()=>{ ...

Encountered a Next-Auth Error: Unable to fetch data, TypeError: fetch failed within

I've been struggling with a unique issue that I haven't found a solution for in any other forum. My Configuration NextJS: v13.0.3 NextAuth: v4.16.4 npm: v8.19.2 node: v18.12.1 When the Issue Arises This particular error only occurs in the pr ...

Using Angular's async, you can retrieve a value returned by a promise

Within the library I am currently utilizing, there is a method called getToken which can be seen in the following example: getApplicationToken() { window.FirebasePlugin.getToken(function(token) { console.log('Received FCM token: ' + to ...

The Dysfunction of JQuery UI 1.12.1 Autocomplete

I am encountering some challenges with implementing JQuery UI. The version of JQuery UI I am using is 1.12.1, the latest one available. I have downloaded the autocomplete feature along with all other necessary widgets. In my project, I have placed jquery ...

Placing a component within a .jsx file instead of utilizing a .css file for positioning

Seeking a way to position a component within a .jsx-file, rather than a .css-file, to accommodate multiple instances of the same component performing various tasks on different parts of the page. Avoiding duplication of files with minor CSS class changes, ...

The presence of decimal values within an AJAX URL

Struggling to pass decimal values in an AJAX request to a server-side endpoint. Everything runs smoothly except when trying to include a decimal value in the URL. The "." character is recognized as reserved within the URL schema, causing a 404 error. Seeki ...

BroccoliMergeTrees function encountered an unexpected data type while attempting to merge trees: TreeMerger (lint) was expecting a Broccoli node, but received an [object

Since switching to Ubuntu 18.04, I've been trying to set up my Ember development environment but have encountered an issue. While my ember project works fine on Windows, I'm getting the error "BroccoliMergeTrees (TreeMerger (lint)): Expected Broc ...

Challenges with AJAX and $_SESSION in WooCommerce plugin

I am currently in the process of creating a plugin that will enhance a WooCommerce order by adding custom data to it. Basically, what I have done is set up a specific product page to load when a custom button is clicked, passing along a URL variable (& ...

I am utilizing jQuery's AJAX function with a datatype of HTML to extract a specific portion of the incoming data

This is the JavaScript function I am working with: function getCountryRegions() { var postData = "id="+$("#selectedCountryId").val(); $.ajax({ url:"/region", data: postData, dataType:"html", type:"POST", ...

Code for refreshing content using AJAX

I'm looking for AJAX code to set a value in a session. For instance: $_SESSION['verif_code'] I want to generate a random number and assign it to this session. I need some AJAX code to refresh this random number function and set the value ...

Using Javascript to trigger form submission using arrow keys

There are four forms displayed on a single page, and I want each form to be submitted based on the arrow key that is pressed. <form name='go_north' action='' method='post'> <input type='hidden' name=' ...