Php JavaScript Refreshing Certain Divs - javascript

I want to do the following:
<html>
<div id="first"><?php echo time(); ?></div>
<div id="second">My dropdown menu goes here</div>
<div id="third"><?php echo time(); ?></div>
</html>
I have this "example.php" and what I want is that refreshing first and third divs and PHP codes inside them every 1 second without reloading page and changing the state of the second div which will hold a selection from dropdown menu.
So the selection of the dropdown menu should be exact and when I click and open the dropdown menu, the menu must not be closed when a refresh occurs at first and third div.
Also, refresh method of the first and third div must be simultaneous and completely separate processes. Time printing is just for feeding a time changing value to my problem. I will read and print MySQL database data inside these PHP codes.
How can I do that using javascript? Thanks...

To achieve your desired result, You need to utilize Ajax and JSON.
Your PHP script will return fresh data as json which will be fetched via Ajax and then replaced in the target divs.
But before we begin let's learn a bit about Ajax and JSON
What is Ajax?
Ajax is a client-side script that communicates to and from a server/database without the need for a post back or a complete page refresh. Essentially, Ajax is “the method of exchanging data with a server, and updating parts of a web page – without reloading the entire page.”
What is JSON?
JSON, or JavaScript Object Notation, is a minimal, readable format for structuring data. It is used primarily to transmit data between a server and web application, as an alternative to XML.
How to integrate it with your script?
We will first define a javascript function named update_data() which fetches the values from the server and then updates the divs with their fetched values.
To do all this, we'll use jQuery as a dependency and will utilize it's jQuery.ajax() method
NOTE - To automatically call the function every second we will also need setInterval method
function update_data() {
$.ajax({
url: 'test.php', // Your PHP script location
type: "GET",
async: true, // refer to reference [1] in my answer
success: function (data) {
// Update the values
$('#first').text(data.time1); // get the value of `time1` key from returned data
// #first targets the element with id="first"
$('#third').text(data.time2);
}
});
}
setInterval("update_data();", 1000);
// calls the function `update_data()` every second
Sample PHP script- (test.php)
<?php
if ($_SERVER['REQUEST_METHOD'] == "GET") {
$data = Array('time1' => time(), 'time2' => time());
// returns the data with mime type `json` instead of `html`
header("Content-Type: application/json; charset=UTF-8");
echo json_encode($data); // converts array into json
}
?>
The above PHP script will return the follwoing JSON structure:
{
"time1": 'value returned by first call to time()',
"time2": 'value returned by repeated call to time()'
}
Full html example (calls external php)-
<html>
<div id="first">Print some value on page load, will be replaced by Ajax</div>
<div id="second">My dropdown menu goes here</div>
<div id="third">Print some value on page load, will be replaced by Ajax</div>
<!-- Include jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function update_data() {
$.ajax({
url: '/test.php', // Your PHP script location
type: "GET",
async: true, // refer to reference [1] in my answer
success: function(data) {
// Update the values
$('#first').text(data.time1); // get the value of `time1` key from returned data
// #first targets the element with id="first"
$('#third').text(data.time2);
}
});
}
setInterval("update_data();", 1000);
// calls the function `update_data()` every second
</script>
</html>
Reference -
1. What does "async: false" do in jQuery.ajax()?

Use http://api.jquery.com/jquery.ajax/
Example:
<script>
$(function(){
$.ajax({
url: "first.php",
})
.done(function( data ) {
if ( data ) {
$('#first').html(data);
}
});
});
</script>
Now, if you are really swimming off the pond, I'll make it easier:
<script>
var t=0;
function fetchFirst()
{
$.ajax({
url: "first.php",
})
.done(function( data ) {
if ( data ) {
$('#first').html(data);
clearTimeout(t);
}
});
}
$(function(){
t=setTimeout(fetchFirst, 1000)
});
</script>
Now you can get the rest from this quick start. Remember to embed jquery before this stuff with
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
and do not make too many requests simultaneously.
Good luck.

Related

Php file called by ajax isn't echoing javascript code

I'm trying to create a page where a user can upload a file and select the people they want to email it to. Once they click submit, I prevent page refresh and reset their inputs in the form. Now I want to place their previously entered information into a table on the same page (different section of the page).
If you did want to proceed with this concept, you would capture the output of the PHP script in a done() function, insert it in an element on the page, and run eval(). Like this...
$.ajax({
type: "POST",
url: "../FileDrop/dbSystem.php",
data: {tags: JSON.stringify(tags), file:
$('input[name=fileName]').val()};
}).success(function(result) {
$( '#element' ).html(result);
$( '#element script' ).each( () => { $(this).html().eval() })
});
But it would make alot more sense to return data that you use to execute the javascript in your page - that is, keep all that logic together rather than splitting some of it off into a PHP file.
<?php
// php process that checks for 'valid'...
// create a json response
$output = array('valid' => 1);
echo json_encode($output);
?>
.... and in your JS
.success(function(result) {
// result is a stringified JSON object. We need to convert it into an actual JSON object with parse()
result = JSON.parse(result);
// might not matter, but result.valid will be a number which JSON converts into a string. By adding the + right before the variable, that tells JS to use it as a number for the comparison
if (+result.valid == 1) {
$(".outputDiv").show();
}
});

