Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

116
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda