how to pass data to a php function through url ajax?

3

People try to give me strength here, I've already looked and I do not find an answer that suits me.

Come on!

I'm working with classes in php, I would like to pass data from a form via ajax. But I have doubts on running the URL, I do not know how it will stay.

$.ajax({
     type:'post',
     url:'DUVIDAAAA',
     ajax:'1',
     success: function (data){
          alert(data)
     }
});

In my url I need to get into my PHP class! but if I put a direct path it enters but the error because the instantiated class was not requested.

I call my classes with an autoload.

    
asked by anonymous 24.01.2016 / 18:12

1 answer

5

I know the question is old and you should have realized what you need to do, but in case someone comes here and wants to know an answer, follow mine.

javascript code fragment using jquery ajax:

    $.ajax({
              type: 'POST',
              url: 'test.php',
              data: {

                  variavel1: 'algumvalor',
                  variavel2: 'outrovalor',
              },
              success: function(data) 
              {
                alert(data);
              }
            });     

On the test.php page:

<?php

//Essa classe abaixo deve ficar em outro arquivo e ser chamada nessa página

class Teste
{
    function exemplo($a, $b)
    {
        // Faz um processamento qualquer com os parâmetros informados e dá um retorno
        return 'O valor de A é ' . $a . ' e o valor de B é '. $b;
    }
}


$var1 = $_POST["variavel1"];
$var2 = $_POST["variavel2"];

//Instancia sua classe e passa as variáveis pra algum método ou
// no construtor se esse aceitar parâmetros

$teste = new Teste();

$retorno = $teste->exemplo($var1, $var2);

echo $retorno; // Isso irá voltar na chamada ajax e o alert do javascript irá exibir na tela 
    
28.12.2016 / 18:37