Insert array from ajax into mysql database

2

I have this ajax that shows the items chosen in the " checkbox " of the form.

$(document).ready(function(){  
      $('#submit').click(function(){  
           var languages = [];  
           $('.get_value').each(function(){  
                if($(this).is(":checked"))  
                {  
                     languages.push($(this).val());  
                }  
           });  
           languages = languages.toString();  
           $.ajax({  
                url:"form_cadastro.php",  
                method:"POST",  
                data:{languages:languages},  
                success:function(data){  
                     $('#result').html(data);  
                }  
           });  
      });  
 });

Html

<input type="checkbox" value="1"   class="get_value" name="redes_sociais">
<input type="checkbox" value="1"  class="get_value" name="site">
<input type="checkbox"  value="1" class="get_value" name="endereco">

<button type="submit" id="submit" class="btn btn-primary">Cadastrar</button>

PHP

if(isset($_POST["languages"]))  
 {  

      echo $_POST["languages"];  
 }  

My question is how can I enter the values of each input in the mysql database?

Mysql Structure

$sql = "INSERT INTO planos (redes_sociais, site, endereco) VALUES

('".$_POST['redes_sociais']."', '".$_POST['site']."',".$_POST['endereco']."')";
    
asked by anonymous 17.05.2018 / 22:11

1 answer

3

Basically the way you treat in JS is wrong.

Your code

$(document).ready(function(){  
      $('#submit').click(function(){  
           var languages = [];  
           $('.get_value').each(function(){  
                if($(this).is(":checked"))  
                {  
                     languages.push($(this).val());  
                }  
           });  
           languages = languages.toString();  
           $.ajax({  
                url:"form_cadastro.php",  
                method:"POST",  
                data:{languages:languages},  
                success:function(data){  
                     $('#result').html(data);  
                }  
           });  
      });  
 });

New code

$(document).ready(function(){  
      $('#submit').click(function(){  
           $.ajax({  
                url:"form_cadastro.php",  
                method:"POST",  
                data:$("input").serialize(),  
                success:function(data){  
                     $('#result').html(data);  
                }  
           });  
      });  
 });

So you can treat in PHP as $_POST["atributo"]

redes_sociais=1&site=1&endereco=1

You can change $("input").serialize() by $(this).serialize()

    
17.05.2018 / 22:29