How to pass PHP/html to javascript loop - javascript

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/

Related

Pass php var to Javascript from an ajax call

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.

Factorize HTML generation code between PHP and Javascript

I have a website entirely coded with PHP. Let's consider the simple example in which a PHP script generates HTML/CSS code from data about a list of fruits, fetched in a MySQL data base :
<?php
function displayFruit( $fruit ) {
echo('<div>');
echo('<span class="fruit-color">Coulor : '.$fruit['color'].'</span>');
...
// display some other parameters of the fruit, with maybe some complex styles, etc.
...
echo('</div>');
}
// Get infos from dabase
$fruits = getAllFruitsFromDatabase();
// Display infos
foreach( $fruits as $fruit ) {
displayFruit( $fruit );
}
?>
Now, I want to add interactivity and to allow the user to filter according to some fruits characteristics (color, etc.) so that only the corresponding fruits are displayed.
So I add some controls and link them to Javascript AJAX queries. These queries will return the same type of data (even though not the same format) as what getAllFruitsFromDatabase() returned, and I want this data to be displayed the same way displayFruit() displayed it.
However, the issue here is that the display/styling process will now have to occur on the client side and not anymore on the server side.
Is there a technical way to factorize the PHP code (the one of displayFruit() ) and the Javascript code that will have to be used, so that there only exists one place where the HTML display code is written (and not once in PHP, and once again in JS) ?
What you describe is a very common problem for interactive web apps and there is not really one 'correct' solution for it. : )
It really depends on what you want in terms of PHP-vs-JS balance, but here are two possible solutions that avoid duplication of the HTML rendering code:
1. Always create the mark-up in Javascript, even on the initial page load
This works well if you want the bulk of your code to be on the client-side. In this solution, you wouldn't have a displayFruit($fruit) function in PHP, but you'd have the equivalent in your Javascript. You would render your page 'frame' on page load, and then do your AJAX call on the document-ready event.
2. Always create the mark-up in PHP, even on the filter-AJAX calls
This is perhaps a more balanced approach and has the advantage that you could design your code such that it's possible to run even if the client has Javascript disabled.
One way to do this is to pass an optional parameter to your page rendering function (in the PHP code) that will make it render only the data part, e.g. something like this:
function renderPage($filters = false, $dataOnly = false)
{
if (!$dataOnly) {
// Output the top of the page
}
// Output the data
// If $filters is not false, the getFruitsFromDatabase call will return filtered data
$fruits = getFruitsFromDatabase($filters);
foreach( $fruits as $fruit ) {
displayFruit($fruit);
}
if (!$dataOnly) {
// Output the bottom of the page
}
}
When your PHP script is called via AJAX, you pass your filters to the first argument of the renderPage function and true to the second argument.
Note on front-end frameworks:
exussum and Michael Chaney have mentioned Javascript frameworks. While I haven't used any of those myself, they look fantastic!
So If you're ready to invest time in re-writing your display logic in JS, then go for it. However, if you don't have much time and would like to re-use as much of your original PHP code as possible, then I would go for solution number 2. The decision probably also depends on the size and design of your existing code.
EDIT: had forgotten to add a $filters argument to the example function
EDIT 2: comment on front-end frameworks mentioned by others in comments

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.

Execute javascript inside the target of an Ajax Call Drag and Drop Shopping Cart without Server language

Well i wanna create an Ajax Drag and Drop Shopping cart using only javascript and ajax. Currently i'm using the example in this page as a stepping stone. Right now it's only with local jquery and it works fine but i want to make the cart work with ajax calls. Note that i do not want to use a server side language( like php, rubby, asp etc), only html and javascript.
My initial thought was that at the $(".basket").droppable i should add an ajax call to another html page containing the "server logic" in javascript, execute in that file all the necessary steps( like reading the get variables (product name, product id and quantity), set a cookie and then return an ok response back. When the server got the "ok" response it should "reload" the cart div with the updated info stored inside the cookie.
If this was with php i would know how to do it. The problem is that as far as i know, you can execute javascript once it reaches the DOM, but how can you execute that js from inside the page that isbeing called upon ? ( thanks to Amadan for the correction)
I've thought about loading the script using $.getScript( "ajax/test.js", function( data, textStatus, jqxhr ).. but the problem with that is that the url GET variables i want to pass to the "server script" do not exist in that page.
I havent implemented all the functionality yet as i am stuck in how to first achieve javascript execution inside an ajax target page.
Below is a very basic form of my logic so far
// read GET variables
var product = getQueryVariable("product");
var id = getQueryVariable("id");
var quantity= getQueryVariable("quantity");
//To DO
//--- here eill go all the logic regarding cookie handling
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
alert('Query Variable ' + variable + ' not found');
}
Any help regarding this matter will be appreciated.
Note: Logic in simple words:
1)have an html page with products+cart
2)Have an "addtocart.html" with the "Cart Server Logic"( being the target of the ajax call when an item is dropped into the product.)
If you have some other idea on this, please enlighten me :)
thanks in advance
Foot Note-1:
if i try loading the scipt using
$("#response").load("ajax/addtocart.html?"+ $.param({
product: product,
id: id,
quantity:quantity
})
);
i get the alert about not being able to find the url parameters( something that i thing is normal as because the content is being loaded into the initial page, from which the request is started, there are no get parameters in the url in the first place)
The problem is that as far as i know, you cannot execute javascript contained in the target of an ajax call, as that page never reaches the browser interpreter.
This is either incorrect or misleading. The browser will execute any JavaScript that enters DOM. Thus, you can use $.load to load content and execute code at the same time. Alternately, you can use hacked JSONP to both execute code and also provide content as a JSON document.
EDIT: Yes, you can't get to the AJAX parameters from JavaScript. Why do you want to? Do you have a good reason for it, or is it an XY problem?
The way I'd do it is this:
$('#response').load(url, data, function() {
onAddedToCart(product, id, quantity);
});
and wrap your JS code in your HTML into the onAddedToCart function.
Depending on what exactly you're doing, it could be simplified even further, but this should be enough to cover your use case.

Categories

Resources