Giter Site home page Giter Site logo

jaxon-core's Introduction

Build Status Scrutinizer Code Quality StyleCI codecov

Latest Stable Version Total Downloads Latest Unstable Version License

The Jaxon core library

Jaxon is an open source PHP library for easily creating Ajax web applications. It allows into a web page to make direct Ajax calls to PHP classes that will in turn update its content, without reloading the entire page.

Jaxon is a fork of the Xajax PHP library.

This package is the Jaxon core library. Several plugins are provided in separate packages.

Features

  • All the Jaxon classes in a directory can be registered in one shot, possibly with a namespace.
  • The configuration settings can be loaded from a file. Supported formats are JSON, YAML and PHP.
  • The library provides pagination feature out of the box.
  • The library is modular, and consists of a core package and several plugin packages.
  • The javascript library is provided in a separated and javascript-only package, loaded by default from the jsDelivr CDN.
  • The generated javascript classes are named according to their namespace or the subdirectory where they are located.
  • All PHP packages install with Composer, are fully namespaced, and implement PSR-4 autoloading.
  • The library natively implements Ajax file upload.
  • Up to version 3, the library runs on PHP versions 5.4 to 7.X. The version 4 runs on PHP versions 7.1 to 8.X.

Documentation

The project documentation is available in English and French.

Some sample codes (only for version 2.x) are provided in the jaxon-php/jaxon-examples package, and demonstrated in the website.

Contribute

  • Issue Tracker: github.com/jaxon-php/jaxon-core/issues
  • Source Code: github.com/jaxon-php/jaxon-core

License

The project is licensed under the BSD license.

jaxon-core's People

Contributors

albertbrufau avatar feuzeu avatar itspirit avatar scrutinizer-auto-fixer avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jaxon-core's Issues

Help with form submit; execution is not entering the registered function

First, thank you for building this library to replace xajax.

I've debugged with xdebug and the registered function is never getting entered. Any help would be greatly appreciated.

Here is the source code from the bottom of the body section of the file that shows the form:

<script type="text/javascript" src="https://cdn.jsdelivr.net/gh/jaxon-php/[email protected]/dist/jaxon.core.min.js" charset="UTF-8"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/gh/jaxon-php/[email protected]/dist/jaxon.debug.min.js" charset="UTF-8"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/gh/jaxon-php/[email protected]/dist/lang/jaxon.en.min.js" charset="UTF-8"></script>
<script type="text/javascript" charset="UTF-8">
/* <![CDATA[ */
try {
    if(typeof jaxon.config == undefined)
        jaxon.config = {};
}
catch(e) {
    jaxon = {};
    jaxon.config = {};
};

jaxon.config.requestURI = "/quick/quick_sign_up.php";
jaxon.config.statusMessages = false;
jaxon.config.waitCursor = true;
jaxon.config.version = "Jaxon 3.2.0";
jaxon.config.defaultMode = "asynchronous";
jaxon.config.defaultMethod = "POST";
jaxon.config.responseType = "JSON";



jaxon_quick_signup_controller = function() {
    return jaxon.request(
        { jxnfun: 'quick_signup_controller' },
        { parameters: arguments }
    );
};



jaxon.dom.ready(function() {





    jaxon.command.handler.register("jquery", function(args) {
        jaxon.cmd.script.execute(args);
    });
});

/* ]]> */
</script>

Jaxon Debug Window:

Thu Feb 27 2020 15:23:50 GMT-0500 (Eastern Standard Time)
CALLING:
jxnfun: quick_signup_controller

Thu Feb 27 2020 15:23:50 GMT-0500 (Eastern Standard Time)
POST: /quick/quick_sign_up.php
jxnfun=quick_signup_controller
&jxnr=1582835030493
[jxnargs] => Array
(
[0] => {"plan_type":"demo","addons":"[5]","token":"0","ssn":"","stype":"quick","first_name":"a","last_name":"b","company_name":"c","email":"d","user_name":"e","password":"f","submit-btn":"Sign Me Up"}
)

/quick/quick_sign_up.php

<?php

require '../vendor/autoload.php';
use Jaxon\Response\Response;

function jaxon_quick_signup_controller($post){

    $response = new Response;

    $response->script('console.log("Im here!");');
    
    return $response;
}

logging the $_POST prior to the above function shows:

$_POST = Array
(
[jxnfun] => quick_signup_controller
[jxnr] => 1582834765016
[jxnargs] => Array
(
[0] => {"plan_type":"demo","addons":"[5]","token":"0","ssn":"","stype":"quick","first_name":"","last_name":"","company_name":"","email":"","user_name":"","password":"","submit-btn":"Sign Me Up"}
)

)

Composer Version mismatch?

I updated my jaxon lib via composer today. I'm still on version 2.2.x

The update process worked fine.
- Updating jaxon-php/jaxon-core (v2.2.14 => v2.2.15): Downloading (100%)

After this I got the error "Call to undefined method Jaxon\Jaxon::readPhpConfigFile()" in my application. I looked in the code and there are a LOT of changes. I think, I got the version 3.x from composer instead of v.2.2.x. This is line 49 from Jaxon.php.
private $sVersion = 'Jaxon 3.2.0';

My composer.json has this line:
"jaxon-php/jaxon-core": "^2.2",

I tried to delete and reinstall jaxon but I get the v3.2. every time. Can you have a look into this please? It looks like a version mismatch in composer.

Question on registering a function to receive form data and files

Hello There I have a question regarding registering a function that receives form data and files.

Looking at the example code, how must be a function registered in order to be able to receive form data and also files?

