Auto Refresh a div in PHP and AJAX - php

I'm stuck with my auto refresh function in my web course assignment. I always put my code like this :
navigation.php :
<html>
<head>
.... ALL STYLE AND JS .....
</head>
<body>
<div class="menu">
...... ALL MY WEB MENU .......
</div>
index.php :
<?php
include "navigation.php";
function A(){
global $variable_functionA;
.... FUNCTION TO CALL API X BY cURL .....
}
function B(){
global $variable_functionB;
.... FUNCTION TO CALL API Y BY cURL .....
}
?>
<div class="container">
...... MY WEB CONTAINER ........
<div class="auto_refresh">
<?php
include "auto_refresh_data.php"; //Success when first load, failed to load style, js, etc at the second load
?>
</div>
</div>
<?php
include "footer.php";
?>
footer.php :
</body>
</html>
<scrpt>..... ALL MY JS SCRIPT.....</script>
My ajax code :
<script>
setInterval(function(){
$.ajax({
url:'auto_refresh_data.php'
}).done(
function(data){
$('.auto_refresh').html(data);
});
},5000);
</script>
auto_refresh_data.php :
<div class="style">
<?php
function A($variable1);
function B($variable2);
... OPERATION FOR GLOBAL VARIBLE RESULT FROM function A and function B ....
?>
</div>
I want to make an auto refresh data in the middle of my container. Then I made it in ajax like this : How do i auto refresh my div class content? . It failed because of some php variable, style, js, function, etc placed before the auto refresh div element.
So the question is how to make it my data become auto refresh if my code design is like that?
Thankyou

I think there are a couple things you should be doing to fix this, but the main problem are your functions:
1) Move your functions somewhere else, like into their own files:
/functions.php
<?php
function A()
{
global $variable_functionA;
.... FUNCTION TO CALL API X BY cURL .....
}
function B()
{
global $variable_functionB;
.... FUNCTION TO CALL API Y BY cURL .....
}
2) Include the functions in the main file where it's used on load:
/index.php
<?php
include("functions.php");
include("navigation.php");
?>
<div class="container">
...... MY WEB CONTAINER ........
<div class="auto_refresh">
<?php include("auto_refresh_data.php") ?>
</div>
</div>
<?php include("footer.php") ?>
3) On the auto_refresh_data.php page, you need to include the functions again, but use include_once instead of include so you don't get a declaration error:
<?php include_once("functions.php") ?>
<div class="style">
<?php
# Presumably you want to run these functions?
A();
B();
... OPERATION FOR GLOBAL VARIBLE RESULT FROM function A and function B ....
?>
</div>
4) Since you aren't really doing anything special with the ajax, I would just use .load():
<script>
$(function() {
setInterval(function(){
$('.auto_refresh').load('auto_refresh_data.php');
},5000);
});
</script>
Further to this, I would probably look at using setTimeout() recursively vs setInterval() just because if you get a delay in response, you may get those responses out of time. Using setTimeout will fire after the response is returned as opposed to every 5 seconds whether the response has come back yet or not.

Related

How do I define onclick function from php file in jQuery?

