Jump to content

How to call php function from ajax


gmc1103
Go to solution Solved by hansford,

Recommended Posts

Hi

 

I'm trying to call this following php function from a ajax call but i can't get it to work 

class EBSPMA {

function visitaValidacaoByUserAdmin($userid) {
        if(isset($_POST['action']) && !empty($_POST['action'])) {
        $id_visita = filter_input(INPUT_POST, 'id_visita');
        $plano =filter_input(INPUT_POST, 'plano ');
        $valido = filter_input(INPUT_POST, 'valido');
        $sql = "UPDATE `new_visitas` SET `plano`= ?,`valido`= ? WHERE `id_visita` = ?";
                $stmt = $this->connection->prepare($sql);
                if ($stmt === false) {
                    trigger_error('Wrong SQL: ' . $sql . ' Error: ' .  $mysqli->error, E_USER_ERROR);
                }
                $stmt->bind_param('ssi',$plano, $valido, $id_visita);
                if (!$stmt->execute()) {
                   echo json_encode(array('status' => 'error', 'message' => 'Opppss...A visita ainda não foi validada'));
                } else {
                   echo json_encode(array('status' => 'success', 'message' => 'A visita já foi validada...Obrigado'));
                }
        $this->connection->close();
        }
    }
}

and this is my ajax call

function submitForm2(formId){
                var id_visita = $('input[id="id_visita"]').val();
                var plano = $('input[id="plano"]').val();
                var valido = $('input[id="valido"]').val();
                $.ajax({
                   url: 'include/fg_membersite.php',
                   type: 'POST',
                   data : {action: 'visitaValidacaoByUserAdmin()', 'id_visita': id_visita, 'plano': plano, 'valido': valido},
                   dataType: 'json',
                   success:function(response){
                      alert(response.message);
                      $("#myModal2").modal('hide');
                      window.location.reload(true);
                  }
              });

           }

Nothing happens....any help please??

Edited by gmc1103
Link to comment
Share on other sites

Cant really help you without seeing the code for include/fg_membersite.php. You need to post the code which is handling the ajax request.

 

Ajax cannot call PHP functions. You can send a HTTP request to a PHP file yes, but its down to the logic in your php code for how PHP functions are called.

Edited by Ch0cu3r
Link to comment
Share on other sites

Hi 

 

Thank you for your help

Now i'm able to write in my database but i don't receive any alert

This is my update.php file

<?php
   require_once("./include/fg_membersite.php");
   $ebspma = new EBSPMA();
   $ebspma->InitDB('localhost','xxxxx','xxxxx','xxxx');
   if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    $result = $ebspma->visitaValidacaoByUserAdmin($_POST['userid'], $_POST['id_visita'], $_POST['plano'], $_POST['valido'] );
    echo $result;
   }
?>

and my ajax call

 <script>
            function submitForm2(formId){
                var userid = '<?php echo $ebspma->UserId(); ?>';
                var id_visita = $('input[id="id_visita"]').val();
                var plano = $('input[id="plano"]').val();
                var valido = $('input[id="valido"]').val();
                $.ajax({
                   url: 'updates.php',
                   type: 'POST',
                   data : {'userid': userid, 'id_visita': id_visita, 'plano': plano, 'valido': valido},
                   dataType: 'json',
                   success:function(response){
                      alert(response.message);
                      $("#myModal2").modal('hide');
                      window.location.reload(true);
                  }
              });

           }
        </script>

The function called is this one

 function visitaValidacaoByUserAdmin($userid, $id_visita, $plano, $valido) {
        $id = $this->SanitizeForSQL($userid);
        $planos = $this->SanitizeForSQL($plano);
        $validos = $this->SanitizeForSQL($valido);
        $sql = "UPDATE `new_visitas` SET `plano`= ?,`valido`= ? WHERE `id_visita` = ?";
                $stmt = $this->connection->prepare($sql);
                if ($stmt === false) {
                    trigger_error('Wrong SQL: ' . $sql . ' Error: ' .  $this->connection->error, E_USER_ERROR);
                }
                $stmt->bind_param('ssi',$planos, $validos, $id_visita);
                if (!$stmt->execute()) {
                   echo json_encode(array('status' => 'error', 'message' => 'Opppss...A visita ainda não foi validada'));
                } else {
                   echo json_encode(array('status' => 'success', 'message' => 'A visita já foi validada...Obrigado'));
                }
        $this->connection->close();
    }

In my console i receive this echo 

echo json_encode(array('status' => 'success', 'message' => 'A visita já foi validada...Obrigado'));

{"status":"success","message":"A visita j\u00e1 foi validada...Obrigado"}

 

But i have i no alert in my main page....any help?

And if in updates.php i want to put different fucntions, how can i do it?

 

Thanks again

Link to comment
Share on other sites

Your JSON object is not correct. Should look like this.

data : {action: 'visitaValidacaoByUserAdmin', id_visita: 'id_visita', plano: 'plano', valido: 'valido'}

You can only set GET or POST vars and send them to PHP, therefore if you need to call a certain function, just check the POST value in PHP.

if (isset($_POST['action']))
{
    // call your function
    $_POST['action']();
}

I personally wouldn't do it this way, rather get the action and put it in a switch statement which calls the appropriate function.

switch($_POST['action'])
{
 } 
Link to comment
Share on other sites

  • Solution

Since you are using international chars, use utf-8 for your encoding.

$.ajax({

url: "get_id.php",
type: "POST",
dataType: "json",
contentType: "application/x-www-form-urlencoded;charset=utf-8",
data : {action: 'visitaValidacaoByUserAdmin', id_visita: 'id_visita', plano: 'plano', valido: 'valido'},
cache: false,
success: function(response) {

      alert(response['message']); 
}

 

PHP page example:

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

// set headers
header("Content-Type: application/json; charset=utf-8");

if (isset($_POST['action']))
{
    // call function
    $ret = $_POST['action']();
    
    // return result
    echo json_encode($ret);
}

function visitaValidacaoByUserAdmin()
{
    return array("status" => "success", "message" => "A visita já foi validada...Obrigado");
}
Edited by hansford
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.