Error when passing Ajax parameters to function in PHP class

Asked

Viewed 247 times

0

It’s the first time I try to pass parameters from ajax to my function that is in a class in php, so I ask, why isn’t it working? searching the forum I saw that could put

data: {
var1 = 'var1',
var2 = 'var2',

},

or go through the URL as I am doing, but even then I did not succeed.. php says that the variables do not exist, below the code

Ajax - Code has been fixed - Here it works!

  /* Função de Busca - Galeria de Imagens AJAX */
function buscar($tamanho){
    var pasta = $('#pasta').val();  
    // utilizando o split para quebrar o diretorio e receber somente o nome da pasta
    var dirimg = pasta.split("/galeriaimg/");
    var tamanho = $tamanho; 
    var data = {
      tamanho: tamanho,
      diretorio: dirimg[1], 

    }

    $.ajax({
        type: 'POST',
        dataType: 'json',  
         url: '/wpauditoria/painel-admin/include/galeriaimg/galeria.php',      
        //  url: '/wpauditoria/inc/class/Galeriaimg_crud.php?diretorio='+dirimg+'/&tam='+tamanho,  
            data:data,
            success: function(result){ 

               $.each(result, function(key, value){
                    var container = '<div class="col-md-4" id="col-'+key+'">';
                    container +=        '<div class="img-wrap">';
                    container +=            '<img src="/wpauditoria/images/'+tamanho+'/galeriaimg/'+dirimg[1]+'/'+value+'" class="img-return" alt="galeria" "/>';    
                    container +=            '<a href="#" class="btn btn-default btn-sm delete" onclick="excluir('+key+')"><i class="fa fa-trash"></i></a>'; 
                    container +=         '</div>';    

                    container +=         '<input type="hidden" name="imagemgaleria['+key+'][endereco]" value="/galeriaimg/'+dirimg[1]+'/'+value+'" />';    
                    container +=         '<input type="text" placeholder="Título" name="imagemgaleria['+key+'][titulo]" class="form-control inputgaleria" />';   
                    container +=         '<textarea name="imagemgaleria['+key+'][descricao]" placeholder="Descricao" class="form-control inputgaleria" ></textarea>';   
                    container +=    '</div>';   

                    $('#galeriaimg').append(container);
               });

               /* monstrando os botoes que foram ocultados.*/
               $('.oculto').show();
              $('.group').remove();
         }
    });
}

Class :

Class Galeriaimg_crud {

    public function __construct() {
     //
    }

        ///////////////////////////////// FUNÇÃO PARA TRATAR OS ARQUIVOS DO DIRETORIO///////////////////////
    // Função que verifica que verifica se todos os retornos são arquivos e retira os invalidos

    function verifica($param){
        if (!is_dir($param)){
            return $param;
        }
    }

///////////////////////////////// FUNÇÃO PARA OBTER OS ARQUIVOS DO DIRETORIO///////////////////////
        public function arquivos(){

                  $diretorio = $_POST["diretorio"];
                  $tam = $_POST["tamanho"];                    

                    // repassando o caminho para a variavel
                    $dir = $_SERVER['DOCUMENT_ROOT']."/wpauditoria/images/$tam/galeriaimg/$diretorio";

                    // escaneando o diretorio através do scandir
                    $files = scandir($dir);                    

                    // realizando um filtro no retorno dos dados do diretorio
                    $result = array_filter($files, 'Galeriaimg_crud::verifica');                             

                    // codificando o retorno através do json_encode  
                    // retorno do conteudo
                    return json_encode($result);
            }

Console Print inserir a descrição da imagem aqui

To Debug I am calling the class via a button as follows. The Code was changed to Get instead of post but it still didn’t work (I updated it here...)

<?php 

if (isset($_GET['cadastrar'])){

  $galeriaimg_crud = new Galeriaimg_crud();

  $result = $galeriaimg_crud->arquivos();
  var_dump($result);

}

?>
  • What is happening is that you are passing the parameters via GET but the method of ajax is defined as POST this will never work.

3 answers

1


Then the javascript object has s erroryntax it should be like this:

var data = {
    chave1: 'valor1',
    chave2: 'valor2'
}

To pass this object through ajax follow this small example

$.ajax({
 type: "POST",
 url: "MinhaPagina.php",
 data: data, 
 success: function(data) {
      alert('sucesso!');
 },
 error: function(){
     alert('ocorreu um erro!');
 }
});

In php you can capture like this:

echo $_POST['chave1']; // valor1
echo $_POST['chave2']; // valor2
  • thank you! I did this way that you spoke and I ended up discovering the problem, in fact I was calling in the url of ajax the class directly without instantiating the method so it didn’t work,(for test I was trying to instantiate the function through a button... and then it didn’t work! ). I created a file only to instantiate this class and it worked! but then I got a question, when using ajax I always have to create a file just to instantiate this class and call the method? or I can do it another way?

0

Put this at the beginning of your file function()

$diretorio = $_GET["diretorio"];
$tamanho = $_GET["tam"]; 

In the place that this:

$diretorio = $_POST["dirimg"];
$tamanho = $_POST["tam"];

In ajax change the type to get

  • @Sergio, I had already done this, but I keep getting error saying that the variable is invalid

  • On the console.log(size, dirimg) appears what ?

  • in the preview nothing appears.. is empty, now if I go in header and in query string Parameters ai returns correctly, but for test I put a button, and call the class but it does not work.. now if I put $_POST['pasta'] then I only get the return of this variable.. the others don’t. (I updated the post with the console screen).

  • I have no experience with POO but I think because I am inside a class you need to instantiate the class and call the file(); method If you put the function code files() in a structured way, without being in a class, it would have to work.

  • Take a look at this link https://stackoverflow.com/questions/23068607/ajax-connect-to-php-oop-webservice Vc will need to instantiate your class in php. $gallery = new Galeriaimg_crud(); echo $gallery ->archives();

  • Blz .. really should work. but then q get variable error.qdo I call the class and the method by button was the way q found to debug, because the console is not showing any errors

Show 2 more comments

0

Problem Solved! Thank you to everyone involved! With your help I was able to identify where my mistake was...

to test I was instantiating the class in a button so that I could not receive the return of the variable php said that it did not exist.

Good to solve, I changed the url of Ajax, calling a file I created named gallery.php, in it I instated the class along with the method and with the return, the problem was solved. I updated the Code in the first post to be correct in case anyone needs it in the future

php gallery.

<?php


      // instanciando a Classe
      $galeriaimg_crud = new Galeriaimg_crud();
      // recebendo o retorno do metodo Arquivos

      $result = $galeriaimg_crud->arquivos();

      // exibindo o retorno
      echo $result;

 ?>

Browser other questions tagged

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