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

Asked

Viewed 17,262 times

10

I’m having difficulty 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;
}

5 answers

10


You can pass the variables to php using the property data 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( /*...*/ );
  • I adapted here in my code and worked perfectly, thanks help! vlw.

  • how did yours turn out please?

5

I always use it like this, 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 is like this

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;
    }

4

The generating functionSenha(...) will not run unless you call it from your PHP file. As far as I know, it is not possible to directly call a PHP function by jQuery.

In this case, you will make the call normally 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() {
   }
});

After in PHP you will have to first acquire this information and there yes 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!

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 pass this data to the function call_user_func_array (doc) to correctly pass the parameters.

Remember that I did no security check. In case your file geraSenhaProvisoria.php is only used to perform the function geraSenha, you do not need to pass it as parameter.

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

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

2

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

Create your functions and after this create one switch with the desired example cases:

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);
   }
});

Thus their PHP does not go out executing everything, he enters the switch goes in the selected option and dps leaves by sending to ajax the answer.

it’s pretty basic but I hope it helps.

Browser other questions tagged

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