Live data update with PHP

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.

ajax importing json content from php to edge animate

I am working on this project in edge animate for a school assignment.
I have a database on my school webspace and I need to import some data from that database into my edge animate project.
I've been looking on the internet how to do this and these pictures show what I have so far. It still has a javascript error, but I can't figure out what. If I could just get that javascript error sorted, I can add code do some things with the array.
I collect the data from the database in a php-array and I want to save it in an array in javascript so I can display anything from inside that array on different places I want to.
thats because $.ajax is a jquery function, therefore you have to import this libary.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
function Load()
{
console.log('start ajax query...');
var delivery;
$.ajax({
method: "POST",
url: "test.php",
data: { foo: "bar" }
})
.done(function( data ) {
delivery=data;
console.log(data);
console.log('...all fine');
});
}
$( document ).ready(function() {
console.log( "firing load function..." );
Load();
});
</script>
PHP Script
dont modify the header, simply echo the return of json_encode().
<?php
/**
* FILE test.php
*/
echo json_encode(array('foo'=>'bar'));
?>

Call the php function using ajax

I have a editor embeded in the html page
<div id="editor">
Problem Statement goes here…
</div>
I basically want to store the contents written in editor to a file(preferably in rich text format). I used a script (given below) for storing the contents in a string.(This I used by referring to HTML div text to save and display )
<script type='text/javascript' src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
var StoreEditorContent; //declare a variable to save Content
document.getElementById('save').addEventListener("click", SaveText); // adding event listner for onclick for Saving text
function SaveText(){
StoreEditorContent = document.getElementById('editor').innerHTML; // Save the Content into
document.getElementById('editor').innerHTML = ""; // to blank the editor Content
window.onload = function(){
$.ajax({
url: "submit_request.php",
type: "GET",
success: function writeMsg(StoreEditorContent){
//Not sure if this part is right.
}
});
}
}
</script>
This of course is storing in the contents in a string StoreEditorContent. I now want to pass this string to a php function which will write this(StoreEditorContent) to a file.The php file that contains function to write is given below
<?php
function writeMsg($msg){
$file = "myfile.txt";
file_put_contents($file, $msg);
}
?>
I know I need to use ajax here, but cannot figure out how? Any help appreciated.
You need to provide a data: option to $.ajax():
$.ajax({
url: "submit_request.php",
type: "POST",
data: { content: StoreEditorContent },
success: function (response) {
// Do something with the response sent from PHP
}
});
Then your PHP can do:
writeMsg($_POST['content']);
You should use POST rather than GET for large requests because the limit on GET parameters is relatively small.

Run PHP Query with Ajax return data in modal

This is my first fully attempting to use ajax. I have looked all over Google and cannot seem to find an answer. I am not even sure if what I am trying to do is possible.
I am trying to populate a modal window with data from a mysql table.
Using this javascript below, I an able to print the DATA-ID in a modal window with an HREF click:
<script type="text/javascript">
$(document).on("click", ".open-RestrictModal", function () {
var myId = $(this).data('id');
$(".modal-body #Id").val( myId );
});
</script>
I would like to add to this code is the ability to run a PHP/MySQL query, get the results, and print it in the modal window.
I think I have to use AJAX, but I am not sure. How can I add to the existing code the ability to send the javascript variable to an AJAX page and return the results in a modal window?
Please help.
It doesn't appear that you are even using ajax here, assuming you are using the jQuery library you can build a call like this:
function some_ajax_call(your_param) {
$.ajax({
type: "POST", // We want to use POST when we request our PHP file
url : "some/url/to/your/file.php",
data : { query : your_param }, // passing an array to the PHP file with the param, value you passed, this could just be a single value i.e. data: your_param
cache: false, // disable the cache optional
// Success callback if the PHP executed
success: function(data) {
// do somethig - i.e. update your modal with the returned data object
$('.modal-body #id').val(data);
}
});
}
You can then write you file.php file to handle the query
<?php
// Capture the variable we passed in via AJAX
$param = $_POST['query'];
// Build a query
$query = "SELECT * FROM some_table WHERE val ='" . $param . "'";
// I assume you know how to run a query, this would be fetching an assoc array
$results = $DB->run__query($query);
// Check we have some results, then echo back to the AJAX call
if(sizeof($results) > 0) {
echo $results;
}
echoing at the $results array at the end of our PHP script if we have any results will populate the data array in our success callback with the returned rows, you can then perform any DOM manipulation in the success callback to update your modal, hope this helps.

Categories