PHP variable to jquery variable - php

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.

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);
});

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.

<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.

Related

Auto refresh with jquery gets echo "test" but it does not get data from mysql query.. How can i fix it?

i will try to explain this as clear as possible.. I have a auto refresh script. This script auto refresh a div. I want to call a php file in this div which has mysql in it.. When i try to call that php file only the manual echos display. It does not display anything from database.. If i check the php file i see that it works on its own.. How can i fix this? Thanks.
My script:
<script>
$(document).ready(function() {
$("#feeds").load("sagmenu.php");
var refreshId = setInterval(function() {
$("#feeds").load("sagmenu.php");
}, 2000);
$.ajaxSetup({ cache: false });
});
</script>
<div id='feeds'></div>
My PHP:
<?php
$feeddatagetsq = mysql_query("SELECT * FROM feed ORDER BY id DESC");
$feeddataget = mysql_fetch_array($feeddatagetsq);
echo $feeddataget['id']; //this does not display.. I want this to display..
echo "test"; //this displays..
?>
load() function loads only the html part of the file. So if you want datas from database just echo it
My friend, the $feeddataget['id'] is not a single record. It is returning more than 1 rows (Obviously only with ID column). So according to me, you cannot send this simply by echoing into PHP file.
Use this instead:
echo json_encode($feeddataget['id']);
and in JS File, use this:
var foo = $.parseJSON(responseText); (If you wanna implement it through JQuery)
and, var foo = JSON.parse(responseText); (If you want to do it without JQuery)
Now, foo is a array containing all the IDs that you've returned from PHP File.

Try to get PHP session user into JavaScript

