How to insert value in mysql with PHP and Ajax

0

I have the following recipe page, which lists the ingredients:

<?php
$db->setQuery("Select * from #__ingredientes");
$tmpingredientes = $db->loadObjectList();
?>

And then I show you the list of ingredients.

I wanted to put an input and button that when submitting, it inserts a new value and already updates that list that is appearing, without updating the page, I believe with ajax, right? Something like this:

echo '
<input type="text" id="ingrediente" value="'.$ingrediente.'">
';
$db->setQuery("INSERT INTO #__ingredientes
(id, ingrediente, ordering, published)
VALUES (NULL,$ingrediente,'0','1')
");

Is the line of reasoning right or traveling?

    
asked by anonymous 23.10.2017 / 21:11

2 answers

1

This is very simple to do, let's assume your code to insert is in a single file, called inserir.php .

$db->setQuery("INSERT INTO #__ingredientes
(id, ingrediente, ordering, published)
VALUES (NULL,$ingrediente,'0','1')
")

Now, just do ajax

$.ajax({
   type: 'POST',
   url: 'inserir.php',
   data: {
      ingrediente: 'ALGUMA COISA'
   },
   success: function(data){
      $('#Lista').append('<li>'+ingrediente+'</li>')
   }
})

This way it will always insert a new item to your list without updating the page, as you did not post all your code, it was difficult to make a more complete example, but the basis is that.

    
23.10.2017 / 21:17
0

Let's break it down:

1 - This process encompasses 4 things, HTML, Javascript, PHP and Ajax.

  • HTML Will build the elements
  • Javascript will do the interaction between HTML, Ajax and PHP.
  • Ajax will interact with PHP and tell Javascript what to do.
  • PHP will think, save in the bank the value, and return something via Ajax for Javascript to work.

First, you need a input and a button :

<input type='text' name='ingrediente' class='input'>
<button class='add-ingrediente'>Adicionar</button>

Second, you need to get the value of input , by clicking on button , this we will do with jQuery (javascript facilitated):

$(document).on('click','.add-ingrediente',function(){
 //Repare que aqui nós vamos atribuir o valor do elemento ''.ingrediente'' (que é o input, a variavel JS ''ingrediente''
 var ingrediente = $('.ingrediente').val();
 //AQUI VAI A CHAMADA AJAX
});

Third, to request a PHP file that saves in BD and return the value, we will use a $.ajax method, which works as follows: NOTE: This ajax call should go inside the event that was passed over.

$.ajax({
   //Define o método que 'ingrediente' será passado para o servidor
   type: "POST",
   //Aqui deve-se apontar o arquivo da chamada
   url: "insere.php",
   //Aqui é o modo de se passar um váriavel JS para o php, 
   data: {ingrediente: ingrediente},
   //Aqui é o formato que o arquivo PHP irá responder
   dataType: 'html',
   //Caso tudo ocorra bem, aqui nós vamos preencher a lista
   //Repare que este 'data' é o que o arquivo insere.php vai devolver
   success: function (data)
      {
          //Selecionamos o elemento '.lista', e com o método jQuery append() colocamos a resposta do arquivo PHP dentro da lista.
          $('.lista').append(data);
      }
  });

Fourth, let's see the file insere.php:

<?php
//Recebendo o valor passado via POST
$ingrediente = $_POST['ingrediente'];
//Aqui você fez correto, 
$db->setQuery("INSERT INTO #__ingredientes
(id, ingrediente, ordering, published)
VALUES (NULL,$ingrediente,'0','1')
");
//E aqui você devolve um elemento 'li' para a requisição:
//Isso é o que será posto no final da lista
echo '<li>'.$ingrediente.'</li>';
  

IMPORTANT:   Do not forget to include the jQuery library within the <head></head> of your page.

<script
              src="https://code.jquery.com/jquery-3.2.1.js"integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
              crossorigin="anonymous"></script>
  

This fiddle below demonstrates how the file that has the list should be basic.

$(document).on('click','.add-ingrediente',function(){
 var ingrediente = $('.ingrediente').val();
 $.ajax({
  type: "POST",
  url: "insere.php",
  data: {function: 'geral_controllers', target: 'render_edit_user_form', collaborator: $collaborator},
  dataType: 'json',
  success: function (data)
    {
       $('.lista').append(data);
    }
  });
});
.div-form {
width:100%;
border:1px solid #ccc;
}

.div-lista {
border:1px solid #999;
width:100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class='div-form'>
<input type='text' name='ingrediente' class='input'>
<button class='add-ingrediente'>Adicionar</button>
</div>

<div class='div-lista'>
<ul class='lista'>
  <li>
     Ing 1
  </li>
  <li>
    Ing 2
  </li>
  <li>
    Ing 3
  </li>
  <li>
    Ing 4
  </li>
</ul>
</div>
    
23.10.2017 / 21:52