Calling distinct functions via Ajax with Jquery in PHP

1

I have the following example:

My HTML file has this snippet of code:

<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>

I also have a file called funcoes.php with the following content:

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

    function teste2(){
      echo json_encode(array('valor' => $_POST['id']));
    }
?>

What I would like to know is: How do I access the test1 (or test2) function? What do I have to pass as "parameter" in my HTML file so that it knows which of these two functions I want to execute?

    
asked by anonymous 08.06.2017 / 18:16

1 answer

0

Ideally, even if you use REST API to gain direct access to the function you want, I recommend that you read through it. If there is a possibility too, it would be interesting to use a PHP framework if your project supports this kind of feature.

Now if you meet your need you could pass an additional parameter in your ajax call:

$.ajax({
    url : 'funcoes.php',
    data: {id : 10, acessar: 'teste'},
    type : 'post',
    dataType : 'json',
    success : function(data){
        alert(data['valor']);
    }
});

And in the file funcoes.php would be:

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

    function teste2(){
      echo json_encode(array('valor' => $_POST['id']));
    }

    if($_POST['acessar'] == 'teste'){
        teste();
    } else if($_POST['acessar'] == 'teste2') {
        teste2();
    }
?>

Looking at your environment would be such an approach.

    
08.06.2017 / 19:37