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);
});
Related
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.
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.
This question already has answers here:
using php include in jquery
(2 answers)
Closed 9 years ago.
My problem is that I need to include a PHP file inside a DIV when a button is pressed without the page reloading.
There is even more explanation in the 'Jsfiddle' file.
Below is an included Jsfiddle document.
http://jsfiddle.net/jjygp/5/
Thanks for your time. I am more than happy to provide any information upon request.
See here for your updated jsfiddle
You had marked the change button with a name of Change but were trying to select it with an id of change. Also, you had not told jsfiddle to include jQuery.
Try the following:
<button name="Change" id="Change">Change Div</button>
You are specifying a click function on an id, but no id is set on the button.
You can try with load() function in jquery
http://api.jquery.com/load/
PHP is a server-side script language, which will be executed before a JavaScript script did.
Therefore, you cannot use .load() to execute a PHP code, however, you may try .ajax() to create an AJAX request to the server which can implement the PHP code.
Please see http://api.jquery.com/jQuery.ajax/ if you have trouble on using .ajax().
Note: in .ajax() method, there is a setting called beforeSend, which "can be used to modify the jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object before it is sent". Hope this method helps you in any way.
Then, your JavaScript code will be like this:
$(document).ready(function(){
$("#Change").click(function(){
//doing AJAX request
$.ajax({
url:"include/start10.php",
beforeSend:function(){
$('#myDiv').fadeOut('slow');
},
success:function(data){
// do something with the return data if you have
// the return data could be a plain-text, or HTML, or JSON, or JSONP, depends on your needs, if you do ha
$('#myDiv').fadeIn('slow');
}
});
});
});
You cannot include PHP file with AJAX, but instead the response of the AJAX server-side script, which is the PHP (which has the same effect).
Loading...
The JS file (code):
function ajaxalizeDiv()
{
$.ajax({
type: "get",
url: "/path/to/the/php/you/want/to/include",
data: {
// Anything in json format you may want to include
id: myvarwithid, // descriptive example
action: "read" // descriptive example
},
dataType: "json",
success: onAjax
});
}
function onAjax(res)
{
if(!res || !res.text)
return;
$("#mydiv").html(res.text);
}
And here goes the PHP file:
<?php
$id = (int) #$_GET['id']; // same as in data part of ajax query request
$action = #$_GET['action']; // same as in data part of ajax query request
$text = 'click me';
// Note this is short example you may want to echo instead of die
// You may use not JSON, but raw text. However, JSON is more human-friendy (readable)
// and easy to maintain.
// Note also the array keys are used in the onAjax function form res (response).
die(json_encode(array('text' => $text /* and anything else you want */)));
?>
Is it possible to get an element id into a PHP variable?
Let's say I have a number of element with IDs:
<span id="1" class="myElement"></span>
<span id="2" class="myElement"></span>
How do I get this into a PHP variable in order to submit a query. I suppose I would have to resubmit the page, which is OK. I would like to use POST. Can I do something like:
<script language="JavaScript">
$(document).ready(function(){
$(".myElement").click(function() {
$.post("'.$_SERVER['REQUEST_URI'].'", { id: $(this).attr("id") });
});
});
</script>
I need to pass $(this).attr('id') into $newID in order to run
SELECT * from t1 WHERE id = $newID
jQuery is a very powerful tool and I would like to figure out a way to combine its power with server-side code.
Thanks.
This is like your question: ajax post with jQuery
If you want this all in one file (posting to active file) here is what you would need in general:
<?php
// Place this at the top of your file
if (isset($_POST['id'])) {
$newID = $_POST['id']; // You need to sanitize this before using in a query
// Perform some db queries, etc here
// Format a desired response (text, html, etc)
$response = 'Format a response here';
// This will return your formatted response to the $.post() call in jQuery
return print_r($response);
}
?>
<script type='text/javascript'>
$(document).ready(function() {
$('.myElement').click(function() {
$.post(location.href, { id: $(this).attr('id') }, function(response) {
// Inserts your chosen response into the page in 'response-content' DIV
$('#response-content').html(response); // Can also use .text(), .append(), etc
});
});
});
</script>
<span id="1" class="myElement"></span>
<span id="2" class="myElement"></span>
<div id='response-content'></div>
From here you can customize the queries and response and what you would like to do with the response.
You have two "good" choices in my mind.
The first is to initiate a post request every time the ordering changes. You might be changing the ordering using jQuery UI sortable. Most libraries that support dragging and dropping also allow you to put an event callback on the drop simply within the initialization function.
In this even callback, you'd initiate the $.post as you have written it in your code (although I would urge you to look up the actual documentation on the matter to make sure you're POSTing to the correct location).
The second strategy is to piggyback on a form submission action. If you're using the jQuery Form Plugin to handle your form submissions, they allow you to indicate a before serialize callback where you can simply add into your form a field that specifies the ordering of the elements.
In both cases, you'd need to write your own function that actually serializes the element IDs. Something like the following would do just fine (totally untested; may contain syntax errors):
var order = [];
$('span.myElement').each(function(){
// N.B., "this" here is a DOM element, not a jQuery container
order.push(this.id);
});
return order.join(',');
You're quite right, something along those lines would work. Here's an example:
(btw, using $.post or $.get doesn't resubmit the page but sends an AJAX request that can call a callback function once the server returns, which is pretty neat)
<script language="JavaScript">
$(document).ready(function(){
$(".myElement").click(function() {
$.post(document.location, { id: $(this).attr("id") },
function (data) {
// say data will be some new HTML the server sends our way
// update some component on the page with contents representing the element with that new id
$('div#someContentSpace').html(data);
});
});
});
</script>
Your approach looks perfectly fine to me, but jQuery does not have a $_SERVER variable like PHP does. The url you would want to provide would be window.location (I believe an empty string will also work, or you can just specify the url on your own). You seem to be sending the ID just fine, though, so this will work.
If you want the page to react to this change, you can add a callback function to $.post(). You can do a variety of things.
$.post(window.location, {id: this.id}, function (data) {
//one
location.reload();
//two
$("#responsedata").html(data);
//three
$("#responsedata").load("affected_page.php #output");
});
I think number 2 is the most elegent. It does not require a page reload. Have your server side php script echo whatever data you want back (json, html, whatever), and it will be put in data above for jQuery to handle however you wish.
By the way, on the server side running the query, don't forget to sanitize the $id and put it in quotes. You don't want someone SQL Injecting you.
I have some code
<script>
FB.Event.subscribe('auth.login', function(response)
{
FB.api('/me', function(response) {
alert(response.id);
});
</script>
An alert screen appears and shows the value i want (response id). but i would like to assign this value to a php value called $id i know how to do this but because the value is in script it wont work, i have tried adding in the below code without success
</script> <?php $id ?> <script> response.id </script> <?php ; ?> <script>
this code is added just below the alert(response.id);
If you want to use the value on the server side the only way is to send it with AJAX to the server and after that store it in the Database or do something.
You can do something like this
<script>
FB.Event.subscribe('auth.login', function(response)
{
FB.api('/me', function(response) {
$.ajax({ type: "POST", url: "save-fb-id.php",data: {id: response.id} });
}
});
</script>
Forgot to mention this is jQuery implementation
In your PHP script do the following:
<?php
$fbID = $_POST['id'];
save_to_db($fbID);
?>
PHP code is executed by the server before it sends the page to the client. Anything in a script tag is executed by the client. In order to send a value back to PHP, you'll have to submit some kind of request back to the server - it could be a hyperlink (a href='page.php?id=whatever), a form with a hidden value, an ajax request, etc
To add the value to a database, you'll need a php page (eg mypage.php) to insert your entry, with something like
if (isset($_GET['insertme'])) {
mysql_query("INSERT INTO myidtable (id) VALUES ('{$_GET['insertme']}')");
}
And in your script, find some kind of ajax function and send a request to mypage.php?insertme=myid, where mypage is your database inserting page and myid is the id you want to insert.
Note that it's unsafe to insert values from $_GET directly into your database like that - you'll want to filter out single quotes first to prevent sql injection.