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

Asked

Viewed 1,116 times

4

People try to give me a force around here, I’ve searched and I can’t find an answer that answers me.

Come on!

I am working with php classes, I would like to pass data from a form through ajax. However I have doubts in the execution of the URL, I do not know how it will look.

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

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

I call my classes with an autoload.

  • Very obscure yet. What’s the problem, specifically?

  • The url will be where POST/GET will exist. If you create cookie.php and inside it $_POST['bolacha'] the URL must be http://seu-site.com/biscoito.php.

  • URL must be the page to which you send the data...

  • I need to access my class.php file and in it access the function I want

  • @Pedrosoares in the Voce URL puts the URL that your system would have if accessing the class/method...

  • yes but my problem is so, I even pass the values to class but there it gets lost, is there a way for me to go through the URL tbm a out of already define which function that data will ? @Rafaelacioly

Show 1 more comment

1 answer

7


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

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 
  • I didn’t even remember that question anymore, but today I know exactly what to do. But even now your answer was quite complete. You can treat the code a little but that’s exactly the way. It will definitely help people starting with Ajax requests with jquery. Thank you for your reply

  • All right! Thank you, hugging. : D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.