Ajax response from php is very strange. What's going on? [duplicate] - javascript

I'm using Kint via Composer in Laravel 4 by loading kint first in composer.json so that dd() is defined by kint, not laravel (suggested here).
I want to leave debug calls in my app, and disable Kint if not in the local environment. I'm successfully using config overrides for Anvard using the following structure:
/app/config/local/packages/provider/package_name/overridefile.php
Unfortunately, this is not working for Kint with the following structure:
/app/config/packages/raveren/kint/local/config.php or
/app/config/packages/raveren/kint/local/config.default.php
The Kint documentation states:
You can optionally copy the included config.default.php and rename to config.php to override default values…
…which works for me (/vendor/raveren/kint/config.php)
How do I achieve this:
without editing a file in the /vendor/ directory that will get overwritten by composer
so that kint is only enabled in the local envirnoment
I've also tried adding the following to a helpers.php file which is called before composer in /bootstrap/autoload.php as suggested here:
<?php
isset( $GLOBALS['_kint_settings'] ) or $GLOBALS['_kint_settings'] = array();
$_kintSettings = &$GLOBALS['_kint_settings'];
/** #var bool if set to false, kint will become silent, same as Kint::enabled(false) or Kint::$enabled = false */
$_kintSettings['enabled'] = false;
unset( $_kintSettings );
(but no dice :)
Any suggestions? TIA!

I'm not familiar with kint but checked the documentation and found that, to disable kint output, you may use (in runtime)
// to disable all output
Kint::enabled(false);
In Laravel you can check the environment using
$env = App::environment();
if($env == 'your_predefined_environment') {
Kint::enabled(false);
}
To configure your environment, you may check the documentation.
Update : I've setup my local environment as givel below (in bootstrap/start.php)
$env = $app->detectEnvironment(array(
'local' => array('*.dev'),
));
And in my local machine, I've setup a virtual mashine which has laravel4.dev as it's base url, so if I visit the app using laravel4.dev or laravel4.dev/logon then I can check the environment in my BaseController.php and it detects the local environment because of .dev
public function __construct()
{
if(App::environment() == 'local') {
// do something
}
}
In your case, I don't know where is the first debug/trace you used to print the output, so you should keep the environment checking and disabling the Kint code before you use any debug/trace but you may try this (if it works for you) but you can check the environment in your filter/routes files too.

Hmm.. I'm not sure if this is the ideal way to do it, but this works, and seems Laravel'ish:
// top of app/start/global.php
Kint::enabled(false);
and
// app/start/local.php
Kint::enabled(true);
(assuming you've got a local environment defined: see #TheAlpha's answer for more info)
http://laravel.com/docs/lifecycle#start-files

Related

How to pass data from the feature file to step definition file using regular expressions?