New to API's and trying to figure out how to get a function to be defined from a js file when i click on a button i a php file.
The js file is correctly added in the functions.php file.
Right now the jQuery code in my js file looks like this.
jQuery(document).ready(function($) {
function getsource(id){
$.ajax({
url:"https://api.spoonacular.com/recipes/"+id+"/information?apiKey=acc3c7fd3cb74d02b7564eefd51172cd",
success: function(res) {
document.getElementById("sourceLink").innerHTML=res.sourceUrl
document.getElementById("sourceLink").href=res.sourceUrl
}
});
}
function getrecipe(q){
$.ajax({
url:"https://api.spoonacular.com/recipes/search?apiKey=acc3c7fd3cb74d02b7564eefd51172cd&number=3&query="+q,
success: function(res) {
for(var i = 0; i < res.results.length; i++ )
document.getElementById("output").innerHTML+="<h1>"+res.results[i].title+"</h1><br><img src='"+res.baseUri+res.results[i].image+"' width='400' /><br>Ready in "+res.results[i].readyInMinutes+" minutes"
getsource(res.results[i].id)
}
});
}
});
And the php file it should listen to is this one.
<?php get_header(); ?>
<section class="mst-section more-recipes-section">
<div class="mst-row">
<div class="row">
<div class="mst-column-1">
<div class="mst-inner-column">
<input id="search"><button onclick="getrecipe(document.getElementById('search').value)">Search</button>
<div id="output"></div>
</div>
</div>
</div>
</div>
</section>
<?php get_footer(); ?>
In my console I get that the function getrecipe is not defined. How can I get the function to understand that I am calling it in the onclick?
One more thing. If i do the script in the php file it works fine. Like this.
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>
<input id="search" ><button onclick="getrecipe(document.getElementById('search').value)">Search</button>
<div id="output"></div>
<script>
function getsource(id){
$.ajax({
url:"https://api.spoonacular.com/recipes/"+id+"/information?apiKey=acc3c7fd3cb74d02b7564eefd51172cd",
success: function(res) {
document.getElementById("sourceLink").innerHTML=res.sourceUrl
document.getElementById("sourceLink").href=res.sourceUrl
}
});
}
function getrecipe(q){
$.ajax({
url:"https://api.spoonacular.com/recipes/search?apiKey=acc3c7fd3cb74d02b7564eefd51172cd&number=3&query="+q,
success: function(res) {
for(var i = 0; i < res.results.length; i++ )
document.getElementById("output").innerHTML+="<h1>"+res.results[i].title+"</h1><br><img src='"+res.baseUri+res.results[i].image+"' width='400' /><br>Ready in "+res.results[i].readyInMinutes+" minutes"
getsource(res.results[i].id)
}
});
}
</script>
Grateful for help!
If i do the script in the php file it works fine.
The problem isn't that you moved the code to a different file. The problem is that you changed the code, and what you changed it to no longer works.
In your working version the functions are defined in global scope. In your non-working version they are not defined in global scope. They're defined within the callback function to the document.ready event. (Why the change?)
Move the functions back into global scope (remove the jQuery(document).ready(/*...*/); operation) and the code will behave the same as the working version.
Alternatively, if you don't want to have functions in global scope (it's generally considered poor form and can lead to bugs as complexity grows) then you can define them locally within that function scope and then assign the click handler also within that scope.
So instead of using the onclick attribute directly in the HTML (also considered poor form and more difficult to maintain as complexity grows) you would apply the click handler in JavaScript:
document.getElementById('search').addEventListener('click', getRecipe);
In this case the event object will be automatically passed as the argument to getRecipe, and you'd use that within the getRecipe function to get the value. For example:
function getrecipe(e) {
var q = e.target.value;
// the rest of the existing function...
}

How to load dynamic content (jquery) inside ajax call?

