Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

117
Visualizações
How to call php function inside ajax method

Here I have the following code. I would like to call a function in a file named functions.php and pass in $var1 as the parameter, how would I go about doing this

$(document).ready(function() {
            $("#your_teams234").change(function() {

                var team = $("#your_teams234").val();
                $.ajax({
                    url: 'functions.php',
                    method: 'post',
                    data: 'members=' + team
                }).done(function(requests) {
                    console.log(requests);
                    requests = JSON.parse(requests);
                    $('#teammates').empty();
                    requests.forEach(function(request) {
                        $('#teammates').append('<p class="myDivs">' + request.fname + ' ' + request.lname + '</p>')
                    })
                    $('.myDivs').click(function()
                    { 
                        $var1 = $(this).text();
                        alert($var1);
                    });
                })
            })
        })
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Generally you will have files that contain functions/definitions and others that handle requests. (This is not necessary, just common practice)

Files that handle requests will include any relevant functions/definitions from those other files

For this case, let's use functions.php to contain your main functions and actions.php as a page to handle requests

See the below setup

// functions.php file
function get_team_members(string $team_name){
    // return a list of members based on $team_name
}
// actions.php file
include "functions.php";

$action = $_POST["action"] ?? "";
$data = null;
switch($action){
    case "get_team_members":
        $data = get_team_members($_POST["team"] ?? "");
        break;
}

echo json_encode($data);
// js file
$(document).ready(function() {
    $("#your_teams234").change(function() {

        var team = $("#your_teams234").val();
        $.ajax({
            url: 'actions.php', // update the url to request from actions.php
            method: 'post',
            data: { // update data to reflect expected data
                action: "get_team_members",
                team: team,
            },
        })
        .done(function(requests) { ... })
    })
})
about 4 years ago · Juan Pablo Isaza Relatório

0

I think the issue is you are trying to declare a variable as in PHP in jQuery.

$var1 = $(this).text();

Try below and hope your issue will be resolved.

  1. Your PHP Function should looks like this in functions.php Assuming you are retrieving data from a database,
public function ajaxGetData()
{
   //If you need any identifier from the front end
   $user_id = $this->request->getPost('user_id');
   //Access the database to get data (using codeigniter here)
   $my_model = new Model_Name();
   $data = $my_model->findAll();
   if (!$data)
      echo "FALSE";
   else
      echo json_encode($data);
}
  1. And make sure you are calling the function name in your ajax
$.ajax({
    url: "functions/ajaxGetData",
    type: "POST",
    data: {
        user_id: id //pass the id here if required (optional)
    },
    success: function (data) {
        if(data != "FALSE"){
            var jArr = $.parseJSON(data);
            $('#teammates').empty();
            jArr.forEach(element => {
                    $('#teammates').append('<p class="myDivs">' + element.fname + ' ' + element.lname + '</p>')
                })
            }
        }
        else $("#teammates").html('<p>No data found</p>');
    },
    error: function (xhr, desc, err) {
        console.log(xhr);
        console.log("Details: " + desc + "\nError:" + err);
    },
});
  1. To add the on click function, add separate jQuery function
$(document).ready(function () {
 
    $(document).on("click", ".myDivs", function(){
        var text = $(this).html();
        alert(text);
    });
    
});
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda