Is it possible to call a PHP function through AJAX?

Asked

Viewed 62 times

0

In my PHP page I have the functions: register(), edit() and remove(). How can I make it so that when ajax sends the data in "index.php" falls in the function "registration()"?

AJAX:

$('form[name="cad-form"]').submit(function(){
  var dados = $(this).serialize();
    $.ajax({
      url: '**cadastro.php**',
      type: 'post',
      data: dados,
      success:function(data){
        if (data == "sucesso") {
          alert("Cliente cadastrado com sucesso! :)");
        } else {
          alert("Não foi possível realizar o cadastro :( verifique todos os campos ou contate o suporte técnico.")
        }
      }
    })
  return false;
})

PHP:

<?php
/* CADASTRO DE CLIENTE */
function Cadastro() {
  $nome     = $_POST['nome'];
  $dataNasc = explode('/', $_POST['data_nasc']);
  $dataNasc = $dataNasc[2].'-'.$dataNasc[1].'-'.$dataNasc[0];
  $telefone = $_POST['telefone'];
  $endereco = $_POST['endereco'];
  $cpf      = $_POST['cpf'];
  $rg       = $_POST['rg'];

   $conn = new PDO('mysql:host=localhost;dbname=luanaconsolini', 'root', '');

    $sql = $conn->prepare("INSERT INTO cliente SET
      nome = :nome,
      dataNascimento = :data,
      telefone = :tel,
      endereco = :endereco,
      cpf = :cpf,
      rg = :rg");
    $sql->bindValue(':nome', $nome);
    $sql->bindValue(':data', $dataNasc);
    $sql->bindValue(':tel', $telefone);
    $sql->bindValue(':endereco', $endereco);
    $sql->bindValue(':cpf', $cpf);
    $sql->bindValue(':rg', $rg);
    $sql->execute();
    if($sql->rowCount()>0){
      echo "sucesso";
    }else{
      echo "erro";
    }
}

Thanks in advance :)

  • Weslipe, you can put the other functions in your PHP, you say you have register(), edit() and remove(). but I’m only seeing the register(). Do you have options in your HTML to register, edit, or remove? You have to show the code according to the question

  • It does not help to fall into the function "registration()" because it has several details that must be corrected to work correctly

  • Leo, good afternoon to you. i put only the registration function for not too long, but basically I have these 3 functions: register, edit and remove, and ajax sends the form data to "register.php page"

  • Right, but how will PHP know if it is sending to register, edit or delete? what is in the form to indicate the function that has to run?

  • That’s my question kk at first, I started my php code already calling the function "Registration()", but I believe there are much better ways to do this, I just don’t know how

  • I’m going to put a very basic answer

Show 1 more comment

2 answers

2


You need to make PHP understand that it is receiving a request and itself invokes the desired method. There are diverse ways to do this, I’ll give a very simple example, but I recommend you take a look at some existing projects, or tutorials like this here and this other.

if (!empty($_POST)){ // caso $_POST não esteja vazio, chame Cadastro()
  Cadastro();
}

It is also interesting that you validate some things, such as the existence of the indexes you will use (data_nasc, phone, etc) because if the user sends only the name, for example, but the rest not, your function will fail.

  • That doesn’t solve the problem.

  • There is no "problem" he just asked a way to make the call.

  • Good afternoon Lucius, I tested your code and it worked. My code already presented flaws when the user did not inform all fields before, but did not know how to solve. When you say "validate some things" refers to not letting the customer send the form if you have blank fields ?

  • In fact the ideal would be to validate both in the browser (through the same JS) and on the server (through PHP). In the browser: If the user does not fill in something, you can show some error message even before sending the form, thus avoiding an unnecessary request to the server. But that alone is not so safe, since I can "circumvent" this validation in my browser and send anyway. That’s where validation comes in on the server. If a request arrives without one of the fields, you can return an error message, which JS will pick up and show to the user.

0

Changes to your PHP

  1. Like the dataType jquery was not set work with numbers to not give problems in return. You could work with echo("success") but would have to change the dataType in script and PHP there would also be a change.

    if($sql->rowCount()>0){
      echo (1);
    }else{
       echo (2);
    }
    
  2. Call the function as explained in the @Lucius0101 response

PHP complete

    <?php
    /* CADASTRO DE CLIENTE */
    function Cadastro() {
      $nome     = $_POST['nome'];
      $dataNasc = explode('-', $_POST['data_nasc']);
      $dataNasc = $dataNasc[2].'-'.$dataNasc[1].'-'.$dataNasc[0];
      $telefone = $_POST['telefone'];
      $endereco = $_POST['endereco'];
      $cpf      = $_POST['cpf'];
      $rg       = $_POST['rg'];

       $conn = new PDO('mysql:host=localhost;dbname=luanaconsolini', 'root', '');

        $sql = $conn->prepare("INSERT INTO cliente SET
          nome = :nome,
          dataNascimento = :data,
          telefone = :tel,
          endereco = :endereco,
          cpf = :cpf,
          rg = :rg");
        $sql->bindValue(':nome', $nome);
        $sql->bindValue(':data', $dataNasc);
        $sql->bindValue(':tel', $telefone);
        $sql->bindValue(':endereco', $endereco);
        $sql->bindValue(':cpf', $cpf);
        $sql->bindValue(':rg', $rg);
        $sql->execute();
            if($sql->rowCount()>0){
              echo (1);
            }else{
               echo (2);
            }
    }

    if (!empty($_POST)){ 
       Cadastro();
    }
?>

Change in your Script

if (data == 1) {
     alert("Cliente cadastrado com sucesso! :)");
} else if (data == 2){
     alert("Não foi possível realizar o cadastro :( verifique todos os campos ou contate o suporte técnico.");
}

FULL SCRIPT

<script type="text/javascript">

    $('form[name="cad-form"]').submit(function(){
      var dados = $(this).serialize();
        $.ajax({
          url: 'cadastro2.php',
          type: 'post',
          data: dados,
          success:function(data){
            if (data == 1) {
              alert("Cliente cadastrado com sucesso! :)");
            } else if (data == 2){
              alert("Não foi possível realizar o cadastro :( verifique todos os campos ou contate o suporte técnico.");
            }
          }
        })
      return false;
    })

</script>

HTML

<form method="POST" id="cad-form" name="cad-form" action="">
    <div class="form-group cad-container">
    <label>Qual o nome completo?</label>
    <input class="form-control" name="nome" placeholder="Nome e sobrenome">
    <label>E a data de nascimento?</label>
    <input type="date" inputmode="numeric" name="data_nasc" class="form-control um" id="cad-dat-nasc" placeholder="Data Nascimento">
    <label>Qual o telefone? </label>
    <input inputmode="numeric" name="telefone" class="form-control um" id="cad-tel"placeholder="Ex: (99) 9 9999-9999">
    <label>Onde mora? </label>
    <input class="form-control" name="endereco" placeholder="Rua, numero, bairro e cidade">
    <label>Qual o CPF?</label>
    <input inputmode="numeric" name="cpf" class="form-control um" id="cad-cpf" maxlength="14" placeholder="Ex: 999.999.999-99">
    <label>E o RG?</label>
    <input inputmode="numeric" name="rg" class="form-control um" id="cad-rg"placeholder="Ex: 99.999999-9">
    </div>
    <!--o cad-btn deve estar dentro do formulario-->
    <div class="modal-footer">
    <button type="button" class="btn btn-outline-secondary" id="volta-btn">Voltar</button>
    <button type="submit" class="btn btn-outline-primary" id="cad-btn">Submeter</button>
    </div>
</form>

Browser other questions tagged

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