I cannot change the structure of the app, and the upload documentation won't give me any hint on how to do this given the app structure.

I tried several tests but failed...

(The example code has been reduced to the important stucture of the web app in order to give context to the question)

The example Jaxon controller

	require_once ($_SERVER['DOCUMENT_ROOT']. '/vendor/autoload.php');
	require_once ($_SERVER['DOCUMENT_ROOT']. '/myIncludedFiles.php');
	
	use Jaxon\Jaxon;
	use Jaxon\Response\Response;
	$jaxon = jaxon();

	$jaxon->setOption('js.lib.uri', '/src');
	$jaxon->setOption('js.app.minify', true);
       
	$jaxon->register(Jaxon\Jaxon::USER_FUNCTION, 'myFunction');
	## How would it be in order to register a function that receives form data and files?


	$jaxon->processRequest(); 

	function myFunction( $formData ){
		$jxnr = new Jaxon\Response\Response();
		$jxnr->setReturnValue($formData );		
		$jxnr->script(" console.log('debugging in browser console...') ");
		return $jxnr;
	}

	$smarty->assign('jxn_js', $jaxon->getJs());
	$smarty->assign('jxn_getScript', $jaxon->getScript() );
	$smarty->assign('jxn_getCss', $jaxon->getCss());

The example html

<form id="myForm" name="myForm">
	<input id="someText" name="someText" type="text">    
	<input type="file" id="upload_example" name="example_file" />
</form>

<script>
	jaxon_myFunction(jaxon.getFormValues('myForm'));
</script>

Response ConfirmCommands not Working

When I try to use confirmCommands in a Jaxon Response, like this:

	public function hello() {
		
		$response = new Response();          // Instance the response class
			
		$texto = "¿Confirm?";
		$response->confirmCommands(1, $texto);
		$texto = "Hello World";
		$response->alert($texto);
		
		return $response;                    // Return the response to the jaxon engine
	}	

I get next error:

TypeError: jaxon.tools.queue.process is not a function
    at Array.jaxon.confirm.commands [as cc] (3bf211d89c3cda5608c467b2a04ec1e3.js:54)
    at Object.call (jaxon.core.min.js:1)
    at Object.execute (jaxon.core.min.js:1)
    at Object.process (jaxon.core.min.js:1)
    at json (jaxon.core.min.js:1)
    at Object.received (jaxon.core.min.js:1)
    at XMLHttpRequest.asynchronous.e.mode.e.request.onreadystatechange (jaxon.core.min.js:1)

In generated Script:
if(confirm(msg)){jaxon.confirm.skip(command);jaxon.tools.queue.process(command.response);}else{jaxon.tools.queue.process(command.response);};

I solved editing Plugin/Manager.php, replacing code:

        $sYesScript = 'jaxon.confirm.skip(command);jaxon.tools.queue.process(command.response)';
        $sNoScript = 'jaxon.tools.queue.process(command.response)';

with this:

        $sNoScript = 'jaxon.confirm.skip(command);jaxon.ajax.response.process(command.response)';
        $sYesScript = 'jaxon.ajax.response.process(command.response)';

Unable to submit form

Hi!

Plz check this code:

<?php
	require_once ('vendor/autoload.php');	

	$jaxon = jaxon();
	$jaxon->setOption('core.request.uri', $_SERVER['REQUEST_URI'] );

	if ( $jaxon->canProcessRequest() == true ) {
		print "<h1>CanProcess</h1>";
	}
	else {		
		print "<h1>Normal Call</h1>";			
	}	
?>

<form action="" method="post" enctype="multipart/form-data">
	<input id="someText" name="someText" type="text"><br>
	<input type="file" id="upload_example" name="example_file" /><br>
	<br>
	<input type="submit" name="cmdSave" id="cmdSave" value="GO">
</form>

When you just press "GO" the canProcessRequest call will return true. But as you can see there isn't any registered methode which should handle an upload. Jaxon should not handle file uploads when there isn't any registered methode with 'upload'.

I think it would be even better if fhe FileUpload Plugin ist not not registered as default or there should be a way to unregister/disable the plugin.

Thanks.

namespace

PHP Parse error: syntax error, unexpected 'namespace' (T_NAMESPACE) in /public_html/inc/vendor/jaxon-php/jaxon-core/src/Request/Plugin/BrowserEvent.php on line 1

This error occurs , I think it is the version of php so change 5.4 to 5.6 and continues to error.

synchronous jaxon request

Request is now working.
But if I make a synchronous request, I got a result from server, but the return Value of jaxon.request() is false and not the return value from server.
My call:
var html = jaxon.request( { jxnfun: 'user_action' }, { parameters: ['default',tpl] }, { mode: 'synchronous' });

Question about migrating from xajax: synchronous call to javascript xajax.request()

Hello,

First, I want to thank you that you have updated the project xajax and you have adapted and improved.

I am updating an old project that uses xajax for form validation.

I use this function, which calls a function registered in xajax with the name xajax_FormName.

function formValidate(frmName)
{
	frm=document.forms[frmName];

	var isValid=xajax.request({xjxfun:"xajax_"+frmName},{parameters:[xajax.getFormValues(frm.name,true)],mode:'synchronous'});

	if(isValid)
		frm.submit();

	return isValid;
}

What is the equivalent jaxon call for this line?

	var isValid=xajax.request({xjxfun:"xajax_"+frmName},{parameters:[xajax.getFormValues(frm.name,true)],mode:'synchronous'});

Thanks, I have not found any similar example in the documentation

Problem with calling registered functions

If I call a registered function nothing happens. With the old xajax it is working.
I register the function on this way.

$this->jaxon->register(Jaxon::USER_FUNCTION, array('appaction', $this, 'appaction') );

and jaxon write it right in the js.

jaxon_appaction = function() {
return jaxon.request(
{ jxnfun: 'appaction' },
{ parameters: arguments }
);
};

My firephp output:

JAXON::__construct()
Application::__construct()
USER::__construct()
Application::__construct() -> jaxon->processRequest();

But the Request will not be processed.
My question is, must I change my application to the namespace model, so jaxon can call my function?
Or should I go step by step through the Jaxon classes,with firephp , to find out why my function not called?

regards,
Joc

How to set properties of a response object

I have upgraded to Version 3.2 of jaxon and saw that registering a CALLABLE_OBJECT isn't possible any longer.
In my code I use descendants of the Response-Object with some properties that needed to be set (depending on the page where they are used) and now I don't know how to do this.

JAXON - SyntaxError: Unexpected token '<'

Hello. I am trying to use Jaxon instead Xajax because I am migrating to PHP 7+ but I am facing a very strange issue.
Everything seems to be right, the jquery is being injected correctly inside the page and my class or function are also being registered.
The problem is when I generate the event that will trigger my function and create the $response.
As soon as $response = new Response() is executed a syntax error from json (jaxon.core.min.js:1) are reported.
the exact point where the error is reported is right at T+ in this part of the json string.
responseText+")")}catch(e){throw e}
I am here asking for a help to find an answer for this strange issue.
thank you very much.

Question on invalid request

Hi Thierry,
thank you for the hint with alias for synchronous and asynchronous calls, that was a good one.

How can I handle this error?
"Uncaught Jaxon\Exception\Error: Invalid function request received"
I tried it with
$this->jaxon->register(Jaxon::PROCESSING_EVENT, Jaxon::PROCESSING_EVENT_INVALID, array( $this, 'error_handler') );
in front of
$this->jaxon->processRequest();
But that doesn't work.

regards,
Joc

Your opinions about file upload

Hi All,
I've started implementing Ajax file upload in the library, and I need help to have the feature tested on various browsers, and I also need opinions about the feature, and the support of older browsers.

I've managed to make the feature as simple as possible, and here's how it works.
First of all, the id of the input file field is passed to Jaxon when registering the PHP class or function that will handle the uploaded file. The uploaded file in the above example is processed by the Upload::saveFile() method.

jaxon()->setOption('upload.default.dir', '/dir/where/to/save/uploaded/files');
jaxon()->register(Jaxon::CALLABLE_OBJECT, new Upload(), array(
    'saveFile' => array('upload' => "'input-file-id'"),
));

When the corresponding js function will be called in the browser, Jaxon will upload the files and save them in a configured directory.
Then, the uploaded files are available in the Jaxon class using the jaxon()->getUploadedFiles() call which returns an array of UploadedFile objects.

class Upload
{
  public function saveFile()
  {
    $response = new Response;
    $uploadedFiles = jaxon()->getUploadedFiles();
    // Do anything necessary with the uploaded files
    return $response;
  }
}

For this code to work, you will need to install the master branches of both the jaxon-js and the jaxon-core libraries. They have not been tagged yet.

This code will work only if the js FormData object is implemented in the browser. This raises a question about the support for older browsers which may not have the js FormData object available, which is usually implemented with iframes. In your opinion, is it a strong requirement to have older browsers supported with this feature?

Thanks for your help.

Hello with old commands from xajax to jaxon

Hello, I am migrating from xajax to jaxon and until now everything is fine, but something appear. In the past I used this command:

xajax.callback.global.onRequest = javascriptfunction1;
xajax.callback.global.onComplete = javascriptfunction2;

is there options for this in jaxon? Well I am thinking about this

$jaxon->register(Jaxon::PROCESSING_EVENT, Jaxon::PROCESSING_EVENT_BEFORE, 'functionName');
$jaxon->register(Jaxon::PROCESSING_EVENT, Jaxon::PROCESSING_EVENT_AFTER, 'functionName');

Thanks for the info...

Jaxon does not get installed

Jaxon does not get installed. The jproof/jybrid is an empty repo.


composer require jaxon-php/jaxon-core:~2.0
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 6 installs, 0 updates, 0 removals
  - Installing jproof/jybrid (0.7.7): Downloading (0%)    Failed to download jpr
oof/jybrid from dist: The "https://codeload.github.com/JProof/jybrid/legacy.zip/
7f0cdb43e5f0c62df9be7523b5861dc46e569b8c" file could not be downloaded (HTTP/1.1
 404 Not Found)
    Now trying to download from source
  - Installing jproof/jybrid (0.7.7): Cloning 7f0cdb43e5 from cache
    7f0cdb43e5f0c62df9be7523b5861dc46e569b8c is gone (history was rewritten?)


  [RuntimeException]
  Failed to execute git checkout "7f0cdb43e5f0c62df9be7523b5861dc46e569b8c" -
  - && git reset --hard "7f0cdb43e5f0c62df9be7523b5861dc46e569b8c" --

  fatal: reference is not a tree: 7f0cdb43e5f0c62df9be7523b5861dc46e569b8c


require [--dev] [--prefer-source] [--prefer-dist] [--no-progress] [--no-suggest]
 [--no-update] [--no-scripts] [--update-no-dev] [--update-with-dependencies] [--
update-with-all-dependencies] [--ignore-platform-reqs] [--prefer-stable] [--pref
er-lowest] [--sort-packages] [-o|--optimize-autoloader] [-a|--classmap-authorita
tive] [--apcu-autoloader] [--] [<packages>]...

Encode the response to utf-8 before calling json_encode()

If the response commands have strings encoded in with a different encoding of utf-8. The method Response\Response-getOutput() fails silently because of the call to json_encode(), and return a null value instead a json.

Putting $jaxon->setOption('core.decode_utf8',true); does not seems to solve the problem

Version 3.x

Hi all,

I've started working on the 3.x version of the Jaxon library, and there's already a few beta releases. It's still an ongoing work, and I would like to share the main features that are expected in the next releases.

All comments and suggestions are welcome.

  1. Lightweight class registration

Until now, registering a user callable object with jaxon actually means creating an instance of both the class and the CallableObject, which is the wrapper class Jaxon internally uses to generate Javascript code and handle Ajax requests.

$jaxon->register(Jaxon::CALLABLE_OBJECT, new FirstClass());
$jaxon->register(Jaxon::CALLABLE_OBJECT, new SecondClass());
$jaxon->register(Jaxon::CALLABLE_OBJECT, new ThirdClass());

When using the jaxon-armada or any framework integration package, we had to avoid registering the classes when processing a request, since only the requested class actually needs to be instanciated.

if($armada->canProcessRequest())
{
    // Process the request
    $armada->processRequest();
}
else
{
    // Register all the classes. Then they are all instanciated.
    $armada->register();
}

In the 3.x version, the user registers classes instead of objects, and Jaxon will instanciate them when needed.

$jaxon->register(Jaxon::CALLABLE_CLASS, 'FirstClass');
$jaxon->register(Jaxon::CALLABLE_CLASS, 'SecondClass');
$jaxon->register(Jaxon::CALLABLE_CLASS, 'ThirdClass');

Directories will also be registered the same way, with no object created until it is actually needed.

$jaxon->register(Jaxon::CALLABLE_DIR, '/path/to/the/first/dir/');
// With namespace
$jaxon->register(Jaxon::CALLABLE_DIR, '/path/to/the/second/dir/', ['namespace' => 'Ns\Jaxon\Second']);

The same will apply to jaxon-armada or any framework integration package.

// Register the classes. No object is created.
$armada->register();
if($armada->canProcessRequest())
{
    // Process the request. Only the requested object is created.
    $armada->processRequest();
}
  1. Dependency injection

This feature is already implemented in the latest release https://www.jaxon-php.org/docs/advanced/dependency-injection.html.

The next releases will take the feature a step further by allowing the use of third party dependencies. For example when using the Laravel framework, the user will be able to inject Laravel dependencies in Jaxon classes with no extra cost.

  1. Config based registration

This feature will let the user specify the functions, classes and namespaces to register in a config file, instead on manually listing them in the code.
Until now, only the jaxon-sentry -based packages could benefit from this feature.

  1. Packages

This may be the most important feature planned in the next releases, and also the most hard to implement.

A Jaxon package bundles a set of classes and templates, and implements all the features needed to provide a service, including the required user interfaces.
After installing a Composer package, setting some config options and adding a couple of lines in a template, the user will be able to gain access to a service from a new or an existing application.

I need your comments

Please let me know if there's any feature you would like to see in the next releases, if you foresee any issue with the planned features, or if you have any questions.

Thank you.

Before processing the request bug?

Hello,

Thank You for updating Xajax!

I'm using Jaxon throughout the website and it's working fine everywhere. I needed help with this callback, either it's not working right or I'm misunderstanding something. The code below is located in the same file where all of the PHP functions are registered with Jaxon.

use Jaxon\Jaxon;
use Jaxon\Response\Response;
$jaxon = jaxon();

require_once $_SERVER['DOCUMENT_ROOT'] . '/configs/ajax_setup.php';

$jaxon->callback()->before(function($target, &$bEndRequest) {
	// Some business logic (user's session expired or app is offline)
	if (! business_logic){
		$objResponse = new Response();
		$objResponse->alert("We're offline now.");
		$bEndRequest = true;
		return $objResponse;
	}
});

other functions registered here

if($jaxon->canProcessRequest())
{
    $jaxon->processRequest();
}

The docs state:
The boolean parameter $bEndRequest is passed by reference. Its initial value is false, and if it is assigned the value true in the callback, the request processing is stopped, and the returned response is sent back to the browser.

But the Debug Output Shows:
RECEIVED [status: 200, size: 13 bytes, time: 84ms]:
{"jxnobj":[]}

Shouldn't the JavaScript response be returned or am I doing something wrong?

Using: "jaxon-php/jaxon-core": "~3.2" in vanilla PHP project.

trim requires string, array given

Installed Jaxon V 2.2.6 with composer.
In my base class i register my dispatch method with:
$this->jaxon->register(Jaxon::USER_FUNCTION, array($this, 'dispatch'));

