I want to update a div by via Ajax if a php variable changes. My setup looks like this:
I'm using 2 files:
index.php (displays the div that needs updating):
<?php include('variables.php?>
<div id="apples">
Apples: <php echo "$applescount"; ?>
</div>
<div id="oranges">
Oranges: <php echo "$orangescount"; ?>
</div>
variables.php (where the variables are defined)
$applescount = 2 (ex: value obtained from db)
$orangescount = 3 (ex: value obtained from db)
I need a simple jQuery function that checks if the variables ($applescount or $orangescount) change and then updates the divs (apples and oranges respectively).
Create an javascript interval that makes an AJAX request every few seconds to your back end, return the results as JSON. Parse the JSON in the front end to update to user interface.
Might want to consider making this using javascripts new 'promise' system.
PHP does not allow two-way data binding without polling.
You could consider creating a socket connection that 'connects' to something on your backend, then there might be a library that can integrate with your database to notify of certain values changing, not sure if this would be with PHP though.
Something like this:
function doPoll(){
$.post('ajax/test.html', function(data) {
alert(data); // process results here
setTimeout(doPoll,5000);
});
}
Try this.
$.post('update.php', function(response) {
$('#apples').text(response.apples);
$('#oranges').text(response.oranges);
});
While this seems to be on the right track... you should use a medium PHP handler to handle whatever you wish to do with the data.
This is the general direction (you need jquery to be loaded)
HTML
Apples : <span id="apples"></span>
Oranges : <span id="oranges"></span>
JS
$.post('handler.php',function(data){
$('#apples').html(data.apples);
$('#oranges').html(data.oranges);
})
PHP - handler.php
<?php
// get from db etc...
$apples = get_from_db();
$oranges = get_from_db();
echo json_encode([
"apples" => $apples,
"oranges" => $oranges
]);
?>
The JS will call PHP and the response should come back in an object.
if you wish a non-jquery version you should look into youmightnotneedjquery.com
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I get some data out of an API. The data comes in JSON format.
I fetch the data with PHP and put it out in HTML.
Now what I want to do is, to implement a filter mechanic to output different content from the API.
Example:
I can call the API with a filter. I choose one request with type = 1 and another with type = 2. Both calls return a JSON object with the expected data. I do a foreach loop in PHP and put out the data from call 1. I do another loop with data 2. At the beginning I want to display Data 1 and when I click on a link (e.g. Get data 2) the data 2 should be loaded and replace data 1.
So far so good. I have not much experience with JavaScript or JQuery. What is the right approach? Fetching the data from the API call and work directly with JS? Is there a way to store the PHP output and just load the output that is needed?
I dont have much code to show because this more like setting up a base. I like to understand how to approach these problems and get to a solution by myself (Still learning). Maybe someone can explain the steps to get to a solution.
<?php
// Making an API call with POST as the method.
// The $filter1 variable holds a JSON Object with search terms for
// data 1
$results = new APIReader('POST', 'https://www.linktoapi.com/', $filter1, 'username:password');
?>
<!-- Links to filter the data output -->
<nav>
get data 1
get data 2
</nav>
<?php
// Loop through data 1
foreach ($results as $result) {
echo $result->ID;
}
?>
So I do another API call and loop for data 2. How can I load data 2 instead of data 1 without having to reload the page?
Thanks in advance!
You have various ways to do. You can either do it at the client side and as well as at the server side.
It is possible to update the UI without reloading the page and the technique used is "AJAX".
Now it depends on you wheather you want to do it at client side or server side.
For client side:
1. Call the Api and get the whole data and store it an global javascript variable ( you can store it in localstorage as well so it does not removed after page refresh).
2. Now you can loop through the data and filter the data as and when required.
For server side:
1. Make 2 Api's at the server with different queries as you required.
2. Now call these Api via Ajax and your page will never get reload but the page will get refreshed.
You should use Jquery for easy implementation.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var dataFetched = null;
//fetching and storing the data on page load
$.ajax({url: "https://www.linktoapi.com/", success: function(result){
dataFetched = result;
}});
$("#button1").click(function(){
if(dataFetched){
//filter the data and show the result
}
});
$("#button2").click(function(){
if(dataFetched){
//filter the data and show the result
}
});
});
</script>
</head>
<body>
<button id="button1">API 1</button>
<button id="button2">API 2</button>
</body>
</html> ```
This (top of mind, quick-and-dirty code) isn't the best way to solve it, although I hope it'll probably help you a step in the right direction
Points of interest:
Input needs to be sanitized
$_GET isn't the best way to get input
urls in href should be well formed
<?php
$filter = GetRequiredFilterObjectFor($_GET['dataId']); // This function you'll have to create
// Making an API call with POST as the method.
// The $filter variable holds a JSON Object with search terms for
// data <dataId querystring parameter>
$results = new APIReader('POST', 'https://www.linktoapi.com/', $filter, 'username:password');
?>
<!-- Links to filter the data output -->
<nav>
get data 1
get data 2
</nav>
<?php
// Loop through data
foreach ($results as $result) {
echo $result->ID;
}
?>
I have an API which works well, however I would like it to be live (get data periodically from API and show it in my html code).
I just need some hint that from where I most start. Javascript, Ajax?
Any clue would be appreciated.
My PHP / HTML:
<h4>Cpu Load</h4>
<span class="text-muted"><?php
echo "" . $first['cpu-load'] . " %" . "";
?></span>
Which outputs 2% or whatever. On refresh the page updates the new value.
My PHP API:
<?php
require('includes/routeros_api.class.php');
$API = new RouterosAPI();
$API->debug = false;
if ($API->connect('MYIP', 'USER', 'PASS')) {
$ARRAY = $API->comm("/system/resource/print");
$first = $ARRAY['0'];
$API->disconnect();
}
?>
To keep things simple you could create a function that has your ajax call.
You should look up the .ajax jquery usage, but this gives you an idea.
function ajaxQuery(){
// some stuff inside here to perform call
$.ajax({
url: 'your-file.php',
dataType: 'what ever data type you expect from server...',
success: function(data) {
// this is where i would normal have an id setup to update
// a specific textbox or form field...
}
});
}
You will then have to use the javascript timer function setInterval() somewhere on your page:
setInterval(ajaxQuery(), 2000);
Use setInterval function to query the API every certain time:
https://www.w3schools.com/jsref/met_win_setinterval.asp
The convenient way for me is using Vue and Vue-resource via data-binding, after querying API and change data, the page will be re-rendered without refresh the whole page.
Using AJAX We can get php echoed data by
success: function(data)
Also We can point them to display inside any ware in the page using id of the element.
Eg-
$("#id").html(data);
My problem is how can I display those data in different places? My result gives me like 8 values and I want them to display in different places of my web page. Better if i can use php codes where ever i want to display them. eg:- <?php echo ($row[0]); ?>
I'am sure it is possible with PHP Sessions. Is there an easy way to achieve this?
Define a global variable and assign returned json to that variable then you can use that value anywhere in the page.
Var datarow;
$.ajax({
...,
success: function(dataJson) {
datarow=dataJson
}
});
$("#yourHtmlId").html(''+datarow.firstValue);
I am developing a php page containing a drop down select button. On changing its value, I am calling a javascript method and passing value selected in drop down. Now I want to use the value passed to get further details from MySql using PHP. How can I write PHP code withing javascript?
I am a beginner to PHP. Suggest me a simple and easiest way to do this
For onchange event of dropdown, you can call php page using ajax and passing your params and get the output.
Try to use ajax like this (http://www.w3schools.com/php/php_ajax_database.asp)
and this (http://coursesweb.net/ajax/multiple-select-dropdown-list-ajax_t)
Front-end client side script (Javascript) can't directly 'invoke' or run PHP code. This is because of the separation between client side (browser) and server side (server) components of a web page. When you make a normal request to a server to return a page (eg. index.html), it will return the content of the page and terminate the execution.
What you're trying to achieve is something called AJAX, which is described on Wikipedia. There's also a pretty good and basic example of how to run a PHP script from Javascript.
In basic terms, AJAX is an asynchronous execution of the server side component of a web page. You can target a page 'test.php' with an ajax request, much the same was as you would when you open the page in your browser, and the content of the page would be returned.
To get the additional content, you can use either a POST ($_POST) or GET($_GET) request to send details back to the server. Typically when you're performing a search, you would use GET. If you're performing an update or create, you would use POST.
So your page URL might be something like http://mywebsite.dev/ajax.php?select=apples (where mywebsite.dev is the development URL). If you have a table of apple types, your MySQL query would be:
$type = $_GET['select'];
// Do some filtering on $type, eg. mysql_real_escape_string() and a few others
SELECT fruit.types FROM fruit WHERE fruit.main_type = '$type';
And then return a formatted JSON object back to the browser:
$return = Array(
0 => 'Pink Lady',
1 => 'Sundowner',
2 => 'Granny Smith',
...
);
$json = json_encode($return);
// expected result
{['Pink Lady'],['Sundowner'],['Granny Smith']};
You can always give extra indexes to arrays (multi-dimensional) or use stdClass to give better structure.
Then in your Javascript you use a for loop to iterate over the json object to build a new list of options.
var output = '';
for (var i = 0, k = json.length; i < k; i++) {
output += '<option value="' + json[i] + '">' + json[i] + '</option>';
}
Hope that helps.
Hi for this you need to use ajax.
try :
index.php code : This script will grab data from from using jquery and post it to search.php file via ajax
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#userid').change(function(){
userid=this.value;
$.ajax({
url:'search.php',
data : 'userid='+userid,
type:'POST',
success:function(result){
$('#result_div').html(result);
}
});
});
});
</script>
</head>
<body>
<form name='getUserData' id='getUserData' action='#' method='GET'>
Select User : <select id='userid' name='userid'>
<option value='1'>Lokendra</option>
<option value='2'>Amit</option>
<option value='3'>Nitin</option>
<option value='4'>Rishabh</option>
</select>
</form>
<div id='result_div'></div>
</body>
</html>
search.php code : This file will contain you business logic . and return value to ajax success method. You can fill retrun result any container.
<?php
$userArray=array(
1 => 'Lokendra',
2 => 'Amit',
3 => 'Nitin',
4 => 'Rishabh',
);
$postedData=$_REQUEST;
// Fire your select query here and diplay data
if(isset($postedData['userid'])){
echo "Selected User name =>".$userArray[$postedData['userid']];die;
}
?>
Dont forget to accept answer if it helps you. :)
i'm trying to update is a javascript which when you hover over an image, a div object floats near your mouse with information, this information is stored in a .js file as an array,
eg.
Text[0]=["image 1","data 1"]
Text[1]=["image 2","data 2"]
in the past if this array is change/data added to/removed from it would require uploading a new copy of the .js file, if data was added to/removed from it would also require a change to the .dwt file for the new image which would update every file that use the .dwt file as the main template which could result in 20+ pages being uploaded
i figured i can automate this by using the database by flagging records if they are active and using a mysql query to get only those which are active, this way a blackened app can add to the database and deactivate record thus eliminating having to upload files every so soften.
to do this, i had planned on storing the information in the database and building the above array based off the results, researching how to use mysql queries in javascript lead me to code like this
$.ajax( "path/to/your.php" )
.done(function() { alert("success"); })
.fail(function() { alert("error"); })
now i understand that i need to make a .php file which runs my query and that my formatting of the query results into the array would be one in the .done part but what i don't understand is what i'm supposed to do in the .php file to output the query results how in the .done part i'm supposed to reference the output
bellow is the code i use to echo my query results to the page to ensure i am getting results
$resultIndex = 0
while($row = $results->fetch_array(MYSQLI_ASSOC))
{
echo '<'.strval($resultIndex).'><br>';
echo 'id = 'strval($row['id']).'<br>';
echo 'name = 'strval($row['name']).'<br>';
echo 'desc = 'strval($row['desc']).'<br>';
echo 'active = 'strval($row['active']).'<br>';
echo '-----------------------<br>';
$resultIndex += 1;
}
i am wondering 2 things
do i just echo or print_r what i want returned from my .php file
how to i access what my .php file returns in .done
I recommend using http://www.php.net/json_encode to output into Json. Yes, just echo the output. On success, a callback is called passed with the data from server.
$.post (url, function (data){
//do some stuff with data from server
});
See http://api.jquery.com/jQuery.post/
Your $.ajax function just points to a page and reads the data on that page. If you want that page to use MySQL, you will need to use php to set up the MySQL query and print the data. The layers of a web app are complicated, but I'll try to break it down for you.
A traditional php/mysql setup works like this:
Javascript:
Client side, only deals with content already available on the page. Often edits html based on user interaction.
HTML
Client side, defines the content on a page
PHP
Server side, runs on the server and construct the html
MYSQL
Server side, used to communicate between the php and the database
Database
Server side, used to permanently store data
Ajax is a way for the Javascript layer to call some php in the background. That php can use MySQL to access data in the database and print it out in a format that the javascript can parse and use. Typically the javascript will then edit the HTML.