I have a project where I need to write text from a database into an HTML5 canvas / Javascript application.
To select this content, I've specified an attribute "reference" where I can ask the database with the content id, for example: index.php?reference=exercise1.
I have used AJAX because I need to get the text content into a Javascript variable in order to write data on canvas.
My solution is working but I need to get the reference attribute value from Javascript document.URL and not PHP $_GET.
Here is the code:
var url = decodeURIComponent(document.URL);
var attr = "reference";
var attrPos = url.lastIndexOf(attr);
var referencePos = attrPos + attr.length + 1;
var reference = url.substr(referencePos,url.length);
What I'm doing seems not to be the clean way to me.
First, ?reference= should be used with PHP $_GET and not be hacked through Javascript.
Then, I have to use lastIndexOf() instead of the search() method in order to get the good value if my application is located in a folder named "reference".
Still, if I have my project in a folder named "reference" with a URI like localhost/reference/projectfolder/index.php and a reference named "projectfolder" in the database, it will load the content even if I have not asked for index.php?reference=projectfolder
From your experience, what is the best solution in my case: be able to get PHP/MySQL data to use with Javascript. Ajax seems to be the best way but as you can see it's not clean, at least my solution.
Thanks for your help.
Still, if I have my project in a folder named "reference" with a URI
like localhost/reference/projectfolder/index.php and a reference named
"projectfolder" in the database, it will load the content even if I
have not asked for index.php?reference=projectfolder
if you want the document to be empty when you are requesting just index.php, check if $_GET["reference"] is set and then return an empty body.
From your experience, what is the best solution in my case: be able to
get PHP/MySQL data to use with Javascript. Ajax seems to be the best
way but as you can see it's not clean, at least my solution.
Check this gist on how to return JSON in your body https://gist.github.com/2627924
Related
I am looking for the method that allows to modify a value/text on my home page with the used link.
For example, if the URL is mywebsite.com/index.php?name=Mike
somewhere on my website, it will say
"Welcome Mike"
If the URL is mywebsite.com/index.php?name=Mark, it will automatically change to
"Welcome Mark"
without changing anything in my code.
Is it possible with HTML only or do I need PHP?
This is possible with HTML, but you need JavaScript. Here's an example:
// Find the query
let query = window.location.search;
// Extract the name
let match = query.match(/name=([^&]+)/);
// If the name exist, put it in the body
if (match) document.body.innerHTML = match[1];
Note that this won't work here, but it will work in the website.
As #JNa0 said, PHP is better suited to this task. The PHP would look like echo $_GET["name"];
You may do it with JavaScript by reading location.search and parse it then modify the DOM (see #AlexH’s answer), but that would be overkilled for such a task. Prefer PHP (or any server-side system) when possible.
I'm trying out Azure Functions using PHP.
Getting the request information is not working for me.
I've not been able to find any documentation at all with the information of how to use Azure Functions with PHP code.
According to the only couple of examples, it seems that in order to retrieve the input information you need to first get the content of the req variable (or whatever name you assign in the function configuration).
That has the path of the file containing the request information (in theory).
$input_path = getenv('req');
So far, if I check the content of it, I get something like this:
D:\local\Temp\Functions\Binding\e2b6e195-02f7-481b-a279-eef6f82bc7b4\req
If I check if the file exists it says true, but the file size is 0.
Do anyone knows what to do here? Anyone with an example? Does anyone know where the documentation is?
Thanks
Ok, unfortunately there's pretty limited documentation out there for php as you have discovered.
At present, looking at the code might be the best doc. Here is the InitializeHttpRequestEnvironmentVariables function that adds request metadata to the environment for the script languages (node, powershell, php, python).
Important environment variables are:
REQ_ORIGINAL_URL
REQ_METHOD
REQ_QUERY
REQ_QUERY_<queryname>
REQ_HEADERS_<headername>
REQ_PARAMS_<paramname>
I'm assuming you've made a GET request, in which case there is no content (req is an empty file), but you will see that these other environment variables contain request data. If you were to make a POST request with a body then req would have data.
here is a full example parsing a GET request in PHP with an Azure Function :)
https://www.lieben.nu/liebensraum/2017/08/parsing-a-get-request-in-php-with-an-azure-function/
snippet from source:
<?php
//retrieve original GET string
$getReqString = getenv('REQ_QUERY');
//remove the ? for the parse_str function
$getReqString = substr($getReqString,1,strlen($getReqString));
//convert the GET string to an array
$parsedRequest = array();
parse_str($getReqString,$parsedRequest);
//show contents of the new array
print_r($parsedRequest);
//show the value of a GET variable
echo $parsedRequest["code"];
?>
Setup:
Script that generates word images from multiple letter images
(autotext.php)
URL is formatted:
www.whatever.com/autotext.php?text=hello%20world
Script that alters images server-side to run filters or generate
smaller sizes (thumbnail.php)
URL is formatted:
www.whatever.com/thumbnail.php?src=whatever.png&h=XXX&w=XXX
Use-case:
I want to generate a smaller version of the autotext server-side. So my call would look something like:
www.whatever.com/thumbnail.php?src=autotext.php?text=hello%20world&h=XXX&w=XXX
As you can see, I would like to treat a URL with _GET variables as a variable itself. No amount of playing with URI encoding has helped make this work.
I have access to the PHP for both scripts, and can make some simple alterations if that's the only solution. Any help or advice would be appreciated. I would not even rule out a Javascript frontend solution, though my preference is to utilize the two scripts I already have implemented.
You should be able to do this by urlencoding all the $_GET params into a variable then assigning that variable to another, like this (untested):
// Url generation
$url = www.whatever.com/thumbnail.php?src=(urlencode(http_build_query($_GET)));
Then you should be able to retrieve on other side:
$src = urldecode(explode('&', $_GET['src']));
I've seen this exact behavior when trapping where to redirect a user, after an action occurs.
---- Update ----
Your "use case" url was correct:
www.whatever.com/thumbnail.php?src=autotext.php?text=hello%20world&h=XXX&w=XXX
.... except that you CANNOT have more than one ? within a "valid" url. So if you convert the 2nd ? to a &, you should then be able to access $_GET['text'] from the autotext.php script, then you can urldecode it to get the contents.
In Laravel, CodeIgniter etc we do have the function to set some data in the Session for 1 request.
Does something like this exist for Zend? Should one even want to use this or is this considered a bad example?
Of course I know about the flashMessenger, but this is only intended for messages as the name says already. I googled about it alot, but cannot seem to find anything related to this topic.
So, to be clear, I want to know the following:
Is it a bad example or habit to use the session for data that is just used one request?
Does Zend Framework 2 include something like a (Laravel example) Session::flashdata($key, $value) ?
To store any data within a session in ZF2 you can (or rather should) use an instance of Zend\Session\Container.
Each 'container' accepts a 'namespace' parameter that allows you to maintain session information independently between containers.
For instance the Zend\Mvc\Controller\Plugin\FlashMessenger that you have mentioned internally uses a session container with a specific namespace, FlashMessenger.
You can create and add any data to a session container (Check out the Session Storage for more info, the default is Zend\Session\Storage\ArrayStorage)
use Zend\Session\Container;
$container = new Container('my_custom_namespace');
$container->foo = array('bar');
$container->hello = 'test';
Edit (Tabs)
The issue you will have with tabs is when you click on a new tab you will not be sending a new HTTP request (unless you use AJAX). Therefore you will need to either store the current tab in local storage or a cookie from javascript.
You can also pass the current tab via GET or POST parameters. I personally append to the HTML anchor # between requests (rather than storing it within sessions).
A basic example might be
// Append the currently selected tab in the anchor
$(document).on('shown.bs.tab', 'ul.nav-tabs > li > a', function (e) {
window.location.hash = $(e.target).attr("href").substr(1);
});
// check if there is already a value and display that tab
var hash = window.location.hash;
if (hash) $('.nav-tabs a[href="' + hash + '"]').tab('show');
So any URL with a anchor will show the matching tab. If you are posting from a form you can add it to the action attribute.
<form id="my-form" method="post" action="/the/form/target#tab-3">
See the namespace expiration section of the Zend Session "Advanced Usage" documentation. You can use a call to Zend_Session_Namespace::setExpirationHops(1) to emulate the 'flash' methods in Laravel.
EDIT: Sorry, I didn't realise that it had been removed in ZF2. Apparently, it does exist in ZF2, but they have moved it to the new container system, which seems to have replaced the old namespace system.
Edit: I thought about a possible solution, but I made another question as it is very specific: see AJAX proxy with PHP, is it possible?
A couple of times I've encountered this problem...
I create sites that have a certain degree of modularity. So, it is possible that there are "components" (think of a rough CMS) which carry their own PHP code, CSS, and JavaScript, all dynamically included. Think about a structure like:
{siteroot}/component/datagrid/datagrid.php
{siteroot}/component/datagrid/js/datagrid.js
{siteroot}/component/datagrid/css/datagrid.css
{siteroot}/component/datagrid/ajax/getsomedata.php
Now, the question is: for JavaScript files, and expecially AJAX calls, how do I make them context-aware with the URLs?
For example, if in datagrid.js I want to call siteroot/component/datagrid/ajax/getsomedata.php with AJAX I should write (with JQuery):
$("#ajax").load("siteroot/component/datagrid/ajax/getsomedata.php");
First problem: siteroot changes on different installations. I've managed that by including a general
var codeBase = <? echo json_encode(Config::$siteRoot); ?>
with PHP on every page, from a Config file that can be easily edited for every installation, so I can do with whatever JavaScript something like:
$("#ajax").load(codeBase + "/component/Datagrid/ajax/getsomedata.php");
What do you think of this approach?
Second problem: but I have PHP functions that return to me also the components folder, or the folder of other components. It would be nice to make the whole URL dynamic. This would account also for changes in the structure of the component if I want.
The only solution I've found is to use a .js.php dynamic Javascript. This is very unelegant, and I have to include all the framework in the JavaScript file, like:
<?php
include "../../libs/framework.php"; // get my functions...
$myUrl = Config::$siteRoot . Framework::getComponentAjaxDir("datagrid") . "/getsomedata.php";
?>
$("#ajax").load(<?=json_encode($myUrl)?>);
Another side effect is that I have to know exactly the include the path for framework.php... I don't want this so hard-codedin my ".js.php" file.
Any smart solutions about that?
As nobody answered in a suitable way, I answer to myself to provide a solution I've found out that can be useful.
The key to my solution is simple:
I create an AJAX proxy at a fixed location in my site structure, so I can use codeBase to reference the proxy from JavaScript
I call this proxy with two parameters: plugin and action, which identify a) the plugin folder in which the "real" ajax is and b) the ajax file to use, along with the other params:
$("#...").load( codeBase + "/main/ajax.php?plugin=Datagrid&action=gettable&otherparams"...)
In ajax.php I sanitize the parameters, and use plugin and action to obtain the "real" ajax file:
{serverRoot}/components/{plugin}/ajax/{action}.php
Then i simply include that file in ajax.php
To be honest your problems are realistic options and aren't that bad practice in general quite frankly.
But let's explore this a little further.
What would be the best approach is for you to have 1 main config.php file which you can then specify modules, i.e. your datagrid etc.
You could store all modules in an array variable like so:
$_SITE_PATH = "/var/www/html/";
$_HTTP_PATH = "http://example.com/";
$_MODULES_PATH = $_SITE_PATH."modules/"
$_MODULES = array(
"datagrid"=>$_MODULES_PATH."datagrid/init.php",
"something_else"=>$_MODULES_PATH."something_else/init.php"
);
Each module would have it's own directory with instantiation init.php so that it would load all it required to get going.
This way you could code as you liked and when you needed something (preferably in the header state) do something like this.
global $_MODULES;
require_once($_MODULES["datagrid"]);
Everything will be easily available as and when required without any variable path issues later down the line.