How to use ajax and php to call a function in php?

8

I'm having trouble requesting a PHP function via Ajax

AJAX Code:

$.ajax({
   url:   'geraSenhaProvisoria.php',
   type:  'POST',
   cache: false,
   data:  {geraSenha(6, true, true, true)},
   error: function() {
         alert('Erro ao tentar ação!');
   },
   success: function( texto ) { 
         $("#senha_provisoria").val( texto );
         $("#senha_provisoria").removeAttr("disabled");
   },
   beforeSend: function() {
   }
});

geraSenhaProvisoria.php

 function geraSenha($tamanho = 6, $maiusculas = true, $numeros = true, $simbolos = false){
    $letrasMinuscula = "abcdefghijklmnopqrstuvwxyz";
    $letrasMaiuscula = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $numero          = "1234567890";
    $simbolo         = "!@#$%*-";
    $retorno         = "";
    $caracteres      = "";

    $caracteres .= $letrasMinuscula;
    if ($maiusculas){ $caracteres .= $letrasMaiuscula; }
    if ($numeros){    $caracteres .= $numero; }
    if ($simbolos){   $caracteres .= $simbolo; }

    $len = strlen($caracteres);
    for ($n = 1; $n <= $tamanho; $n++) {
    $rand = mt_rand(1, $len);
    $retorno .= $caracteres[$rand-1];
    }
    return $retorno;
}
    
asked by anonymous 04.02.2015 / 12:24

5 answers

7

You can pass variables to php using the data property of ajax and then in php itself check and make the function call:

Ajax:

$.ajax({
  type: 'post',
  url: 'geraSenhaProvisoria.php',
  data: {
        geraSenha: "true",
        tamanho: "6",
        maiusculas: "true",
        numeros: "true",
        simbolos: "true"
  } /* ... */
});

php:

$geraSenha = $_POST['geraSenha'];
$tamanho = $_POST['tamanho'];
$maiusculas = $_POST['maiusculas'];
$numeros = $_POST['numeros'];
$simbolos = $_POST['simbolos'];

if ($geraSenha == "true"){
  geraSenha($tamanho, $maiusculas, $numeros, $simbolos);
}

geraSenha( /*...*/ );
    
04.02.2015 / 12:38
4

I always use this way, passing the parameters in the url

        $.ajax({
        url: '/main/conciliacao/gera-senha/tam/6/mai/true/sim/true/num/true',
        type: 'POST',
        cache: false,
        datatype: "json",
        error: function() {
            alert('Erro ao tentar ação!');
        },
        success: function(texto) {
            $("#senha_provisoria").val(texto);
            $("#senha_provisoria").removeAttr("disabled");
        },
        beforeSend: function() {
        }
    });

If the parameters are variable the url would look like this

url: '/main/conciliacao/gera-senha/tam/<?php echo $tam ?>/mai/<?php echo $maiusculas ?>/sim/<?php echo $simbulos ?>/num/<?php echo $numeros ?>',

And the function stays that way

public function geraSenhaAction() {
        $tamanho = $this->params()->fromRoute('tam', 0);      
        $maiusculas = $this->params()->fromRoute('mai', 0);
        $numeros = $this->params()->fromRoute('sim', 0);      
        $simbolos = $this->params()->fromRoute('num', 0); 
        $letrasMinuscula = "abcdefghijklmnopqrstuvwxyz";
        $letrasMaiuscula = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $numero = "1234567890";
        $simbolo = "!@#$%*-";
        $retorno = "";
        $caracteres = "";

        $caracteres .= $letrasMinuscula;
        if ($maiusculas) {
            $caracteres .= $letrasMaiuscula;
        }
        if ($numeros) {
            $caracteres .= $numero;
        }
        if ($simbolos) {
            $caracteres .= $simbolo;
        }

        $len = strlen($caracteres);
        for ($n = 1; $n <= $tamanho; $n++) {
            $rand = mt_rand(1, $len);
            $retorno .= $caracteres[$rand - 1];
        }
        $json = json_encode($retorno);
        echo $json;  exit;
    }
    
04.02.2015 / 12:44
3

The Generate (...) function will not be executed unless you call it through your PHP file. As far as I know, it is not possible to directly call a PHP function through jQuery.

In this case, you will normally call through ajax:

$.ajax({
   url:   'geraSenhaProvisoria.php',
   type:  'POST',
   cache: false,
   data:  "val1=6&val2=true&val3=true&val4=true",
   error: function() {
         alert('Erro ao tentar ação!');
   },
   success: function( texto ) { 
         $("#senha_provisoria").val( texto );
         $("#senha_provisoria").removeAttr("disabled");
   },
   beforeSend: function() {
   }
});

Then in PHP you will have to first get this information and then call the function. Something like:

$val4 = $_POST['val1'];
$val3 = $_POST['val1'];
$val2 = $_POST['val1'];
$val1 = $_POST['val1'];

geraSenha($val1,$val2,$val3,$val4);

function geraSenha($tamanho = 6, $maiusculas = true, $numeros = true, $simbolos = false){
    $letrasMinuscula = "abcdefghijklmnopqrstuvwxyz";
    $letrasMaiuscula = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $numero          = "1234567890";
    $simbolo         = "!@#$%*-";
    $retorno         = "";
    $caracteres      = "";

    $caracteres .= $letrasMinuscula;
    if ($maiusculas){ $caracteres .= $letrasMaiuscula; }
    if ($numeros){    $caracteres .= $numero; }
    if ($simbolos){   $caracteres .= $simbolo; }

    $len = strlen($caracteres);
    for ($n = 1; $n <= $tamanho; $n++) {
    $rand = mt_rand(1, $len);
    $retorno .= $caracteres[$rand-1];
    }
    return $retorno;
}

Any questions, just talk!

    
04.02.2015 / 12:43
2

You can do something like this:

JS

// ...
data: {
    funcao: 'geraSenha',
    parametros: [ 6, true, true, true ]
}
// ...

PHP

call_user_func_array($_POST['funcao'], $_POST['parametros']);

In this case, I am passing the name of the function to be executed and its parameters. In PHP I just need to pass this data to the call_user_func_array ( doc function) to pass the parameters correctly.

Remember that I did not do any security checks. If your geraSenhaProvisoria.php file is only used to execute the geraSenha function, you do not need to pass it as a parameter.

// ...
data: {
    parametros: [ 6, true, true, true ]
}
// ...

call_user_func_array('geraSenha', $_POST['parametros']);
    
04.02.2015 / 12:55
2

Depending on the size of your system and the amount of functions you have in it, you will need to use a more organized way of working with Ajax/Php running functions, here are some tips:

Create your functions and after that create a switch with the desired cases example:

PHP :

function soma($a, $b) {
   return $a + $b;
}

switch ($_POST['ACAO']):
   case 'SOMA':
      $output = soma($_POST['A'], $_POST['B']);
      break;
endswitch;
json_encode($output);

jQuery :

var a = 1;
var b = 2;
$.ajax({
   type: 'POST',
   url: 'teste.php',
   data: 'ACAO=SOMA&' +'A=' + a + '&B=' + b ,
   dataType: 'json',
   success: function (data) {
      console.log(data); 
   },
   error: function (data) {
      alert(data);
   }
});

In this way, your PHP does not run at all, it goes into switch in the selected option and dps comes out sending the answer to ajax.

It's pretty basic but I hope it helps.

    
04.02.2015 / 13:08