Problem with axes vue and php: Undefined Index

1

I have a very simple code, I'm using PHP VueJs and axios for Ajax requests

I have a button that sends data by ajax to a php file per post but it does not recognize post data, that I infer from this error:

  

Notice: Undefined index: email in   /opt/lampp/htdocs/projects/winecommunity/php/index.php on line 2

HTML

<button @click="sendEmail">Enviar </button>
<p> {{{res}}} </p>

<script src="js/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

<script src="js/index.js"></script>

THE php

echo $_POST['email'];

and the js

new Vue({
    el: 'body',
    data: {
        email:'[email protected]',
        res:'tu email'
    },
    methods: {
        sendEmail: function (){
            var vm = this;
            axios.post('php/index.php', {
                email:vm.email,
            })
            .then(function (response) {
                vm.res = response.data
            })
            .catch(function (error) {
            console.log(error);
            });
        }
    }

})

Any idea what I need for php to return the email to me?

    
asked by Emiliano Pamont 16.08.2018 в 08:01
source

1 answer

0

First of all for your code, it is recommended that the root element is not the <body> tag, it even throws an error in the console if so, so you must wrap the content in a parent or root element.

Then to print the values the double keys are used and not 3 {{ valor }}

For data to work, you must add them to a FormData , I would recommend having all the data that will be modified or v-model in a parent object (postData for the example) for later generate the shipment.

HTML

<div id="app">
    <button @click="sendEmail">Enviar </button>
    <p> {{res}} </p>
</div>

VUEJs

new Vue({
    el: '#app',
    data: {
          //Objeto postData, se pueden añadir más propiedades
        postData :  {email:'[email protected]'},
        res:'tu email'
    },
    methods: {
        sendEmail: function (){
            var vm = this;
            axios.post('php/index.php',this.createdFormData())
            .then(function (response) {
                vm.res = response.data
            })
            .catch(function (error) {
                console.log(error);
            });
        },
        // función para generar el formData a partir del objeto postData
         createdFormData : function (){
                    var formDa = new FormData();
                for(var key in this.postData){
                    formDa.append(key, this.postData[key]);
                }
                return formDa;
            }
    }
})
    
answered by 16.08.2018 / 08:23
source