I would like to send data to a php file from my Vue application to eventually save the data in a JSON file. If I understand it right, I can use JQuery/Ajax to do so as in any other non-vue application:
methods: { postData() {
$.ajax({
url: 'http://localhost:8080/test.php',
type: 'POST',
data: {
data: {name: "test", age: "test"}
},
complete: function(data, status) {
if (status == 'success') {
console.log('saved!');
} else {
console.log('Error has been occurred');
}
}
});
}
},
I placed the test.php file in the public folder:
<?php print_r($_POST); ?>
If I open http://localhost:8080/test.php, my browser does download the file. However, my vue app returns http://localhost:8080/test.php 404 (Not Found) in the console.
Where do I need to place the php file? Can this work at all? Grateful for any hints!
Edit: I served the file from another port. In my Vue app, I execute this code in the mounted hook:
mounted() {
$.ajax({
url: 'http://localhost:8888/test.php',
dataType: 'jsonp',
type: 'post',
data: '{ "name":"test", "age":30, "city":"test" }',
success: function( data ){
console.log(data)
},
error: function(errorThrown){
console.error(
errorThrown
);
}
});
}
This throws a 200 error in the console. My file test.php simply contains the following line:
<?php
echo($_POST);
?>
If I open it in my browser, it says Array:
test.php screenshot