Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

axios post server does not receive data from browser

Tags:

axios

I am using axios.post but the server does not seem to receive the post-data.

This is what I have:

var baseURL = "http://localhost:8888/dbRouting.php";
var body = {
  function: 'foo',
  id: 'bar',
}

axios.post(baseURL, body)
.then((response) => { console.log( "Data Loaded AXIOS: " + response.data ); })
.catch(function (error) {console.log(error);});

// Data Loaded AXIOS: array(0) {
// }

This jQuery post to the same file, on the other hand, works:

$.post( baseURL, body )
  .done(function( data ) {
     console.log( "Data Loaded JQUERY: " + data );
  });

//Data Loaded JQUERY: array(2) {
//["function"]=>
//string(3) "foo"
//["id"]=>
//string(3) "bar"
//}

The server file (dbRouting.php) is just:

<?php
var_dump($_POST);
?>

Any ideas what might be going on?

like image 276
gondolfier Avatar asked Feb 18 '17 21:02

gondolfier


1 Answers

This is my way of allowing the back-end which is php to process it via $_POST. This is part of my code in vue inside method section.

Assuming you are post it to a post_url and you have an object, var myObject:

var myObject = {
  property: value,
  property1: value1,
  property2: value2
}

Inside my vue, method section:

 updateForm: function( myObject ){
            var post_url = (your post url);

            axios.post(post_url, makePostReady( myObject ) )
            .then(function (response) {
                console.log(response);
             })
            .catch(function (error) {
                console.log(error);
             });
      }

Then above(before axios post call) or make it a global function. I created below function to turn any object I want to send as post using axios so that it will form

property=value&poperty1=value1&property2=value2......

Below is the function:

function makePostReady( object )
{
    var sentence = "";
    for (var key in object) {
        sentenceAdd = key + '=' + object[key] + '&';
        sentence = sentence + sentenceAdd;
    }
    //console.log( 'sentence: ' + sentence );
    return sentence;
}

After that you can var_dump( $_POST ) at your post_url to check if everything is fine. Then you can process the data as usual.

Hopefully it helps

Below is some picture to help understanding better

enter image description here

enter image description here

like image 176
Apit John Ismail Avatar answered Oct 01 '22 12:10

Apit John Ismail