Pass javascript array to php using ajax

Asked

Viewed 2,103 times

2

Good morning, everyone. I’m here with a question in a php/jquery work and I wanted you to help me

In a javascript file I have this code here

var categorias;
var categoria;
var array = [];




$(document).ready(function(){
	$.getJSON("Categorias.php", function(dados){
		categorias = dados;
		$.each(categorias, function(index, categoria){
                    
                   // var a = array.indexOf(categoria);
                    //if(a==-1){
                          array.push(categoria);
                      //}
                      
		});
                filtrar();
	}); 
});


function filtrar(){
            
            var variavel;
            for(var i = 0; i < array.length; i++){
                variavel = "<input type='checkbox' name='categorias' checked value='"+array[i].categoria+"' class='opcoes'/>"+array[i].categoria+"<br />";
                $("#filtro").append(variavel);
            }
            $("#ver").click(function(){
                array=[];
                $(".opcoes").each(function(index, check){
                   if($(check).prop('checked')){
                       array.push($(check).attr("value"));
                   }
                });
               alert("Você escolheu as seguintes categorias: " + array);
                });
                
                
            $("#todas").click(function(){
                array=[];
                $(".opcoes").each(function(index, check){
                   if($(check).prop('checked')){
                   }
                   else{
                       $(check).prop('checked', true);
                   }
                });
                });
                
                
            $("#remove").click(function(){
                array=[];
                
                $(".opcoes").each(function(index, check){
                   if($(check).prop('checked')){
                        $(check).prop('checked', false);
                   }
                });
                });
        }

and now I wanted to pass the variable array to my php page only that I’m not getting

function(array)
   {
      $.ajax({
	  type: "POST",
      url: "load_post.php",
	  data: {categoria : array},
      success: function(dados){
          alert(dados);
	  $('#load_post').html(dados);
      }
    });
      
   }

in my variable array I have the name of the categories, so I wanted this function to receive this array, turn it into string so that I could later use it in a query to fetch the information of that category...

in load_post.php I have this

<?php


$ligacao = mysqli_connect("localhost", "root", "", "publicidades");
                        if (mysqli_connect_errno()) {
                            echo "Erro na liga��o MySQL: " . mysqli_connect_error();
                        }
                        
                        
                        $sql_img = "SELECT * FROM publicidade WHERE id_publicidade  > 0 and estado = 1 AND categoria in ('".$_POST['categoria']."') ORDER BY visualizacoes DESC";
                        $imagem = mysqli_query($ligacao, $sql_img);
                        $objeto = mysqli_fetch_assoc($imagem);
                        $attempts = $objeto["descricao"];
                        $estado = $objeto["estado"];
                        
                        $visu = "SELECT visualizacoes FROM publicidade WHERE id_publicidade ='".$objeto["id_publicidade"]."'";
                        $obj = mysqli_query($ligacao, $visu);
                        $res = mysqli_fetch_assoc($obj);
                        $final = $res["visualizacoes"];
                        
                        
                        $num_post = mysqli_num_rows($imagem);


if( $num_post ) {
    if($estado){
                if($final>0){
                echo "<img src=\"$attempts\" alt=\"Não deu!!\">";
                $alterar = "UPDATE publicidade SET visualizacoes  = visualizacoes-1 WHERE descricao = '$attempts'";
                $alteracao =  mysqli_query($ligacao, $alterar);
                }else{
                    echo 'O seu tempo de antena acabou';
                }
                }   
} else {
   echo '<p>Já não existem mais imagens.</p>';
}

?>

Here I wanted to use the variable that is enough to enter it in the query

Category.php

<?php

$ligacao = mysqli_connect("localhost","root","","publicidades");
   if (mysqli_connect_errno())
   {
	  echo "Erro na liga??o MySQL: " . mysqli_connect_error();
   }


$sql = "select distinct categoria from publicidade";

   $resultado = mysqli_query($ligacao, $sql);
   
$array_publicidades = array();

   while( ($registo = mysqli_fetch_assoc($resultado)) !=null)
   {
		$array_registo['categoria'] = $registo['categoria'];
		
                array_push($array_publicidades,$array_registo);
   }    
   
   echo json_encode($array_publicidades);
?>

Here I create a json with various advertising categories

  • 1

    What comes to PHP when you do var_dump($_POST['categoria']);?

  • Undefined index: categoria in C: xampp htdocs RAFA load_post.php on line 39 NULL

  • You can put the code of this load_post.php?

  • I already put the code

  • I think your doubt would be the same here. http://answall.com/questions/53896/enviar-objeto-javascript-para-php/53922#53922

  • Which file code Categoria.php?

  • I’ve updated that part, it’s at the end

  • @Filipe: nesse load_post.php where you put var_dump($_POST['categoria']);? I don’t see it in the code? and what line is that line 39 in the code that you showed?

Show 3 more comments

1 answer

0


When I used PHP and needed this I was describing a string with all the positions of the array separated with 2 Pipes ex: campoa||campob||campoc|etc... After the js side I would split it, like var.split("||"). this way makes the array again in js and this way can manipulate the data.

  • 1

    Exactly, I was able to do that. I assembled a string with all the data and I was able to handle it. Thanks

  • good, young! success ai in php!

Browser other questions tagged

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