Is there any way to make asyncronous calls to PHP objects methods? Using jquery I could .load en external file into div, but then I wouldnt be able to access methods like setTemp below. I want to avoid having to "wait" for one object to update before the second update is initiated..
My (failed) attempt looks like this, three files:
beachregister:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>OO Method test</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function() {
setInterval(function() {
$("#BaiadoSancho").load();
}, 60000);
});
$(document).ready(function() {
setInterval(function() {
$("#GraceBay").load();
}, 60000);
});
</script>
</head>
<body>
<?php
include 'Baiadosancho.php';
include 'Gracebay.php';
$baia = new Baiadosancho;
$baia->setTemp();
$grace = new Gracebay;
$grace->setTemp();
// .... lots of other beaches
?>
<div id = "BaiadoSancho">
<?php $baia->setTemp(); ?>
</div>
<div id = "GraceBay">
<?php $grace->setTemp() ?>
</div>
</body>
</html>
Baiadosancho.php
class Baiadosancho{
private $temp;
public function getTemp() {
return $this->temp;
}
public function setTemp() {
// $json = file_get_contents('urltogettemperature');
// $arrayDecodedFromJSON = json_decode($json, true);
// ...
// $this->temp = $arrayDecodedFromJSON['temp'];
}
}
Gracebay.php
class Gracebay {
private $temp;
public function getTemp() {
return $this->temp;
}
public function setTemp() {
// $json = file_get_contents('sampl/temperature');
// $arrayDecodedFromJSON = json_decode($json, true);
// ...
// $this->temp = $arrayDecodedFromJSON['temp'];
}
}
..I have also considered other means like the ones below, are they favorable you think?
GearMan, Parallel cURL execution in PHP, EvPeriodic and iron.io
The answer(s) to my question are as follows:
As deceze wrote:
If you want asynchronous execution (in standard PHP), then you will have to resort to something like Gearman or possibly forks. Standard PHP is single threaded and not evented.
It is possible using jquery though, and how to access objects from requested file is explained here:
Using objects in Ajax calls PHP files
Related
I am trying to display records from query in a table and on button clicked to make an ajax call to download the information in an xml format. The query is executed from method inside a class and the ajax request makes call to a different method inside the same class. The first method fills two private properties inside the class and the second property(the one called through the ajax request) must read the properties and fill the data inside table and make the file downloadable. When I try to read the properties from the same class though I get nulls and the foreach returns an error.
This is my ajax request(downloaderScript.js):
;
$("#downloadBtn").click(function (event) {
event.preventDefault();
event.stopPropagation();
$.ajax({
url: 'allClients.php',
type: 'post',
data: {action: 'downloader'},
complete: function (result) {
console.log(result);
},
error: function () {
console.log('Error');
}
});
});
This is the class from which I call the first and the second methods:
class HttpHandlerClient extends HttpHandlerAbstract
{
private $clientsService;
public $storedClientsHeadings;
public $storedClientsData;
public function viewAllClients()
{
$data = $this->clientsService->getAllClients(clientEntity::class);
if(isset($data)) {
$this->storedClientsHeadings = ["Client Names:", "Delivery Address:", "Phone number:"];
$this->storedClientsData = $data;
$this->render('allClientsView', $data);
}
else
{
$this->redirect('clientAdd');
}
}
public function downloader()
{
header("Content-Type: text/plain");
var_dump($this->storedClientsHeadings);
foreach ($this->storedClientsHeadings as $arrayName)
{
echo implode("\t", $arrayName)."\r\n";
}
/**
* #var clientEntity $clientData
*/
foreach ($this->storedClientsData as $clientData)
{
echo implode("\t", $clientData->getClientName())."\r\n";
echo implode("\t", $clientData->getAddressForDelivery())."\r\n";
echo implode("\t", $clientData->getPhone())."\r\n";
}
$filename = "clients_".date("Y-m-d").".xls";
header("Content-Disposition:attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel");
}
And this is the php file that i use between my ajax request and the php class(The file name is: allClients.php, in common.php I make an instance of the class HttpHandlerClient):
require_once 'common.php';
if(isset($_POST['action'])){
$myHttpHandlerClient->downloader();
} elseif (isset($_GET['typer'])) {
$myHttpHandlerClient->viewClientByNumber($_GET['typer']);
} else {
$myHttpHandlerClient->viewAllClients();
}
Sorry if my question is trivial, I even started doubting that after require_once I re-run the code in common.php, making a new instance of HttpHandlerClient and because of this I get nulls in the properties. But when I was reading the documentation in php's site I did not read such a thing. Any help will be appreciated, thanks.
It sounds like what may be happening is that there is a disconnect between the javascript initially loading and then more markup being added to the DOM.
The page loads up which runs your javascript. At this point the JS only knows what is currently on the page.
Your make the first call which changes the DOM. Your javascript does not know about these changes.
You try to reference something that has not been recognized by your initial load of the Javascript.
After you make the call that changes the DOM, you may have to reinitialize your JS to recognize the changes.
Good luck
This is a weird question about a php mvc pattern with ajax calls. The purpose is make a better and dynamically web apps. Let me explain you:
When I learn php, I used this pattern specifically :
model.php
<?php
class myClass {
private $attrOne;
private $attrTwo;
public function getAttrOne() {
return $this->attrOne;
}
public function setAttrOne($attrOne) {
$this->attrOne = $attrOne;
}
public function getAttrTwo() {
return $this->attrTwo;
}
public function setAttrTwo($attrTwo) {
$this->attrTwo = $attrTwo;
}
// ----------------------------------------------------
public function doSelect() {
//some code
}
public function doInsert() {
//some code
}
public function doUpdate() {
//some code
}
public function doDelete() {
//some code
}
}
controller.php
<?php
require "../models/model.php";
if(isset($_POST['action'])) {
$action = $_POST['action'];
if(is_callable($action)) {
$action();
}
}
function registerSomething(){
$model = new myClass();
$model->setAttrOne($_POST['attrOne']);
$model->setAttrTwo($_POST['attrTwo']);
$return = $model->doInsert();
echo $return;
}
function registerSomething2(){
// more app logic code and other stuff
}
view.php -> this is most a pure html file with php extension
<div id="result"></div>
<form id="register" role="form" >
<input type="text" id="attrOne" name="attrOne"/>
<input type="text" id="attrTwo" name="attrTwo"/>
</form>
<script src="script.js" type="text/javascript"></script>
And the script.JS
$('#register').submit(function() {
var action = 'registerSomething';
$.ajax({
data: $(this).serialize() + '&action='+action,
url: '../controlllers/controller.php',
type: 'POST',
success: function(response) {
$('#result').html(response);
}
})
return false;
})
So, what do you think about this pattern? is this pattern efficient?
What is the best way to do ajax calls with a proper mvc pattern in php?
Is this a best practice?
If your goal was to specifically implement something MVC-like, then you have utterly failed. This setup has absolutely nothing to do with MVC. To be honest, it seems that you are way too inexperienced for tackling something like that.
If instead this is your first attempt in applying Separation of Concerns on your code, then it's appropriate. Though, I still wouldn't put that type of code in the production.
My recommendation for you would be: stop trying to "do MVC" for now, and focus instead on improving your general understanding of web development.
You should google the following topics for PHP:
url routing
autoloading and PSR4
difference between active record and data mapper pattern
request abstraction
I am a PHP beginner and trying to write PHP classes that work with HTML and MySql.
I am facing the following problem,
I have created a class called DatabaseManager that contains the function get_value. This function simply returns a value. In another file, I am calling this function on a button click using java script. But the link doesn't seem to work between the two files....Can someone help me?
thank you.
Here's my file that contains the PHP class.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Untitled 1</title>
</head>
<body>
<?php
class DatabaseManager {
private $value=1;
public function get_value ()
{
return value;
}
}
/php>
</body>
</html>
and here's the other file that calls it.
<html>
<head>
<?php include("DatabaseManager.php"); ?>
<script type="text/javascript">
function connect()
{
<?php
$database_manager= new DatabaseManager;
echo "the value is" . $database_manager->get_value();
?>
}
</script>
</head>
<body>
<input type="button" value="Search " onclick="connect()">
</body>
</html>
The name of the file that contains the function get_value is DatabaseManager.php
DO Like this
In Databasemanager.php
<?php
class DatabaseManager {
private $value = 1;
public function get_value() {
return $this->value;
}
}
?>
In another PHP file
<html>
<head>
<?php include("Databasemanager.php"); ?>
<script type="text/javascript">
function connect()
{
<?php
$database_manager= new DatabaseManager;
echo "the value is" . $database_manager->get_value();
?>
}
</script>
</head>
<body>
<input type="button" value="Search " onclick="connect()">
</body>
</html>
A few things:
in DatabaseManager.php remove all HTML. You're including the file elsewhere, you don't need or want duplicated HTML tags.
Remove the # in your MySQL section. This suppresses any errors you are having.
Switch to PDO or MySQLi. They are safer (if used properly)
Your closing php tag is wrong in the database file. You have /php> it should be ?>
Your class does absolutely nothing as-is.
There are multiple things here that you're douing wrong.
You don't need the html code in the first example.
You close the php wrong /php> should generate an error, it should be ?>
When your instantiating your DatabaseManager class you've left out the parentheses which means that the constructor will never get called, this should also generate an error.
You're probably trying to use alert in javascript which in this case you're not doing.
It should look something like this instead:
<?php
class DatabaseManager {
private $value = 1;
function getValue() {
return $this->value;
}
}
?>
And in your html (still php, but the one containing the html-markup) file:
<html>
<head>
<script type="text/javascript">
function connect() {
alert("
<?php
include "nameofDBManagerClassFile.php"
$dbm = new DatabaseManager();
echo "the value is " . $dbm->getValue();
?>
");
}
</script>
</head>
<body>
</body>
</html>
It could also be that you think that the php-code that is inside of the javascript function will not be executed untill you call the JS function connect() this is not so. PHP code is executed on the server and thus will be called when a user requests that webpage, the javascript on the other hand is clientside and will be executed in the users browser. I highly recommend that you read up on both php and JavaScript.
You do it wrong way, to output something in your JavaScript function connect() make this :
function connect() {
alert("
<?php
$database_manager= new DatabaseManager;
echo "the value is" . $database_manager->get_value();
?>
");
}
because php code is executed apart from your on click event.
Actually it's unclear what you wish to get, but you misunderstand the basics.
[edited to clarify users question how to output something to the screen]
I think the easiest way is to use require i another file.
require('login.php');
function get_value()
{
return get_value;
}
I have a PHP script that creates HTML by calling PHP class that I have created. The class creates all the HTML tags one of which is a tag that loads an external JS file. When I try to access the functions from said file nothing happens. Any Ideas?
index page:
function main(){
$content = "Heres some text for you";
$page = new Page($title="MyTitle", $script="external.js", $content=$content)
echo $page->toString();
}
function __autoload($className){
require_once $className . '.class.php';
}
class page:
//class constructor
function __construct($title='untitled', $script='', $content='Default Page class page'){
$this->title = $title;
$this->script = $script;
$this->stylesheet = $stylesheet;
$this->content = $content;
// $this->currentUser = $currentUser;
}
// creates tag structure for HTML pages
function toString(){
return <<<END
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="jquery.js"></script>
// Heres the link to the external JS file
<script type="text/javascript" src="$this->script"></script>
<script type="text/javascript">
test();
</script>
<title>$this->title</title>
<link type="text/css" rel="stylesheet" href="$this->stylesheet" />
</head>
<body>
$this->content
<p id='content'>page content</p>
</body>
</html>
END;
}// end toString function
} // end class Page
?>
External JS:
function test(){
alert("ext. JS test works");
}
You cannot have any spaces before the ending identifier of your heredoc:
END;
should be:
END;
I would also check to make sure that the path to your external.js file is correct. Are any of the other things working? Like the title or css? You also are not passing $stylesheet into your __construct anywhere which produces an error trying to set $this->stylesheet, maybe the whole script is failing to load because of that?
Don't see anything that stands out....
Are you sure the JS file is accessible in the same directory as your script (may want to apply an absolute or relative path if necessary)?
You might also, since you have jquery (assuming it's loaded), try putting the call to test(); in an "on ready" block, like so:
$(document).ready(function () {
test();
});
Other than that, I'd use your given browsers debugging tools to see if you can glean anything useful (like the script not even being loaded as a resource).
Good luck!
Can I use a script to check if a JS file is loaded?
I have a function, which places a form on a page with javascript controls. I don't know where the user will use this form, and it might be loaded several times into a page. It strikes me as the best way to handle things if the form itself loads the script, so it doesn't load if not needed, but this leads me to need to check if the script is already loaded to avoid reloading and adding to page load times and bandwidth use.
No. The page isn't seen until the PHP script has flushed all its output, by which time it's too late to do anything. But most browsers are smart enough to only load an external resource once per page anyway.
You should have an asset management system in your PHP to see whats being included into the page.
Ultra simple example (derived from link):
<?php
class Page {
private static $head = array();
private static $js_assets = array();
private static $content = '';
static function add_head($tag) {
self::$head[] = $tag;
}
static function render_head() {
foreach (self::$head as $tag) echo $tag;
foreach (self::$js_assets as $js) echo '<script src="'.$js.'" type="text/javascript"></script>';
}
static function render_content() {
echo self::$content;
}
static function read_content($file) {
ob_start();
require $file;
self::$content = ob_get_clean();
}
static function render_layout($file) {
require $file;
}
static function add_js($js) {
if (!in_array($js, self::$js_assets)) {
self::$js_assets[] = $js;
}
}
}
Page::add_js('/javascripts/application.js');
Page::read_content('view.php');
Page::render_layout('layout.php');
?>
layout.php:
<html>
<head><?php Page::render_head(); ?></head>
<body>
<div id="header"></div>
<div id="content"><?php Page::render_content(); ?></div>
<div id="footer"></div>
</body>
</html>
view.php:
<?php Page::add_head('<title>Hello World!</title>'); ?>
<h1>Hello</h1>
<p>World</p>