Would not work - returned fatal trim() requires string from Request/Plugin/UserFunction.php at line 89.

        if($sType == Jaxon::USER_FUNCTION)
        {
            //Was: $xUserFunction = trim($aArgs[1]); <<---Problem
            $xUserFunction = $aArgs[1];   //Removed the trim call 7/24/19 to allow array like 
             array($this, 'method')
            if(!($xUserFunction instanceof \Jaxon\Request\Support\UserFunction))
                $xUserFunction = new \Jaxon\Request\Support\UserFunction($xUserFunction);

Request/Support/UserFunction class allows array( &myObj, 'myMethod') and now it works as advertised.

Question about get debug messages on a browser window

Hello,

When i set $jaxon->setOption('core.debug.on', true); some times I get the messages on a new browser window, but another times, I get the Messages sequentially as alerts box.

I do not know why this happens. Is there any way to always force the browser window for debugging messages?

Thank you

Notice: Array to string conversion in CallableFunction.php - getHash()

Hello!

I've just change Jaxon configuration to export JS code to an external file. Everything seems to work fine, but i'm getting this Notice on every page:

Notice: Array to string conversion in C:\xxx\vendor\jaxon-php\jaxon-core\src\Request\Plugin\CallableFunction.php on line 147
Method: getHash()

My $this->aFunctions contains this Array:
Array ( [uploadFile] => Array ( [upload] => 'file-input' ) )

Thanks in advance

response->append clears form values when dinamically adding more form elements

In my Smarty + Jaxon app I have the following issue:
(not using jaxon-smarty)

jaxon.php = Jaxon 2.0-beta.25
jaxon.core.js = jaxon.core.js 327 2007-02-28 16:55:26Z

When I want to append a new row of form elements to my form, all previous form values get cleared,

this is my demo code:

$jxnr = new Jaxon\Response\Response();
$template = $smarty->fetch('file:[sub]newFormRow.html');
$jxnr->append("formBox","innerHTML",$template);

If I create a string with all the template html code and then I append it to the element using jquery, it works:

//$jxnr->append("formBox","innerHTML",$template);
$jxnr-&gt;script(" $('#formBox').append( '".$str_template."' ); ");

Can this be a jaxon issue?

Fuelphp

How about it to make a axon library integration (package) for the Fuelphp 1.8/ 1.9 dev framework ?

jaxon.debug - load error message

From @nevtag on December 15, 2016 8:40

Hi,
I get this message, if I enable debug.
The message is only on the first page call, allways.

The jaxon.debug javascript component could not be included. Perhaps the URL is incorrect?
URL: /js/jaxon/jaxon.debug.min.js

After that, debug is working.
Looks like jaxon.debug.isLoaded isn't set, at the time you make the try check, if(jaxon.debug.isLoaded)

regards
Joc

Copied from original issue: jaxon-php/jaxon-js#1

Decoding UTF-8 parameters from FormValues

Configured Charset ISO-8859-1 with decode_utf8 enabled:

$jaxon->setOption('core.encoding', 'ISO-8859-1');
$jaxon->setOption('core.decode_utf8', true);

I make a Jaxon Request with rq()->form(), like this:

<form id="formulario">
    <!-- The crux of this page -->
    Enter your name:
    <input type="text" name="username" id="username" />
    <input type="button" value="Submit" onclick=" <?php echo rq()->call('Ajax.Test.hello',rq()->form('formulario'))?>" />
</form>    

In Request/Manager.php, there is a process() method that decodes input utf-8 parameters:

$mFunction = array(&$this, '__argumentDecodeUTF8_' . $sFunction);
array_walk($this->aArgs, $mFunction);

In my case, it's calling next method:

    private function __argumentDecodeUTF8_iconv(&$mArg)
    {
        if(is_array($mArg))
        {
            foreach($mArg as $sKey => $xArg)
            {
                $sNewKey = $sKey;
                $this->__argumentDecodeUTF8_iconv($sNewKey);
                if($sNewKey != $sKey)
                {
                    $mArg[$sNewKey] = $xArg;
                    unset($mArg[$sKey]);
                    $sKey = $sNewKey;
                }
                $this->__argumentDecodeUTF8_iconv($xArg);
            }
        }
        elseif(is_string($mArg))
        {
            $mArg = iconv("UTF-8", $this->getOption('core.encoding') . '//TRANSLIT', $mArg);
        }
        error_log(print_r($mArg,true));
    }

Previous method is not working when $mArg is an Array. It decodes ok individually each $sKey and each $xArg, but at the end of the recursive function, the arguments array stay inaltered, hasn't been decoded from utf-8.

I've fixed declaring this method instead:

    private function myArgumentDecodeUTF8_iconv($mArg)
    {
    	if(is_array($mArg)) {
    		array_walk_recursive($mArg, function(&$item, $key){
    			$item = iconv("UTF-8", $this->getOption('core.encoding') . '//TRANSLIT', $item);    			
    		});
    	}
    	elseif(is_string($mArg))
    	{
    		$mArg = iconv("UTF-8", $this->getOption('core.encoding') . '//TRANSLIT', $mArg);
    	}
    	
    	return $mArg;
    }

And calling it like this:
if($sFunction == "iconv") $this->aArgs = $this->myArgumentDecodeUTF8_iconv($this->aArgs);

Error php

When I test this code :

<?php
require("vendor/autoload.php");
use Jaxon\Response\Response;

// La classe HelloWorld
class HelloWorld
{
    public function sayHello($isCaps)
    {
        $text = ($isCaps) ? 'HELLO WORLD!' : 'Hello World!';
        $response = new Response();
        $response->alert($text);
        return $response;
    }
}

// Retrouver le singleton Jaxon
$jaxon = jaxon();

// Enregistrer une instance de la classe avec Jaxon
$jaxon->register(Jaxon::CALLABLE_OBJECT, new HelloWorld()); // line 21

// Traiter la requête Jaxon, lorsqu'il y en a une
$jaxon->processRequest();

?>
<!doctype html>
<html>
<head>
    <title>Jaxon Simple Test</title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="/favicon.ico">
<?php
// Insert the Jaxon CSS code into the page
echo $jaxon->getCss();
?>    
</head>
<body>
    <input type="button" value="Submit" onclick="JaxonHelloWorld.sayHello(1);return false;" />
</body>
<?php
// Insert the Jaxon javascript code into the page
echo $jaxon->getJs();
echo $jaxon->getScript();
?>    
</html>

I have this error :
Fatal error: Uncaught Error: Class 'Jaxon' not found in /home/jaxon/www/index.php:21 Stack trace: #0 {main} thrown in /home/jaxon/www/index.php on line 21

Why ?

Error signaling from executed js

Hi!
When you use the script method of the response object to execute js code on the client, if the code fails, the behaviour might be unpredictable and, more dangerously, the client never finds out (as opposed to regular js code which shows in the console).
This is the eval function which runs the script

jaxon.js.execute = function(args) {
    args.fullName = 'execute Javascript';
    var returnValue = true;
    args.context = args.context ? args.context : {};
    args.context.jaxonDelegateCall = function() {
        	eval(args.data);
    };
    args.context.jaxonDelegateCall();
    return returnValue;
}

That eval function, in such a case, throws an exception. But


        try {
            if (false == jaxon.executeCommand(obj)) 
                return false;
        } catch (
        }

Here, it is silently discarding it.
This...

        try {
            if (false == jaxon.executeCommand(obj)) 
                return false;
        } catch (e) {
        	alert(e);
        }

...would do. (or maybe console.log(e))
Of course, there might be better approaches (callbacks to some parameterized function o even to php?), but it would not hide potential errors in response->script() code.
If you patch your code about it, please let me know to load the jaxon.core.js back from the cdn (now i'm using local copy with said patch)
Thanks!!

Using plugins

This may as well be my own fault, but I can't figure it out, so I hope you're willing to help.

I added my own request handler and added it through the \Jaxon->registerPlugin() method. When I ran this I noticed the \Jaxon\Request\Plugin\CallableObject actually handles the function instead of my own implementation.

After some debugging I discovered that in \Jaxon\Plugin\Manager called $this->aRequestPlugins, an unordered array instead of $this->aPlugins. Replacing this solved the issue (altough it is very ugly looping through all plugins instead of the request plugins).

Is it possible to order the aRequestPlugins array by priority, or is there something I'm doing wrong?

Encode Response to UTF-8 before calling json_encode()

I know this "issue" was discussed and closed in #18 , but I would like to reopen it to ask you (🙏) considering again the encoding of the Response to UTF-8 when the encoding is ISO-8859-1.

I have a lot of code migrated from XAJAX where it was not necessary to encode manually this response, and only a few lines extra in getOutput() in Response Class would be very helpful for me.

The behaviour If we forget to encode the Response is annoying because Jaxon request fails silently with no error message, even with debug enabled.

Something like this:

    public function getOutput()
    {
        $response = [
            'jxnobj' => [],
        ];
        
        if(($this->returnValue))
        {
            $response['jxnrv'] = $this->returnValue;
        }
        
        foreach($this->aCommands as $xCommand)
        {
            //25/12/2019 --> Encoding ISO-8859-1 to UTF8
            if($this->getOption('core.encoding') == 'ISO-8859-1') {
                $response['jxnobj'][] = $this->utf8_converter($xCommand);
            }
            else $response['jxnobj'][] = $xCommand;
        }
        
        return json_encode($response);
    }

With some utf converter function like this:

    private function utf8_converter($mArg)
    {
        if(is_array($mArg)) {
            array_walk_recursive($mArg, function(&$item, $key){
                if(!mb_detect_encoding($item, 'utf-8', true)){
                    $item = utf8_encode($item);
                }
            });
        }
        elseif(is_string($mArg))
        {
            $mArg = utf8_encode($mArg);
        }
        
        return $mArg;
    }

Thank you!

TypeError with new Version 2.2.0

After upgrading to new Version (2.2.0) i get these errors:

PHP Fatal error: Uncaught TypeError: Argument 1 passed to ReflectionClass::newInstanceArgs() must be of the type array, null given in /var/www/vendor/jaxon-php/jaxon-core/src/Request/Support/CallableObject.php:134

Stack trace:
#0 /var/www/vendor/jaxon-php/jaxon-core/src/Request/Support/CallableObject.php(134): ReflectionClass->newInstanceArgs(NULL)
#1 /var/www/vendor/jaxon-php/jaxon-core/src/Request/Support/CallableObject.php(158): Jaxon\Request\Support\CallableObject->setCallable()
#2 /var/www/vendor/jaxon-php/jaxon-core/src/Request/Support/CallableObject.php(374): Jaxon\Request\Support\CallableObject->getRegisteredObject()
#3 /var/www/vendor/jaxon-php/jaxon-core/src/Request/Plugin/CallableObject.php(272): Jaxon\Request\Support\CallableObject->call('changeVariation...', Array)
#4 /var/www/vendor/jaxon-php/jaxon-core/src/Plugin/Manager.php(355): Jaxon\Request\Plugin\CallableObject->processRequest()
#5 /var/www/ in /var/www/vendor/jaxon-php/jaxon-core/src/Request/Support/CallableObject.php on line 134

I made a downgrade to 2.1.5 and the Error disappeared.

Occurs on PHP 7.2.7

Performance

I am attempting to upgrade my old web-page from Xajax to Jaxon, which appears to be fairly straight forward to do. However, I ran into "performance issues": compared to the original Xajax (V0.5) Jaxon's response times are considerably slower. Like when I click on an element that called Xajax code, the response was pretty much immediate, where as with Jaxon I notice a considerable delay (feels like ~250ms). I tested with older versions, and it feels like the newer the version, the slower the response time.

Anyone else experienced this? Is there an explanation for this? Am I doing something wrong?

Incorrect jQuery value in Ajax call.

In our Jaxon class, a click handler is set on a button with this PHP code.

$this->jq('li.delete>a')->click($this->rq()->del(jq()->parent()->parent()->attr('data-id'))->confirm('Delete?'));

The following javascript code is generated.

$('li.site_delete>a').click(function(){jaxon.noty.confirm('Delete?',function(){Jaxon.App.Source.Site.del($(this).parent().parent().attr('data-id'));});})

The javascript $(this) variable is supposed to be the a link the user clicked on.
But due to the confirm function, the variable is used in a different context, making its value undefined.

Documentation - jaxon-php.org

Hi Thierry,

I try to create a response plugin, and your documentation ends where it will be interesting "create a response plugin".
I have made my own local repository for composer and that is working, my plugin will be installed in vendor.
But if the registerplugin() function was called in start.php of my plugin, I got the error that the class \xx\xx\Plugin which is in Plugin.php not found. Looks like the Plugin.php was not load. As example I used jaxon-toastr plugin.
How should I tell jaxon to load the Plugin.php ?

Can Jaxon\Response\Manager's append(Response $xResponse) be nullable?

We're former xajax users that were able to basically drop jaxon in place with the proper config.

All went well until we found a few user functions that never returned a response object. (They're just saves that don't need to do anything response wise.) I guess Xajax never had that as an implicit requirement.

However that now results in the following error in the response to the browser, although the save is successful:
Argument 1 passed to Jaxon\Response\Manager::append() must be an instance of Jaxon\Response\Response, null given

Is it possible to make it so user functions don't have to return a Response, and if none is given the code just assumes it should make a new/empty Response object, and continue?

Upload Files

I need to upload the files and have the name of the file that was sent for registration in database, would also like to rename the file to a new name and then insert into the database, how can I do that in Jaxon?

SyntaxError: JSON.parse

Hi,

I get an error even when returning a newly created empty response.

POST Response:
SyntaxError: JSON.parse: unexpected character at line 2 column 1 of the JSON data
Firefox Devconsole (JS error):
SytaxError: expected expression, got '<'

I can see the JSON array (when sending data e.g. innerHTML) but it breaks afterwards.

Specs:
Apache: 2.4
PHP: 7.0

Type hint

Hi. I've just met jaxon, and seems very promising. However, i'm getting an error that makes me doubt if i should be using it.
The error is
Default value for parameters with a class type hint can only be NULL
And the line where it takes me is
public function jQuery($sSelector = '', string $sContext = '')
(that is jaxon-php/jaxon-core/src/Module/Controller.php on line 113)

But here, it says "Type hints cannot be used with scalar types such as int or string". So, is this an error or i'm using it wrong? Can i safely remove the string hint? Is there many more around the code i should look for?
Thanks in advance!

NOTICE: Trying to access array offset on value of type null

I have a debugger running and the file Utils/URI.php keep throwing notices in line 143.

$sURL.= $aURL['path'].@$aURL['query'];

I know the @-Operator is frequently used to suppress array warnings. So, it's not really a bug. But it would be nice, if this is solved with a isset or similar, to prevent notices even on highest log level.

Preparing the next 3.2 release

Hi,

I've starting working on the 3.2 release, which will feature many changes both in the javascript and the PHP libraries.

In javascript

  • No more synchronous ajax calls. All are asynchronous, and synchronous commands will be implemented using queues. No more warning due to the use of synchronous ajax calls.
  • The confirm and alert commands will use the javascript library defined by the jaxon-dialogs plugin. The users will be able to use the library of their choice instead of the javascript's alert() and confirm().
  • The "challenge" feature will be removed. I'm not sure it's still relevant today.
  • Improve the upload without ajax so it does not need iframe anymore. Not sure if it is possible.

Some of these changes are already available on the develop branch.

In PHP

  • Replace the Container interface with the PSR-11 Container interface. The signatures are the same.
  • Rename the pr() global function. This name is already in use in the CakePHP framework.
  • Add a new confirm command which is used as follow $this->response->confirm($question, function($response) {}). The commands defined in the function are executed only if the answer to the question is ok.

Please drop a comment if there a feature you'll like to see in this release.

Hello I need help with the installation

From @bioraft-xx on April 18, 2018 14:28

Hello, I am a newbe with this and I need help, I installed Composer in my server and my developement macchine, I am using Apache 2.4 with PHP 7.2.4. Ok with composer installed in both my server and my machine I installed Jaxon.

but when I try to execute even the simple example I got this error:

Fatal error: Uncaught Error: Call to undefined function jaxon() in C:\Webprojects\Web_Authority_Framework\WebApp\test3.php:19 Stack trace: #0 {main} thrown in C:\Webprojects\Web_Authority_Framework\WebApp\test3.php on line 19

is the line $jaxon=jaxon();

I don't know what more I can do... I think I am missing somethin and I have the same error in my server and my development machine. I am migrating some code from Xajax and I need to migrate to PHP 7 and I think with Jaxon will be the way.

Please help and thanks.

Copied from original issue: jaxon-php/jaxon-js#11

Why getFormValues don't return unchecked checkboxes?

When I want to validate if a checkbox has been marked on a form, it is impossible for me because getFormValues does not return that unchecked checkboxes and my code only validates the fields that come from that function.

I know how to fix it because I already had to modify that part of the javascript code in xajax. But, apart from not be recommendable for possible changes in future updates, I'm curious to know why those fields are not returned?

Thanks

Question: callback.global

Hi Thierry,

I use xajax callback funktions in javascript.

<script type="text/javascript">
//<![CDATA[
  xajax.callback.global.onRequest = function() { $('#loading').css('display','block'); }
  xajax.callback.global.beforeResponseProcessing = function() { $('#loading').css('display','none'); }
//]]>
</script>

Have you an equivalent in jaxon?
I saw that you have callbacks pre-processing and post-processing, but that are on server.

Regards,
Joc

Boolean Arguments on Request

When I call a Jaxon Request with boolean parameter, PHP function throws an Exception "Uncaught ArgumentCountError: Too few arguments to function...."

<html>
<head></head>
<body>
<form id="formulario">
    <input type="checkbox" ID="myChk" onclick="Ajax.Test.foo4(25,this.checked)">
</form> 
</body>
</html>
class Test {	
	public function foo4($ID,$isTrue) {				
                $this->response->alert('foo function');
		return $this->response;
	}
}

Form Data is sending 2 parameters (Numeric and Boolean):
jxncls: Ajax.Test
jxnmthd: foo4
jxnr: 1577402062576
jxnargs[]: N25
jxnargs[]: Btrue

PHP throws exception:

[27-Dec-2019 00:11:20 Europe/Amsterdam] PHP Fatal error:  Uncaught ArgumentCountError: Too few arguments to function Ajax\Test::foo4(), 1 passed and exactly 2 expected in C:\x\www\x\jaxon\classes\Test.php:26
Stack trace:
#0 [internal function]: Ajax\Test->foo4(25)
#1 C:\x\www\x\vendor\jaxon-php\jaxon-core\src\Request\Support\CallableObject.php(261): ReflectionMethod->invokeArgs(Object(Ajax\Test), Array)
#2 C:\x\www\x\vendor\jaxon-php\jaxon-core\src\Request\Plugin\CallableClass.php(310): Jaxon\Request\Support\CallableObject->call('foo4', Array)
#3 C:\x\www\x\vendor\jaxon-php\jaxon-core\src\Request\Handler\Handler.php(242): Jaxon\Request\Plugin\CallableClass->processRequest()
#4 C:\x\www\x\vendor\jaxon-php\jaxon-core\src\Request\Handler\Handler.php(305): Jaxon\Request\Handler\Handler->_processRequest()
#5 C:\x\www\x\vendor\jaxon-php\jaxon-core\src\Jaxon.php(398): Jaxon\Request\Handler\Handler->processRequest()
#6 C:\x\www\lapre in C:\x\www\x\jaxon\classes\Test.php on line 26

I think the problem is on this method in Request/Handler/Argument class. Boolean values are being ignored and removed from the arguments list:

    /**
     * Decode an Jaxon request argument from UTF8
     *
     * @param array             $aDst           An array to store the decoded arguments
     * @param string            $sKey           The key of the argument being decoded
     * @param string|array      $mValue         The value of the argument being decoded
     *
     * @return void
     */
    private function _decode_utf8_argument(array &$aDst, $sKey, $mValue)
    {
        $sDestKey = $sKey;
        // Decode the key
        if(is_string($sDestKey))
        {
            $sDestKey = call_user_func($this->cUtf8Decoder, $sDestKey);
        }

        if(is_array($mValue))
        {
            $aDst[$sDestKey] = [];
            foreach($mValue as $_sKey => &$_mValue)
            {
                $this->_decode_utf8_argument($aDst[$sDestKey], $_sKey, $_mValue);
            }
        }
        elseif(is_string($mValue))
        {
            $aDst[$sDestKey] = call_user_func($this->cUtf8Decoder, $mValue);
        }
        elseif(is_numeric($mValue))
        {
            $aDst[$sDestKey] = $mValue;
        }
    }

Upgrade Jaxon-PHP from 2.0-beta.24 to 2.2.6

Hello,
i worked successful for years with xajax and afterwards with jaxon-php. The last version i worked with is Jaxon2.0-beta.24. In the meantime i changed to codeigniter as framework and could successful integrate jaxon-php (with jaxon-codeigniter).
Now i tried to update with "composer update" to the current jaxon-php (2.2.6) but have no success.
I changed the old

use Jaxon\Sentry\Classes\Base as JaxonClass;
to
use Jaxon\Sentry\Armada as JaxonClass;
and the Classes registers successful. I can call from the Javascriptconsole the functions, but the response is empty. I inserted some checkpoints into the code (in the __constructer), but they are never past. It seams that the registered functions are not called:

Jaxon.App.auswertungen_austritt_ajax.hole_liste();
false

Parameter =>

jxncls | Jaxon.App.auswertungen_austritt_ajax
jxnmthd | hole_liste
jxnr | 1570315569596

Answer => {"jxnobj":[]}
do you have a glue what i missed ?

Code:

class Auswertungen extends MY_Controller {

public function __construct()
{
parent::__construct();
// Load the Jaxon library
$this->load->library('jaxon');
}
public function Austritt() {
$this->jaxon->register();
$this->smarty->view('benutzer-listenAustritt2-index.tpl', array(
"jaxonCss" => $this->jaxon->css(),
"jaxonJs" => $this->jaxon->js(),
"jaxonScript" => $this->jaxon->script(),
));
}`

auswertungen_austritt_ajax.php

namespace Jaxon\App;

use Jaxon\Sentry\Armada as JaxonClass;
// use Jaxon\Sentry\Classes\Base as JaxonClass;

class auswertungen_austritt_ajax extends JaxonClass {
protected $ci=0;
public function __construct() {
log_message("info","__construct");
echo "HIER !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!";
parent::__construct();
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.