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 ..
Related
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.
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
I'm using ajax to pass data to a php session in order to save the contents of a js powered shopping cart. Here is the test js code:
//js.html
<html>
<body>
<script>
function addCart(){
var brandName = $('iframe').contents().find('.section01a h2').text();
$.post("sessions.php", {"productName": brandName}, function(results) {
//success alert
});
}
</script>
</body>
</html>
and here is the php code:
//session.php
<?php
session_start();
// store session data
$_SESSION['productName'] = $_POST['productName'];
?>
<html>
<body>
<?php
//retrieve session data
echo "Product Name = ". $_SESSION['productName'];
?>
</body>
</html>
However what I need is after having saved the data to the session, I want to output it to the user in a mini cart in the sidebar.
When I run js.html it successfully passes the data to sessions.php. However the echo isn't displayed in js.html. If I run sessions.php then the echo displays but isn't in the page I need.
My question is, either via PHP or js, how do I then echo or display this data to the user on the page I need?
Thanks
Change session.php to this:
<?php
session_start();
// store session data
$_SESSION['productName'] = $_POST['productName'];
//retrieve session data
echo "Product Name = ". $_SESSION['productName'];
?>
And in your HTML code:
function addCart(){
var brandName = $('iframe').contents().find('.section01a h2').text();
$.post("sessions.php", {"name": brandName}, function(results) {
$('#SOME-ELEMENT').html(results);
});
}
$.post("sessions.php", {"productName": brandName}, function(results) {
alert(results.productName);
},"json");
//session.php
<?php
session_start();
// store session data
$_SESSION['productName'] = $_POST['productName'];
echo json_encode(array('productName' => $_SESSION['productName']);
?>
Using Pure Javascript
The echo isn't appearing because you're making an AJAX call. I don't see what's stopping you from outputting the details in the JS code, underneath where you make the Ajax request.
$.post("sessions.php", {"name": brandName}, function(results) {
//As in put the code here.
});
With the mootools Library
Alternatively, you can look into the mootools library. That library has a Request object, with an onSuccess method. You can port your shopping basket code into that onSuccess method.
i give another codes for example
this is my some3.php code:(First file)
:
<head>
<script src="jquery-1.7.2.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$('p').click(function(){
var who = $('input#who').val();
var why = $('input#why').val();
$('#geting').load('file2.php',{who:who,why:why},function(applyData){
if ( applyData == 'YEY . Ye have hi' ){
alert('OKKK data is ok ');
} else{
alert('Nooo We dont have requested output');
}
});
});
});
</script>
</head>
<body>
<p> click </p>
<input type="text" id="who">
<br>
<input type="text" id="why">
<div id="geting" align="center">
</div>
</body>
i this my file2.php:
<?php
echo "1";
echo "2";
if($_REQUEST['who'] == "hi"){
$myVariable = "YEY . Ye have hi";
echo $myVariable;
} else{
$myVariable = "The out put is not Hi";
echo $myVariable;
}
?>
its not work why? becuse we have echo "1" and echo "2"
i want jquery just check $myVariable data not whole php callback ! i think i must use json but i dont know how
Well, assuming that you want to read the value with JQuery off the page you are posting to, you could do this, since you are echo'ing the value out in that page by doing the following: echo $myVariable;
Now this is how I generally read a value off another page with JQuery which is by using JQuery's get() method.
$.get("thepagetoretrievefrom.php", function(retrievedvalue) {
alert("Here's the data you requested: " + retrievedvalue);
if (retrievedvalue == 1) {
//print out something here
alert("The retrieved value was 1.");
}
});
And that should retrieve the value from the PHP page. "thepagetoretrievefrom.php" is the page where you want to retrieve the information from. function(retrievedvalue) just indicates that whatever output you're requesting from the page via JQuery will be put into retrievedvalue. Then, using JQuery, you may decide whether you want to do a new call to another page depending on what the "retrievedvalue" was.
This, however is not the best method to achieve this, since this will print whatever may be in that page, but if you are requesting one specific value from that page, then it shouldn't be an issue.
<?php include("news.php"); ?>
Hello, I include a news.php in my main page index.php. I want to refresh the news.php every 30 seconds, but not refresh the main page index.php, How to partial refresh a include php page? Thanks.
I've been searching for something similar and it's taken a while but I think this might work:
<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
<script>
$(document).ready(function() {
setInterval(function() {
$("#screen").load('news.php')
}, 2000);
});
</script>
Another way to refresh an include (Valid only if the include only contains variables and their values):
<?php
$config = file_get_contents("news.php");
$config = str_replace("<?php", "", $config);
$config = str_replace("?>", "", $config);
eval($config);
?>
Very easy method to refresh include (only for backend single user, not for frontend):
<?php
$t = time();
rename("news.php", "news_${t}.php");
include("news_${t}.php");
rename("news_${t}.php", "news.php");
?>