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);
});
})
})
})
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) { ... })
})
})
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.
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);
}
$.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);
},
});
$(document).ready(function () {
$(document).on("click", ".myDivs", function(){
var text = $(this).html();
alert(text);
});
});