How to insert value in mysql with PHP and Ajax

Asked

Viewed 1,035 times

0

I have the following page of recipes, which brings the list of ingredients:

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

And from now on I’ll show you the list of ingredients.

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

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

The right line of reasoning or traveling?

  • You got the idea right, but you missed far in practice, you’ve done something in JS or Ajax that makes a query ?

  • with ajax no.. :/

  • I put in a very detailed answer, I believe you’ll achieve based on it.

2 answers

1

This is quite simple to do, let’s assume that your code to insert is in a unique file, called inserir.php.

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

Now just do the ajax

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

That way it will always insert a new item to your list without updating the page, as you have not posted all your code, it was difficult to make a more complete example, but the basis is this.

  • is that the code is a bit complex, I decided to test first in a blank file to learn, I set up an addingrediente.php that has a form with input and button, I wanted in his Ubmit, he do this whole process

0

Let’s go in pieces:

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

  • HTML Will build the elements
  • Javascript will make 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 of a button:

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

Second, you need to take 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 to save to BD and return the value, we will use a method $.ajax, which operates as follows: NOTE: This ajax call should go inside the event that was passed up.

$.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 inserts.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: Don’t forget to include the jQuery 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>

Browser other questions tagged

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