This project is using NodeJS, Cucumber, Gherkin, Selenium.
I am trying to pass either a stored value or for now, a value in this example it would be a URL from the feature file into the step definitions file through the usage of regular expressions.
An example of a feature i would like to use (< url > is my guess-work which i've seen in other examples, which doesnt seem to work)
Scenario: 0 | A User Logging In
Given I open the page with the <url>
And then also my step definitions file
Given("/^I open the page with the url? (.*)$/"), function(next){
driver.get("http://localhost:3000/login");
pageElement = driver.findElement(By.id("email"));
pageElement.sendKeys("example#email.co.uk");
next();
};
I believe my step definitions file is correct however i'm not positive.
If you need any more information about my project please let me know i am active throughout the day on stack-overflow and aim to have this working quickly.
Thank you in advance for any support,
Jack
I would try changing the regular expression in your JavaScript to a string that expects the variables you're passing into the Given statement:
Given('I open the page with the url {string}'), function(next) {
//your code
}
You can define variables in the Gherkin Given statements by stating them as they would be presented typically. For example, if you wanted to pass in a string:
Scenario: 0 | A User Logging In
Given I open the page with the url "http://localhost"
Would pass in the variable url to your javascript file and contain the string http://localhost
Same goes for integers:
Scenario: 0 | A User Logging In
Given I open the page with the url "http://localhost" and port 3000
Your javascript function will now receive 2 variables, url and port. Logging them to the console, you will see
http://localhost
3000
So I would re-arrange your code to look like the following:
Gherkin:
Scenario: 0 | A User Logging In
Given I open the page with the url "http://localhost:3000/login"
JavaScript:
Given('I open the page with the url {string}', (url, next) => {
console.log(url) // log to check the variable is being passed into the function
driver.get(url);
pageElement = driver.findElement(By.id("email"));
pageElement.sendKeys("example#email.co.uk");
next();
});
EDIT:
You can find all the documentation on this particular issue here.
A short answer below- May be useful for upcoming visitors!
The universal RegEx pattern works for all types of data in cucumber is- ([^"]*)
This is how it will go with complete step def-
#Given("^I open the page with the ([^"]*)$") //See note below *
public void yourMethodName(yourdatatType yourDataVar) {
Your Method(s) implementation using (yourDataVar)
...
}
// * Note- '^' and '$' symbols will be added automatically by cucumber in the beginning and end of any step definition respectively.

How to import constant from frontend side of Node app and use it at backend side, in POST route

Let's say I have some frontend code saved in "public/js/frontend.js":
// some jquery...
$(function() {
// ...
});
//...
const names = ['abc123', 'qwe456', 'zxc789']
const rand = names[Math.floor(Math.random() * names.length)];
document.getElementById("captcha").src=`/img/captcha_${rand}.jpg`;
and I have some backend code saved here: "controllers/registration.js"
post: async (req, res, next) => {
// ...
if (valid.value.captcha_input !== 'rand') {
// do something, i.e.
req.flash('captcha_wrong', 'Please enter the characters you see to continue.');
res.redirect('/registration');
return;
}
}
As you can see I need to export "rand" constant from "frondend.js" file and import it to "registration.js" file. The reason is I want to compare randomly picked value (from "names" array) with value entered by user, something like that:
The comparison will take place when user will click "submitt" button.
What I've tried so far:
1.
import { rand } from '../public/js/frontend';
in "registration.js", right after "npm start" command, gives me this in Terminal:
import { rand } from '../public/js/frontend';
^^^^^^
SyntaxError: Unexpected token import
2.
const { rand } = require('../public/js/frontend');
also in "registration.js", right after I click "submitt" button, gives me this in Browser:
ReferenceError: $ is not defined
3.
module.exports = rand;
in "frontend.js" gives me the same as 2.
4.
localStorage.setItem('rand', rand);
in "frontend.js" seems to work properly (with every reload of "http://localhost:5000/registration") Local Storage in Browser is updated), but
rand = localStorage.getItem('rand');
in "registration.js", right after I click "submitt" button, gives me this in Browser:
ReferenceError: localStorage is not defined
In summary, I do not know how to import "rand" constant from "frontend.js" without importing "$" - jQuery code I need for something else. And, I can not use Local Storage in backend side ("registration.js").
I will appreciate any useful hint. Thanks!
In short, value from your variable is dynamically defined on the browser, server can't know its value without your browser sending it.
There are two ways to share value between browser and server.
Sharing file
In this case value must not be dynamically generated. You can create file inside your public folder that you import into your browser JS code using either <script> tag or using bundler solution such as Webpack. Then you will be also able to require that file inside Node.js server code as well by using global.require function. Note: This case works only if value is static. (predefined)
AJAX
This is the case which fits your needs. In this case you can generate value on the client and use it on the server. Basically generate value and send HTTP request to your server which should handle request and use/store value accordingly. This allows you to use dynamic values generated in browser accessed by server.
As for your errors:
Your first error related to import keyword is because you do not use bundler (such as webpack) or type="module" property on your script tag (see here about that: https://jaketrent.com/post/import-js-module-without-dot-dot-slash/) but I would recommend using webpack due to browser compatibility.
Your browser probably knows $ is jQuery due to global import via script tag inside your html file. But on the server it doesn't exist or browser JS file that lives inside other html file where $ is not globally accessible throws this error.
global.localStorage is browser only object which doesn't exist inside Node.js, you can't use it on your server, use AJAX instead.
Basically these two JavaScript files you shared above live on different environments, one lives inside user's browser and other lives on your hosting server. To make them communicate use AJAX.

Roxy Fileman remove part of URL in returnurl

I'm attempting to get Roxy Fileman to work in my environment, however running into a little hitch. I can see the directories for images (done via a symlink) however when returning from the Roxy UI via the "select" button I'm getting a url like this:
https://images.example.com/path/to/Uploads/symlink/123/logo.png
And what I really want is:
https://images.example.com/symlink/123/logo.png
I've already put in the RETURN_URL_PREFIX, however I'm still getting the extended path whether I use a session_path_key or just the regular root (and then browse to the correct directory via the symlink).
My code for the session_path_key looks like:
<?php $_SESSION['dynamic-user-folder'] = "/path/to/Uploads/symlink/"; ?>
and my config.json:
"FILES_ROOT": "",
"RETURN_URL_PREFIX": "https://images.example.com/",
"SESSION_PATH_KEY": "dynamic-user-folder",
Ok, I found the answer. In the plugin php folder there is a file called filelist.php. In here I simply added a
$fullPath = str_replace('/path/to/Uploads/', '', $fullPath);
And this returns the path variable p with all of the stuff I don't want removed back to the UI, so when you do a select it uses the correct URL with the RETURN_URL_PREFIX in front and then the symlink and file name.

elFinder override 'rm' PHP

I am using elFinder to manage assets for a web site and it's default functionality works great; however I need to add some additional logic to several of the PHP functions which resides in on of my Controllers.
The place that I would like the logic to be added is <elfinder_Dir>/PHP/elFinderVolumeLocalFileSystem.php specifically in the function _unlink($path) before a file is actually removed I would like to call out to another class to destroy the database entries for this asset.
The original function looks like this:
protected function _unlink($path) {
return #unlink($path);
}
When I try to add code like the following:
protected function _unlink($path) {
var_dump($path);
return #unlink($path);
}
OR
//top of file...
use controllers\ResourceManager;
//OR
//include <pathToResourceManager>
//...
protected function _unlink($path) {
ResourceManager::delteFromDB();
return #unlink($path);
}
I receive this alert on the screen:
I also noticed that when that message is given, the header in my "Network" tab shows a Response Header Content-type of text/html instead of application/json as expected by the JS portion of elFinder.
Why is the header Content-type being changed when I add custom logic?
Is there a better way to add this functionality to the project?
The answer to my question turned out to be pretty straight forward.
1) error_reporting(0); was squashing all of my errors related to using the proper namespace-ing for my files, I changed this to error_reporting(E_ALL) so I could see the real problem.
2) The files needed to be added to a namespace, since I used the same namespace I did not have any extra include_once() calls.
Next I had to add replace this line:
$class = 'elFinderVolume'.(isset($o['driver']) ? $o['driver'] : '');
With:
$class = __NAMESPACE__ . '\\elFinderVolume'.(isset($o['driver']) ? $o['driver'] : '');
Which allows the driver (which is now in the namespace) to be loaded properly.
Once these changes were made, all is well, I can add my own logic where I please.

Symfony2 routing with dynamic javascript - OR - installing FOSJsRoutingBundle

I'm trying to find the best way to deal with dynamic routing generated through an AJAX call with Symfony2.
When a new call is made, I need the current path to be available , along with some dynamic variables that get passed into the path.
Essentially this .
A few answers have suggested putting the route into a variable within each templete , such as
<script type="text/javascript">
var productPath = {{ path("acme_myBundle_default_product" , {"magazine" : "bobscheese" , "product" : "chedderfornoobs"}) }};
</script>
The issue here is, the path rely s on variables, that won't exist at runtime (namely $magazine and $product).
A perfect solution would be FOSJsRoutingBundle it seems , but the installation doesn't seem to be up to date with the latest Symfony2 .
Installation runs fine with git submodule add git://github.com/FriendsOfSymfony/FOSJsRoutingBundle.git vendor/bundles/FOS/JsRoutingBundle
but then I think the rest of the ReadMe is out of date, following it gives me a blank screen, with no errors in the log.
So my question is , either , how to install FOSJsRoutingBundle in Symfony2.1.3 , or how best to handle client side generated URLS within Symfony2.
FOSJsRoutingBundle can be normally used in my environment(2.1.3).
Does routing go wrong?
Has it set up?
acme_myBundle_default_product:
pattern: // ...
defaults: // ...
options:
expose: true
I just went down the
<script type="text/javascript">
var basePath = 'http://www.mybaseurl.com';
</script>
Route. Not as fulfilling, but worked for me in this case.

Categories