Call PHP function in jQuery

0

I'm starting my PHP studies and I have to do a registration form, however, it's very bad to do data validation via PHP, so I'm using jQuery for this.

However, I need to call the PHP function inside jQuery to just get data that has already been validated. How can I do this?

    
asked by anonymous 25.09.2015 / 22:10

1 answer

4

Request via AJAX with jQuery.

We are accessing a file http://exemplo.com/funcoes.php , assuming it is in the same directory, it is possible to access links. A very simple example, this is the HTML file:

   <script>
      $( "form" ).submit(function( event ) {
              event.preventDefault();
                    $.ajax({
                    url : 'funcoes.php',//url para acessar o arquivo
                    data: {id : 10},//parametros para a funcao
                    type : 'post',//PROTOCOLO DE ENVIO PODE SER GET/POST
                    dataType : 'json',//TIPO DO RETORNO JSON/TEXTO 
                    success : function(data){//DATA É O VALOR RETORNADO
                        alert(data.valor);//VALOR INDICE DO ARRAY/JSON
                    },
        });

});

</script>

and the file funcoes.php

<?php
    //funcao retornando um json
    function teste(){
      echo json_encode(array('valor' => $_POST['id']));
    }

    //executando a funcao
    teste();
?>
    
25.09.2015 / 23:11