Reputation: 167
I am wondering how to transition a variable from PHP to Jquery.
My php file is loaded into a div like this:
$("#leaguesSelectionTable th").click(function(){
var teamSelect = this.id;
$("#loadTables").load("php/leagueTable.php?team="+teamSelect);
});
When the leagueTable.php is loaded into the div, I echoed and made sure the variable gets there. It does.
<?php if(isset($_GET['team'])){
$team = $_GET['team'];
}?>
leagueTable.php also has its own .js file with more functions. I want to know if I can get the $team variable in leagueTable.php to the .js file (which runs on document ready) and stored into a variable. Something like:
$.get( "../leagueTable.php", function( data ) {
var = data;
});
What I really don't get about ajax calls is how do I specify the particular data I want from the PHP file? I only want to retrive the $team variable and store it in a jquery variable.
Thanks.
Upvotes: 0
Views: 129
Reputation: 7277
<script type="text/javascript">
$("#leaguesSelectionTable th").click(function(){
var teamSelect = this.id;
$.get( "php/leagueTable.php?team="+teamSelect", function( data ) {
var teamSelect = jQuery.parseJSON(data);
});
});
<script>
OR you can simply use like below:
var teamSelect = jQuery.parseJSON('<?php echo $teamSelect;?>');
Here you will have to prepare the $teamSelect in the php file as a JSON string.
Upvotes: 0
Reputation: 425
The load
method will expect HTML from the provided URL, to be embedded in the element provided, #loadTables
in this case.
The script
element is completely valid and the browser will probably execute what ever is inside immediately after appending the new DOM elements.
So, the context where this new JS is executed should be the same as the one where you made the AJAX call. If I am not wrong, you could globally declare a variable before calling the load
method and the sub-script
included in the AJAX response should be able to access it.
Though, I think this is probably not the very best approach you could use.
Upvotes: 0
Reputation: 3210
simply
<?php if(isset($_GET['team'])){
echo $_GET['team'];exit;
}?>
and try this to check if you are getting correct values
$.get( "../leagueTable.php", function( data ) {
console.log(data);
});
Upvotes: 1