My homepage loads pages with jquery ajax call. In the Pictures subpage there is 3 div, and each loads a php with ajax, too. I would like to include a gallery js to every sub-subpage. However, the js does not loads. Here is my code in the index.php for the subpages:
<script type="text/javascript">
$(function()
{
var actualmenu = 'fooldal.html';
$('#tartalom').load('fooldal.html');
$('.fooldal').click(function()
{
$('#tartalom').load('fooldal.html');
actualmenu = 'fooldal.html';
}
);
$('.kepek').click(function(){
$('#tartalom').load('kepek.php', function(){
$(document.body).on('click', 'a[rel=gallery_view]' ,function(){
$(this).KeViewer('gallery', {'percent' : 70});
return false;
});
});
actualmenu = 'kepek.php';
});
});
</script>
And there is my kepek.php page:
<script type="text/javascript">
$(function()
{
$('#galeria').load('kepek_csenge.php');
$('#csenge').click(function()
{
$('#galeria').load('kepek_csenge.php');
}
);
);
</script>
<div id="albums">
<div class="album" id="csenge">
Csenge
<br/>
<img src="albumok/csenge/01.jpg" alt="csenge"/>
</div>
</div>
<div style="clear:both;"></div>
<div id="galeria" width="500"></div>
Inside kepek_csenge.php there are rows like this, which should trigger the gallery:
<a class="thumb_wrapper" href="albumok/csenge/01.jpg" title="Első" rel="gallery_view"><img alt="" class="thumb" src="albumok/csenge/thumbs/01.jpg" /></a>
Unfortunately it just loads a new page with the selected picture. How can i use the galleryviewer js in this page?
It is important to understand that the document you are loading into was ready long before you load anything with ajax
This means that the code wrapped in $(function() in your ajax pages will fire as soon as it is encountered. If that code precedes the html it references then it won't find those elements since they don't exist yet.
Try moving all the script tags in the ajax loaded content to after the html.
It is generally easier to put all the scripts into one and wrap different parts in functions and then just call those functions in the success callback of load();
function loadPage(page){
var url = '...' +page;
$('#selector').load(url, function(){
initViewer();
});
}

PHP scope issue when loading page with ajax

I have an issue with PHP. I have an index file like this:
<?php session_start(); ?>
<!doctype html>
<html lang="en">
<head>
...
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<?php
include $_SERVER['DOCUMENT_ROOT'] . '/config.php';
function __autoload($class_name) {
include $_SERVER['DOCUMENT_ROOT'] . '/classes/' . $class_name . '.php';
}
include '../shared/navigation-bar.php';
$user = new Users($db);
print_r($user);
//this prints fyi - so all is well here
?>
<div class="fill grey-bg">
<?php include(dirname(__FILE__) . '/sidebar.php');?>
<div id="content" class="col-md-10 white-bg">
</div>
</div>
<script src="../shared/js/bootstrap.js"></script>
<script src="./js/app.js"></script>
</body>
</html>
All is well here. Now I have a sidebar included, which does this:
<table class="table">
<tr>
<td>
Manage Users
</td>
</tr>
</table>
Which when clicked uses an ajax call to load a new page:
$("#manageUsers").click(function(){
$("#content").load('pages/manageUsers.php');
});
Ok so this loads the new page - manageUsers.php
<h3>List Users</h3>
<?php print_r( $user ) ;?>
Now, problem here as you can probably guess is that the $user doesn't print out in the loaded in page. I'm guessing it's a scope issue. I define it first time when the index page loads, and then when I load in the document with the click it can't pass the original $user variable through to the new page because PHP is serverside and has already loaded?
The question is, what is the way around this - I'm trying to code in an OOP manner, hence loading the classes and creating the object on the index for use in the other pages.
Problem is if I can't do that, I then have to re-include the classes and create a new object on each loaded in page. This seems frightfully inefficient. Is there a way round this?
If I have to use ajax, is there a smart way to do this via ajax? Or should I just drop the OOP plan and write a function list, including it and a new pdo instance in every loaded in page?
You cannot access php variables after the page is executed. So you need to store the data in javascript and send it to the pages using GET/POST where you want to use them.
Add the below code after "print_r($user);"
<script>
var users_list = <?php echo json_encode($user); ?>;
</script>
Change your javascript code as below
$(document).on('click', '#manageUsers', function(){
$("#content").load('pages/manageUsers.php', {"users": users_list});
return false;
});
Change manageUsers.php code to
<h3>List Users</h3>
<?php print_r($_POST['users']); ?>
If you are unaware of usage of JSON .. JSON is a simple way to interchange/maintain/access data ...
$users = array();
$users[1] = array('name' => 'mr.mad', 'age' => '22');
$users[2] = array('name' => 'miss.mad', 'age' => '22');
echo json_encode($users);
the above code will echo
{
"1": {
"name": "mr.mad",
"age": "22"
},
"2": {
"name": "miss.mad",
"age": "22"
}
}
Make sure even your users array is a structured array like above
Don't use 'click' event directly .. go with "$(document).on('click')" as you are thinking of an ajax application. With this you can use this handler even on newly added dom objects too ..
AJAX is the good way and you are doing it correct with your thought process .. go on ..

How to load a script in a template footer - CodeIgniter

I'm trying out a more maintainable way to structure my code as learnt by some tutorials at nettuts+.
I've succeeded in making my header and footer files separate from the main content of each page so that they are loaded along with each different page, thus making it easier to manage changes to these two files.
I currently want to add some jQuery code to my footer, for only one page. This is where I've hit a wall in thinking. How can I allow this jQuery code to be present in my footer for only one page, and not all pages? Could someone please explain?
I was thinking of doing something like:
<?php if($title = "The jQuery Page"){?>
<script>
jquery code here....
</script>
<?php } ?>
But I think that is considered messy, as you are using one language to set off another.
Edit: Here's the requested code:
In my Controller I call the views:
$data['title'] = "The jQuery Page";
$this->load->view('header', $data);
$this->load->view('cool_page');
$this->load->view('footer');
Then in my footer I want to load a specific script in only this one pages footer:
<script src="<?php echo base_url();?>js/jquery-1.10.2.min.js"></script>
<script>
$(document).ready(function() {
/*cool jquery stuff*/
});
</script>
Try to load a view into the main view
/application/controllers/test.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Test extends CI_Controller {
public function index() {
$data = array(
'title' => "The jQuery Page",
'script' => TRUE // if you omit or comment this variable the 'views/script.php' is not loaded
);
$this->load->view('test', $data);
}
}
/application/views/test.php
<html>
<head>
<title><?php echo $title;?></title>
</head>
<body>
<?php if (isset($script)) { $this->load->view('script'); } ?>
</body>
</html>
/application/views/script.php
<script>
jquery code here....
</script>
You could specify JS to include as part of the data passed to the view:
CONTROLLER1
$this->data['js'][] = 'alert(\'Hi\');';
$this->data['js'][] = 'alert(\'Hey\');';
$this->load->view('footer', $this->data);
CONTROLLER2
$this->data['js'][] = 'alert(\'Yo\');';
$this->data['js'][] = 'alert(\'Sup\');';
$this->load->view('footer', $this->data);
Footer VIEW
if(isset($js) && is_array($js) && count($js) > 0){
echo '<script>';
foreach($js as $key=>$value){
$value;
}
echo '</script>';
}
I don't think there is a way around making a conditional 'if' statement around the script, so I used the suggested solution in my question.
Check the title to see if it is the desired page:
<?php if($title = "Photo Albums - Hands of Humanity"):?>
Then add the script to the DOM if it is so:
<script>
$(document).ready(function() {
//jquery stuff
});
</script>
<?php endif;?>
If there are other ways which are better for maintainability, I would be happy to hear them

Change value of PHP variable with AJAX

The PHP:
<?php
$mainView = "views/dashboardView.php";
?>
The HTML:
<div class="mainContent">
<?php include($mainView); ?>
</div>
I would like the click event of a button to change what view .mainContent shows and I believe AJAX can accomplish this but as yet have not been able to get it to work.
Any advice?
You would have to modify your PHP script to allow for this.
For example:
PHP:
if (isset($_POST['change']))
{
$mainView = $_POST['change'];
echo $mainView;
}
HTML & jQuery:
<button id="change">Change the var</button>
<script>
$("#change").click(function() {
$.post("file.php", {change: $(this).val()},
function (data)
{
$("#mainContent").html(data);
});
});
</script>
<script type="text/javascript>
function changePage(pageDest){
var xmlobject = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xmlobject.onreadystatechange = function (){
if(xmlobject.readyState == 4 && xmlobject.status == 200){
document.getElementById("mainContent").innerHTML = xmlobject.responseText;
}
else{
document.getElementById("mainContent").innerHTML = 'Loading...';
}
}
xmlobject.open("GET",pageDest,true);
xmlobject.send();
}
</script>
<div class="mainContent" id="mainContent">
Change this HTML
</div>
<div onmouseup="changePage('views/dashboardView.php')">Get dashboard view</div>
The parameter in the changePage function is the location of the page that you would like to place in your mainContent <div>
Does this help?
You cannot change the value of a PHP variable, as PHP is Server Side (done first), and JS is Client Side (done after Server Side).
Typically AJAX is used to repopulate an area of a web page, but that would suit your purpose. In the example below, ajax/test.php is the new file you want to include. Obviously change the path/name as you wish, and create that file.
I will add though, if you are repopulating a large chunk of your page, it will probably be just as quick to fully reload it.
$(function(){
$('.your-button-class').on('click', function(){
$.post('ajax/test.php', function(data) {
$('.mainContent').html(data);
});
});
});
Storing the View in the session, will keep the site displaying this view until the user closes the browser and ends the session, the session expires or they change the view again.
The include that sets mainView
<?php
session_start();
$mainView = "views/dashboardView.php"; // default
if(isset($_SESSION['mainView']))
{
$mainView =$_SESSION['mainView'];
}
?>
// the ajax script that sets the mainView
<?php
session_start();
$_SESSION['mainView']='views/'.$_GET['mainView'].'.php';
?>
the javascript link for ajax
ajaxURL='ajax.php?mainView=otherDasboard';
you may also want to check for empty session variable and that the file exists before setting it

Categories