I am trying to get the user session from a PHP script into jQuery, but the result is empty. If I use the code in a PHP script it is working properly.
How can I make this work?
<script>
jQuery(document).ready(
function(){
var user = '<?php echo $_SERVER['LOGON_USER']; ?>';
alert(user);
$('#answer83148X78X346').val(user);
}
);
</script>
You might want first try to check whether the variable you're using is correct by logging an output of $_SESSION['LOGON_USER'] or whatnot. In this case, you can easily do this by checking the resulting HTML page's source code.
Also, when serializing values for JavaScript you should escape them to prevent XSS attacks - i.e., filter value through htmlspecialchars function - or better serialize it as JSON, because it handles all types of values, not only strings.
here is my solution:
i created a authuser.php with the following code:
then i retrieved via jquery.get the result from authuser.php and set the textfield with this data:
$( document ).ready(function() {
$.get("authuser.php", function(data) {
alert("Data Loaded: " + data);
$('#answer83148X78X346').val(data);
});

Refreshing database information via PHP function with Javascript

I'm trying to get a span to refresh with a php function which queries the database for spaces. However, I can't figure out how to keep it refreshing the actual database content dynamically (preferably via a timer). Here's what I have so far
<script type="text/javascript">
window.onload = startInterval;
function startInterval()
{
setInterval("startTime();",1000);
}
function startTime()
{
document.getElementById('spaces').innerHTML = <?php echo get_spaces($id)?>;
}
</script>
You're going to have to use Ajax to load content dynamically without reloading the page.
You will have to make a PHP script that will output only the content you want to load dynamically on the page and then load this script with Ajax.
There is an easy way to do this with jQuery, see this example: http://www.sitepoint.com/ajax-jquery/
I assume get_spaces executes a query by a parameter id
Have this function return a result by
echo json_encode($result);
Now, instead of function start_timer calling your php function statically as your example has above, have it return via ajax
function start_timer(){
$.ajax ({
url: get_spaces.php?id=1, // replace the parameter with dynamic assignment
dataType: json,
Success: function(result){
//iterate thru result json obj
}
});
Like the other posters pointed out, you'll have to use AJAX to make this work. Here is some pseudo code that might help you,
<script type="text/javascript">
window.onload = // Start your setInterval, pass it interval.ajax_call()
var interval = (function(
// Store data here
var data;
return {
// Make your ajax call within this function
ajax_call: function(),
}
)();
</script>
This way you can store the information from your database into data via the ajax callback.

Pass a PHP variable dynamically to an AJAX JavaScript function

I have a JavaScript function (which users on this forum graciously helped me construct) that passes variables via POST to a PHP file with a query for inserting the data to a MySQL database.
The function is invoked "onchange" for a series of 2000+ rows that are spit out from a MySQL database. I use the ID of the row to give each form field a unique name/id, like this:
echo "=<select name='$AdvertisersSQLResult[id]geolocation' id='$AdvertisersSQLResult[id]geolocation' onchange = 'insertAdvertiser()'>";
The JavaScript function looks like this:
function insertAdvertiser() {
var data = $('#<?php echo $AdvertisersSQLResult[id]?>dataid,#<?php echo $AdvertisersSQLResult[id]?>industry,#<?php echo $AdvertisersSQLResult[id]?>geolocation').serialize();
$.post('/database/InsertAdvertiserRelationship2.php', data);
return false;
}
As you can see, I'm attempting to pass PHP variables as part of the form id values. However, this doesn't work, as the function is written to the page once (in the section) without any variables yet populated.
In other words, I'd like to have this JavaScript function utilize whatever PHP variable is being passed to it dynamically. I've looked at other threads about passing a PHP variable to a JavaScript function, but I can't find any reference to how this can be done dynamically, such that the JavaScript function changes to use a different PHP variable each time (if that makes sense).
Thanks for any help...
Well yes because you'd need a seperate insertAdvertiser() method for every advertiser on the system.
A better way to do it would be to do this:
Javascript:
// This line turns your PHP array into a Javascript object
var advertisers = <?php echo json_encode($AdvertiserSQLResult); ?>;
function insertAdvertiser(id) {
$.post('/database/InsertAdvertiserRelationship2.php', advertisers[id]);
}
// Try not to use attributes to bind events, use handlers like this instead.
$(document).ready(function() {
$('select').on('change', function() {
// Reads the advertiser id from the data attribute
insertAdvertiser($(this).data('advertiserid'));
});
});
HTML:
<select data-advertiserid="<?php echo $AdvertiserSQLResult['id']; ?> class="advertiser-select">...</select>
I wrote this as I went along so apologies if I've overlooked something.
See:
jQuery Data
jQuery .on()
You can make a global JavaScript variable and use it in your scripts.
<script type="text/javascript">
myVariable = <?php echo $x; ?>;
</script>
You can store your variables someplace and then access them via JavaScript.
<input type="hidden" class="myVariable" value="<?php echo $x; ?>"
<script type="text/javascript">
var myVar = $('.myVariable').val();
</script>
After you have your data in JavaScript you can do what ever you want to do with it.

How do I use JQuery's "load" function to get the wanted data in a variable?

I need to know how to use jQuery's "load" AJAX function to get the wanted data in a variable?
Should look like this in the end:
var data = "->load data<-";
Thanks!
The load method is there to directly append the data to a jQuery element. Instead you could use jQuery.get or jQuery.post to issue a GET or POST request. Eg.
$.get("url.to/load/from", { param: "Hello" }, function(data){
var loadedData = data;
});
It's a bit difficult to say what you're asking here...
There are 2 load functions in jQuery's core.
If you want to get some data through an ajax call, you should take a look at other jquery ajax methods such as get,post,ajax... and so on:
var data = null;
$.get(url,params,function(response){
data = response;
});
If you want to listen to an load event (such as when the window or an image is loaded) you can do something like :
var data = null;
$(window).load(function(){
data = 'some data';
});
Use http://api.jquery.com/jQuery.get/ or jQuery.post with callbacks to store data into variable.
I hope it will help you
.load is specifically a convenience wrapper to place data directly into a DOM element, without needing to go through custom functions to do so. Use one of the other AJAX methods, like .get.
I have successfully implemented jQuery post
$.post("loadurl.php", { param: value },
function(data) {
alert("Data Loaded: " + data);
});
});

Categories