Load different api content on click (JS) [closed] - javascript

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

Related

How do i make a function that will repeat itself and keep on extracting new values from the database? [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 4 years ago.
So, I need to develop a function that will invoke when the page is loaded at the start and will extract the value from the database and display the same. The value of cod and bod will keep on updating in the database so what I need is to display that updated value onto a page without reloading or refreshing. Thank you.
code:
<?php
include("dbconfig.db");
?>
<script>
function update_data()
{
</script>
<?php
$execute_query = "SELECT cod,bod,tss FROM front_end_data WHERE
slave_id=1";
$output=mysqli_query($conn,$execute_query);
$result_data = mysqli_fetch_assoc($output);
$cod_data = $result_data['cod'];
$bod_data = $result_data['bod'];
$tss_data = $result_data['tss'];
?>
<script>
setTimeout(update_data, 5000);
}
window.onload = function()
{
update_data();
};
</script>
<html>
<head>
<title>
test
</title>
</head>
<body>
<h2>COD DATA: <?php $cod_data ?></h2>
<h2>BOD DATA: <?php $bod_data ?></h2>
<h2>TSS DATA: <?php $tss_data ?></h2>
</body>
</html>
You need Javascript for this. Once the page is loaded, the PHP script has finished executing, so you need to rely on JS for further page interactions after loading.
Your code example is mixing server-side processing with client-side processing. To separate those concerns out, make a single PHP page that serves up the data. Then make a HTML page with javascript that fetches the data from the PHP output. You might like to look at https://www.w3schools.com/php/php_ajax_database.asp as a starting point.
You need to use ajax for this functionality, You can trigger you ajax call with in a timeframe. But it'll make unnecessory calls to server every time. Instead you can use pusher, You can trigger an event whenever a DB value get updated.
Your Code is mixing Server Side Code with Client Side Code resulting into code vulnerabilities. Instead try doing ajax, and do setTimeout Function. What it does is it will call at every X timestamp and fire AJAX to server side and bring up the data.
Here is the nice example to do that:
https://guide.freecodecamp.org/jquery/jquery-ajax-post-method/

If the PHP variable change, update div by using Ajax

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

How to pass javascript variables to php variables with yii

First: I KNOW this is a duplicate. I am creating this because none of the answers to all the other questions satisfy me. I have a very particular situation where I'm using yii and tryi I can't send it through ajax because the php and javascript are on the same page on the same page.
Basically what I'm asking is if you have a page that uses yii and chart js, and you need to render a page that requires two arguments from the clicked bar, which is represented by activeBars[0]:
<script>
canvas.onclick = function(event) {
var activeBars = getBarsAtEvent(event);
<?php $controller->functionThatRendersView($arg1 /**(activeBars[0].value*/,$arg2 /**(activeBars[0].label*/); ?>
}
I don't care if it will render automatically, that is another problem. I just need to get those arguments to the php.
Thanks.
Also, if it helps, I am passing those two values to javascript through php for loops:
labels: [<?php for ($i=1;$i<=$numberIssues;$i++) {
echo $i . ",";
}?>],
The problem with grabbing $i and putting it into the label argument is that I don't know which bar label is the clicked one, I need javascript to pass the clicked bar values back to php.
Explain to us again why you can't use ajax. You say "because the php and javascript are on the same page". That's not what ajax is - you need a different URL for the ajax request, and a separate PHP file or something to handle it.
Without ajax it's impossible for javascript to send information to PHP, because the PHP runs on the server before the javascript runs on the client. Unless of course you want to do a complete page refresh, which is slower and generally worse from the user perspective.
I found an answer to my question! I'm just doing this for anyone else who is stumbling:
To pass javasctipt variable var jsInteger = 5; to php you type (in javascript):
window.location.href = "yourPhpFile.php?phpInteger="+jsInteger;
You access the variable in php like so:
$phpInteger = $_GET['phpInteger'];
This will require a page refresh, and will redirect you to the php file.

Handling MYSQL Query Results returned from PHP 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);

Executing PHP code from javascript

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

Categories