Pass php var to Javascript from an ajax call - javascript

I would create an ajax code that load a php page every x seconds.
Result: obtain a specific php var in the loaded page.
Then: assign the value of the obtained var to a javascript.

Polling, in your case downloading a page every x seconds, is hardly ever the best approach to a problem. It wastes resources.
However, if you want to do something with Ajax, I suggest you use JQuery:
https://api.jquery.com/jquery.get
An example, suppose you have a php 'test.php' file with:
echo $myVariable;
You can then do this in javascript:
$.get("test.php", function( data ) {
alert( "The PHP variable is: "+data);
});
Combine this with a Javascript timer and you're done.

Related

How do I execute a PHP function every two seconds inside JavaScript?

I have this PHP function called GetTotalItemsPercentage() which gets the amount of entries in my MySQL database and returns a percent based on the maximum amount of entries that are allowed (returns 50, 40, 39 etc.). However, I want this to update a div's height depending on this percentage. I currently have this code, however after the first update, it doesn't update again.
<script type="text/javascript">
setInterval(function() {
$("#filled-jackpot-display").animate({height:'<?php include 'database/config.php'; include 'database/jackpot.php'; echo getPotFilledPercentage(); ?>%'});
}, 2000);
</script>
So how would I go about getting it to update every two seconds and constantly change the size of the div? I'm guessing I will have to run a loop in the PHP code and then use echo inside the PHP file to run JavaScript rather than the other way.
PHP executes on server, javaScript on the client, you have to make a new php file with
<?php include 'database/config.php'; include 'database/jackpot.php'; echo getPotFilledPercentage(); ?>
in it, let's call it 'getTotalIP.php' then you call it with ajax.
<script type="text/javascript">
setInterval($.ajax('getTotalIP'), 2000); //Short answer with jQuery
</script>
If your script is intended to print something then you need more code to parse the answer. A good way to do it is printing the php result in json and parse it with javaScript.
Here you have more cross-browswer ajax information: https://www.w3schools.com/php/php_ajax_php.asp
You cannot execute PHP on the client side. The way to do this would be to call the php code with ajax() and then animate in the success handler
myscipt.php
<?php include 'database/config.php'; include 'database/jackpot.php'; echo getPotFilledPercentage(); ?>
myscript.js
setInterval( function() {
$.ajax({url: 'myscript.php', success: function(data){
$("#filled-jackpot-display").animate({height: data});
}, 2000);
Note, since ajax is asynchronous, it may not smoothly animate in 2 second intervals. If you only need the height once, then load it on ready and proceed to animate in 2 second intervals

Ajax after success, how to pass data to a variable to php

I have script like this
function getval(sel) {
var id= sel.value;
$.ajax({
type:"POST",
url:"./tab.php",
data:{id:id,task:'search'},
success: function(response){
//(I don't know what i should write for pass to php code)
}
});
}
I don't know how I can pass data response to php code ?
For Example: if I alert response, it's show 123 .so I want pass value 123 to a variable in php
$id = 123
response is the result passed BY php, not TO php. What's passed to php is the id and the task.
In your tab.php, you can access these two values :
<?php
$id = $_POST['id'];
$task = $_POST['task'];
//do anything you want with it...
?>
This is not the right workflow. PHP executes on runtime, so every time the page has finished loading you can't really put variables back into PHP (unless you reload the page). This is where AJAX comes in, so you can call PHP scripts from JavaScript / jQuery and don't have to reload the page every time.
The right thing to do is to either store the variable you have generated in the tab.php script in a database, $_SESSION, $_COOKIE or something similar like so:
//put this at the top of all your php scripts you want to use the variable in
session_start();
//now store the variable you wanted to pass (in tab.php)
$_SESSION['returnValue'] = $myValue;
Now if you want to use the variable in other pages just echo it like so (remember to add session_start() at the top of the PHP script.
echo $_SESSION['returnValue'];
First of all, start by reading this
To answer your question,
function getval(sel) {
var id= sel.value;
$.ajax({
type:"POST",
url:"./tab.php",
data:{id:id,task:'search'},
success: function(response){
//(I don't know what i should write for pass to php code)
}
});
}
The result from id and task are sent via $_POST (type:"POST") to the page tab.php (url:"./tab.php"). If you want to do that on a different page, just change the url in your ajax call: url:"./any_other_page.php" and the posted values will be sent there
Finally, read THIS post as well. It is greatly written and very well explained.
Hope it helps!
Keep on coding!
Ares.

Passing data from PHP to JS and JS to PHP

Hi I'm trying to learn PHP and javascript, therefore I tried to do an exercise about passing data but I didn't understand the js function and currently unable to do anything.
Here is the code
php-code.php
$v1=$_GET['v1'];
$v2=$_GET['v2'];
$v3=$_GET['v3'];
//Some operations about them
echo $output;
my-js.js
var v1 = $('#v1 option:selected').val();
var v2 = $('#v2 option:selected').val();
var v3 = $('#v3 option:selected').val();
//This is where I want to pass these variables to my php file and get the output
//But i don't know how
js-execute.php
//this is where my js gets the variables at first
PHP is a server-side language while JavaScript is a client-side one. This means that PHP will be executed when someone requests a page, but the browser will only get the result of the PHP code. On the other hand, JavaScript is sent to the browser and the browser will execute it at the appropriate time (when the page loads or when an event happens). That's why if you look at the source code of a page, you will be able to see the JavaScript code, but never the PHP code.
If you want to pass values from JavaScript to PHP, you will need to make a remote call to a PHP file. PHP isn't like JavaScript – once it's done running its code, it won't be able to respond to anything without a reload of the page.
The easiest way to send something to a PHP file and fetching the result with JavaScript can probably be achieved with JQuery. It has a function $.get which will fetch a given URL. Just be sure to properly validate the input on the server side – never trust user input.
JavaScript (using JQuery to send v1, v2 and v3 to page.php)
function requestPage(v1, v2, v3) {
$.get('page.php', {'v1':v1, 'v2':v2, 'v3':v3}, function(data) {
alert(data);
});
}
PHP (a trivial example)
// Be sure to properly validate input!
if(isset($_GET['v1']) && is_scalar($_GET['v1'])) {
echo strrev($_GET['v1']);
}

setInterval php variable in javascript [duplicate]

This question already has an answer here:
PHP code only runs once inside javascript setInterval
(1 answer)
Closed 8 years ago.
I am trying to post an updating ping on my website, without having it reloading all the time, yet when i try it posts the initial ping, but it doesnt update after the time interval i've set
index.php :
<script>
setInterval(document.write('<?php echo json_encode(getPingout());?>'),100);
</script>
functions.php :
<?php
function getPingout() {
// some function that finds the ping of the server
return $server->getPing();
}
?>
You can't just have php run multiple times after a page has loaded. That PHP is executed one time when the page loads.
To do what you are attempting to do you should use some javascript and an ajax call.
$(function(){
function pingServer(){
$.post('/ping.php',function(data){
console.log('server is ok');
});
}
setInterval( pingServer, 4000 );
});
Also you may not need to ping the server every that often (every 100). Otherwise you may have issues.
That is not how javascript & PHP work together.
In order to refresh data without a page reload, you must request the data asynchronously. Search for AJAX or XHR, I really recommend that you look into something like jQuery though, as you will save alot of time writing code and debugging, compared to if you were to write the javascript by yourself.
If you were to do this in jQuery:
//this means run when page is ready
$(function(){
setInterval(function(){
//Send POST request to ping.php
$.post('ping.php',{},function(){
//Append the result to the body in a new div
$('body').append($('<div>'+data+'</div>'));
});
},100);
});
and your ping.php should simply return the ping and nothing else.
And don't let the dollarsigns confuse you, in PHP its a prefix for variables, but in the javascript/jquery context it simply is a variable, containing the jquery object that you call functions from.

How to pass PHP/html to javascript loop

I have a pretty robust JavaScript script that controls my room lights via some external software. I have a PHP that when run returns only a 1 or a 0. I ideally want to have a JavaScript loop that runs every couple seconds and pulls that 1 or 0 and if it is a 1, do some work. Problem is, can't figure out how to get the JavaScript to open another page in terms or processing/data collection.
Is there a "file get contents" equal to JavaScript? I don't want the PHP values written on the JavaScript page, just to have the value to do a little if statement.
As #Marc B said, you want to make AJAX calls. Here is a idea in how to implement it using jQuery.
<script>
function updateData(){
$.get( "ajax/test.html", function( data ) {
//now "data" has the response
});
}
setInterval(updateData, updateInterval);
</script>
JavaScript Timers - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Timers
jQuery $.get() - http://api.jquery.com/jQuery.get/

Categories

Resources