Jaxon doesn´t return anything on response - ajax

Please, can anyone help?
I´m starting to use jaxon 3, planning to migrate from xajax. On a php7.3 plataform, I made a simple code, just to load jaxon and run a single alert script, but its returning nothing on browser. There are no errors on server log and no info on browser, no even on the chrome debug console.
Here is the simple code:
<?php
require_once( 'Jaxon/vendor/autoload.php' );
use Jaxon\Jaxon;
use Jaxon\Response\Response;
$ajax = jaxon();
$ajax->setOption('core.debug.on', false);
$ajax->setOption('core.prefix.function', 'jaxon_');
$ajax->setOption('core.request.uri', 'ajax.php');
$objResponse = new Response();
$objResponse->alert('test');
return $objResponse;
echo 'tests';
?>
PS: I didn´t use the jaxon word on tag cause the editor doesn´t let me do it

I would tell you to delete the echo at the end, and try to code some functions even for testing, so you can better understand v3.
Here, check this code, it might help you, this code is tested and will work.
<?php
require_once ($_SERVER['DOCUMENT_ROOT'].'/vendor/autoload.php');
use Jaxon\Jaxon;
use Jaxon\Response\Response;
$jaxon = jaxon();
$jaxon->setOption('js.app.minify', TRUE);
$jaxon->setOption('js.lib.uri', '/vendor/jaxon-php/jaxon-js/dist');
/** ################################# */
/** using jaxon with just functions then you have to register each function
*
* call these functions like this:
* jaxon_demo1();
* jaxon_demo2();
*
* <button type="button" onclick="jaxon_demo1()"> call fn 1 </button>
* <button type="button" onclick="jaxon_demo2()"> call fn 2 </button>
*
*/
$jaxon->register(Jaxon::USER_FUNCTION, 'demo1');
$jaxon->register(Jaxon::USER_FUNCTION, 'demo2');
$jaxon->register(Jaxon::CALLABLE_FUNCTION, 'functionThatReturnsUsing_setReturnValue', ['mode' => "'synchronous'"]);
function demo1(){
$jaxonResponse = new Response();
$jaxonResponse->alert('Hello there, be sure to open browser console to see the console.log');
$jaxonResponse->script("console.log('Hello there')");
return $jaxonResponse;
}
function demo2(){
$jaxonResponse = new Response();
// <div id="theDiv"> this will be replaced </div>
$jaxonResponse->assign("theDiv","innerHTML",'Some content that can even be a template if you implement smarty or similar');
return $jaxonResponse;
}
/**
* check out https://github.com/jaxon-php/jaxon-js/issues/15
* this should work, take a look at the link provided
* also use the browser console to look the response data being returned
*/
function functionThatReturnsUsing_setReturnValue(){
$jaxonResponse = new Response();
// lets suppose you have a script like this
// <script>
// function demo3(){
// var myData = jaxon_functionThatReturnsUsing_setReturnValue();
// console.log(myData);
// }
// </script>
$someData = array(
'isValidated' => TRUE,
'str_data' => 'some data here',
'int_data' => 123,
'flt_data' => 1.23,
'row_data' => array(
'isValidated' => TRUE,
'str_data' => 'some data here',
'int_data' => 123,
'flt_data' => 1.23
)
);
$jaxonResponse->setReturnValue($someData);
$jaxonResponse->getOutput();
return $jaxonResponse;
}
if($jaxon->canProcessRequest()){
$jaxon->processRequest();
}
/**
* if you are using composer, then your composer.json should have this at least:
*
* {
* "require": {
* "jaxon-php/jaxon-core": "^3.2",
* "jaxon-php/jaxon-js": "^3.2"
* }
* }
*
*/
?>
<!DOCTYPE html>
<html lang="es">
<head>
<title>Demo jaxon</title>
<?php echo $jaxon->getCss(); ?>
</head>
<body>
<ul>
<li>demo fn 1</li>
<li>demo fn 2</li>
<li>demo fn 3</li>
</ul>
<div id="theDiv">this will be replaced</diV>
<script>
function demo3(){
var myData = jaxon_functionThatReturnsUsing_setReturnValue();
console.log(myData);
}
</script>
<?php
echo $jaxon->getJs();
echo $jaxon->getScript();
?>
</body>
</html>

Related

Chartisan/Laravel - > "Call to undefined method" error

I am trying to figure out how to use Chartisan and my controllers in Laravel. Having spend a couple of days on this, I have to admit that I am missing some fundamental because I understand the error, I just can't fix it..
What I have done so far is followed this https://charts.erik.cat/guide/installation.html#publish-the-configuration-file and reading multiple other guides online on how to solve it. If I stick to the guide, with the basic example then it works fine, but I want to create multiple charts, based on id/user variables which require I get the information from my database..
My problem is: "Call to undefined method App\Charts\SampleChart::labels()"
Are there anyone who has experience with this issue and tell me how to fix?
SampleChart.php (location: app/Charts/SampleChart.php)
declare(strict_types = 1);
namespace App\Charts;
use Chartisan\PHP\Chartisan;
use ConsoleTVs\Charts\BaseChart;
use Illuminate\Http\Request;
class SampleChart extends BaseChart
{
/**
* Handles the HTTP request for the given chart.
* It must always return an instance of Chartisan
* and never a string or an array.
*/
public ?string $name = 'my_chart';
public ?string $routeName = 'my_chart';
public function handler(Request $request): Chartisan
{
return Chartisan::build();
}
}
My Controller is:
namespace App\Http\Controllers;
use App\Charts\SampleChart;
use App\Charts\ExerciseInsight;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class ExerciseInsightChartController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index(Request $request): Chartisan
{
$samplechart = new Samplechart;
$exercise = 16;
$created_at = [];
$exercise_name = [];
$exercise_weight = [];
$exercise_rep = [];
$records = DB::table('dump_all_records')->where('exercise_id',"=", $exercise)->get();
foreach ($records as $record)
{
array_push($created_at, $record->created_at);
array_push($exercise_name, $record->exercise_name);
array_push($exercise_weight, $record->exercise_unit_value);
array_push($exercise_rep, $record->exercise_round_value);
}
// dd($samplechart);
$samplechart->labels($created_at);
$samplechart->dataset(['Weight','line', $exercise_weight]);
// $samplechart->dataset('Reps','line', $exercise_rep);
return view('insight.exercise_insight', compact('samplechart'));
}
}
my view is:
<!-- Charting library -->
<script src="https://unpkg.com/echarts/dist/echarts.min.js"></script>
<!-- Chartisan -->
<script src="https://unpkg.com/#chartisan/echarts/dist/chartisan_echarts.js"></script>
<!-- Chart's container -->
<div id="chart" style="height: 300px;"></div>
<script>
const chart = new Chartisan({
el: '#chart',
url: "#chart('my_chart')",
hooks: new ChartisanHooks()
.colors(['#4299E1','#FE0045','#C07EF1','#67C560','#ECC94B'])
// .datasets([{ type: 'line', fill: false }, 'bar'])
.datasets(
[
{
type: 'line',
fill: true ,fillColor : 'rgba(38,198,218,1)',
strokeColor : 'rgba(38,198,218,0)',
pointColor : '#26c6da',
pointStrokeColor : 'rgba(38,198,218,0)',
pointHighlightFill : '#fff',
pointHighlightStroke: 'rgba(38,198,218,1)',
},
{
type: 'line',
fill: true
}
]
)
.axis(true)
.tooltip()
});
</script>
Since the documentation has wroten, you can pass the data manually using data : {...} property.
So, the first step is call the Chartisan class, but don't forget to call the ServerData Class first, because the Chartisan Class constructor need parameter a ServerData Class.
In YourController.php
use Chartisan\PHP\Chartisan;
use Chartisan\PHP\ServerData;
In your method,
public function index () {
$serverdata = new ServerData;
$chart = new Chartisan($serverdata);
$chart->labels(
['First', 'Second', 'Third', 'Four', 'Five',
'Six', 'Seven', 'Eight', 'Nine', 'Ten']);
/**
* This your query will be placed,
* just for example :
*/
for ($i = 1; $i < mt_rand(5,9); $i++) {
$chart->dataset('Attribute '. $i, [
mt_rand(3,50), mt_rand(3,50), mt_rand(3,50), mt_rand(3,50), mt_rand(3,50),
mt_rand(3,50), mt_rand(3,50), mt_rand(3,50), mt_rand(3,50), mt_rand(3,50)
]);
}
/**Please remember on this chartisan version,
* Chartisan class will return an Object
* But the frontend loader just read a JSON format only.
* so it's easily to call Chartisan toJSON method.
* */
$chart = $chart->toJSON();
return view('your.view', [
'chart' => $chart,
]);
}
Next, in your blade view, this must be same scheme to load the chart according the documentation. But don't forget to escape $chart variable at blade syntax.
<script>
const chart = new Chartisan({
el: '#chart',
data: {!! $chart !!},
hooks: new ChartisanHooks()
.title({
textAlign: 'center',
left: '50%',
text: 'Example Chart Title',
})
.colors()
.datasets('line')
.axis(true)
.tooltip()
});
</script>
And the html part,
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="container">
<!-- here your chart-->
<div id="chart" style="height: 300px;"></div>
</div>
</body>
</html>
CMIIW. Hope its help.
Thank you.

Laravel Echo not receiving Pusher notifications in realtime - ideas?

I am trying to implement a user messaging approach using ideas from this site:
https://www.sitepoint.com/add-real-time-notifications-laravel-pusher/
The key idea is using the laravel notifications capability to update a notifications table (for purposes of marking off messages as read) and at same time broadcast to pusher as a private channel and listen in client via Laravel Echo.
I want to send notifications when I add a new exercise, so I use the EventServiceProvider to listen to a database create event and that is where I trigger the notification:
Exercise::created(function ($exercise) {
foreach ($users as $user) {
$user->notify(new NewExercisePosted($user, $exercise));
}
The notification:
class NewExercisePosted extends Notification implements ShouldBroadcast
{
//use Queueable;
protected $exercise;
protected $user;
public function __construct(User $user, Exercise $exercise)
{
$this->user = $user;
$this->exercise = $exercise;
}
public function via($notifiable)
{
return ['database', 'broadcast'];
}
public function toArray($notifiable)
{
return [
'id' => $this->id,
'read_at' => null,
'data' => [
'user_id' => $this->user->id,
'ex_id' => $this->exercise->id,
],
];
}
}
This is just populating the notifications table and broadcasting to pusher.
Here is my master view file:
<!DOCTYPE html>
<html>
<head>
<meta name="csrf-token" content="{{ csrf_token() }}">
<link rel="stylesheet" href="/css/app.css")/>
<script src='https://www.google.com/recaptcha/api.js'></script>
<script>
window.Laravel = <?php echo json_encode([
'csrfToken' => csrf_token(),
]); ?>
</script>
<!-- This makes the current user's id available in javascript -->
#if(!auth()->guest())
<script>
window.Laravel.userId = <?php echo auth()->user()->id; ?>
</script>
#endif
</head>
<body>
#include('partials/header')
#if(Session::has('message'))
<div class="alert alert-info">
{{Session::get('message')}}
</div>
#endif
#yield('content')
#include('partials/footer')
#include('partials/analytics')
<script src="/js/app.js"></script>
</body>
</html>
Here is the relevant part of the header view where I have the messages appear:
<li class="dropdown">
<a class="dropdown-toggle" id="notifications" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
<span class="glyphicon glyphicon-user"></span>
</a>
<ul class="dropdown-menu" aria-labelledby="notificationsMenu" id="notificationsMenu">
<li class="dropdown-header">No notifications</li>
</ul>
</li>
Here is my app.js:
require('./bootstrap');
var app = 0;
window._ = require('lodash');
window.$ = window.jQuery = require('jquery');
require('bootstrap-sass');
$(document).ready(function () {
$(function () {
$('[data-toggle="tooltip"]').tooltip()
})
});
window.Pusher = require('pusher-js');
import Echo from "laravel-echo";
const PUSHER_KEY = 'blah';
const NOTIFICATION_TYPES = {
follow: 'App\\Notifications\\UserFollowed',
newEx: 'App\\Notifications\\NewExercisePosted'
};
window.Echo = new Echo({
broadcaster: 'pusher',
key: PUSHER_KEY,
cluster: 'mt1',
encrypted: true
});
var notifications = [];
$(document).ready(function() {
// check if there's a logged in user
if(Laravel.userId) {
// load notifications from database
$.get(`/notifications`, function (data) {
addNotifications(data, "#notifications");
});
// listen to notifications from pusher
window.Echo.private(`App.User.${Laravel.userId}`)
.notification((notification) => {
addNotifications([notification], '#notifications');
});
}
});
function addNotifications(newNotifications, target) {
console.log(notifications.length);
notifications = _.concat(notifications, newNotifications);
// show only last 5 notifications
notifications.slice(0, 5);
showNotifications(notifications, target);
}
function showNotifications(notifications, target) {
if(notifications.length) {
var htmlElements = notifications.map(function (notification) {
return makeNotification(notification);
});
$(target + 'Menu').html(htmlElements.join(''));
$(target).addClass('has-notifications')
} else {
$(target + 'Menu').html('<li class="dropdown-header">No notifications</li>');
$(target).removeClass('has-notifications');
}
}
// Make a single notification string
function makeNotification(notification) {
var to = routeNotification(notification);
//console.log(to);
var notificationText = makeNotificationText(notification);
return '<li>' + notificationText + '</li>';
}
function routeNotification(notification) {
//console.log(notification.data.data.ex_id);
var to = `?read=${notification.id}`;
if(notification.type === NOTIFICATION_TYPES.follow) {
to = 'users' + to;
} else if(notification.type === NOTIFICATION_TYPES.newEx) {
const exId = notification.data.data.ex_id;
to = `guitar-lesson-ex/${exId}` + to;
}
return '/' + to;
}
function makeNotificationText(notification) {
var text = '';
if(notification.type === NOTIFICATION_TYPES.follow) {
const name = notification.data.follower_name;
text += `<strong>${name}</strong> followed you`;
} else if(notification.type === NOTIFICATION_TYPES.newEx) {
text += `New exercise posted`;
}
return text;
}
Things are working somewhat, but not quite. Messages are appearing in database and in Pusher right away after I create a new exercise, and when you click the MarkAsRead notification the notification is being marked off as read. Here is the problem:
When I create a new exercise, the client doesn't update in realtime. It only seems to produce a change when the page is refreshed.
Based on what I have above, any tips on how to fix things? I am clueless about javascript, especially about scope of variables, order of execution, etc, etc. So I suspect I have overlooked some finer points. I am a guitarist before I am a developer!
Thanks!
Brian
I spent all day yesterday trying to figure this out and in the end it came down to * vs {id}...
The problem was in the channels.php file where channel authorization is done. I was using App.User.{id} not realizing that was per 5.4 instructions when in fact for 5.3 needs to be App.User.*
I simply didn't even think to consider that! Now everything is working as expected.
thanks, Brian

Implement Viewstate in codeigniter

I´ve been working with aspnet for quite a while, and i´d like to implement aspnet viewstate with in php (exactly in codeigniter). Is there a way to implement ASP ViewState with Codeigniter ?
This answer will accomplish some of the goals of Viewstate in that is will preserve control values between form submits. If you navigate away from the page the data will be lost. But it's the same for Viewstate. The example code make heavy use of the CodeIgniter (CI) Framework.
Here is some documentation related to the parts of CI used here.
Form Validation
Form Helper
Session
The CI_Form_validation library suffers from not being able to keep validation results across a redirect. This class extends CI_Form_validation to overcome that limitation.
File: application/libraries/My_Form_validation.php
/**
* Extends CI_Form_validation to facilitate using the Post/Redirect/Get pattern for form handling.
* https://en.wikipedia.org/wiki/Post/Redirect/Get
* http://solidlystated.com/design/best-way-to-process-forms-with-php/
*
* The base class (CI_Form_validation) has the protected property $_field_data
* which holds all the information provided by form_validation->set_rules()
* and all the results gathered by form_validation->run().
* Form Helper and Form_Validation use the $_field_data to re-populate fields and present error messages.
*
* To use this class you must have CodeIgniter Session setup and working.
*
* This class stores $_field_data in session flash data for use in the controller method that is the
* redirect target.
*
* Class is handy for defining custom validation methods which will NOT require the "callback_" prefix.
*
*/
defined('BASEPATH') OR exit('No direct script access allowed');
class MY_Form_validation extends CI_Form_validation
{
public function __construct($rules = array())
{
parent :: __construct($rules);
$this->CI->load->library('session');
}
/**
* Enhanced version of form_validation->run(). Sets a $_SESSION item with the contents of $this->_field_data
*
* #param string $group The name of the validation group to run
* #param bool $persistent If TRUE save the state of $_field_data even if validation passes
* #return boolean TRUE on success and FALSE on failure
*/
public function run($group = '', $persistent = FALSE)
{
if(parent:: run($group))
{
if($persistent)
{
$this->CI->session->set_flashdata('validation_field_data', $this->_field_data);
}
return TRUE;
}
$this->CI->session->set_flashdata('validation_field_data', $this->_field_data);
return FALSE;
}
/**
* This is used in the redirect target defined in the form processing controller/method
*
* #return bool TRUE if $_SESSION['validation_field_data'] is set. It indicates that validation failed.
* Returns FALSE if there is no indication that validation has failed or even been run.
*/
public function is_failed_validation()
{
if(isset($_SESSION['validation_field_data']))
{
// Validation failed or is being persisted.
$this->_field_data = $_SESSION['validation_field_data'];
return TRUE;
}
return FALSE;
}
/**
* A validation function to cleanup strings
*
* #param string $str Value of the field
* #return string|bool The sanitized string or FALSE if filter_var() fails
*/
public function sanitize_str($str)
{
return filter_var($str, FILTER_SANITIZE_STRING);
}
/**
* A do-nothing routine assigned to any field we want included in validation results
* #return boolean
*/
public function alwaysTrue($val)
{
return TRUE;
}
}
Hopefully the comments explain what's going on. One major thing to understand is that form_validation only captures the $_POST data for controls that have validation rules. That's the reason for the "do-nothing" validation routine alwaysTrue(). Use this rule on any control where you want the values to persist.
The following controller shows a usage example.
File: application/controllers/Viewstate.php
class Viewstate extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load
->library('form_validation', NULL, 'fv') //renames 'form_validation' to 'fv'
->helper(['form', 'url']);
$this->fv->set_error_delimiters('<span class="error">', '</span>');
}
public function index()
{
$this->fv->is_failed_validation(); //captures validation data if it's there
//Define some data for consumption by CI's Form Helper functions
$data['username_field'] = [
'name' => 'username',
'id' => 'username',
'value' => $this->fv->set_value('username'),
'class' => 'your_css',
];
$data['confirm_username_field'] = [
'name' => 'usernameconf',
'id' => 'usernameconf',
'value' => $this->fv->set_value('usernameconf'),
'class' => 'your_css',
];
$data['comment_field'] = [
'name' => 'comment',
'id' => 'comment',
'value' => $this->fv->set_value('comment'),
'class' => 'comment',
];
$data['project_lead_field'] = [
'name' => 'project_lead',
'value' => 1,
'checked' => $this->fv->set_radio('project_lead', 1, FALSE)
];
$selected_status = ['None' => "None"]; //default dropdown item
$status_items = ["None" => "None", "Good" => "Good", 'Bad' => 'Bad', "Ugly" => "Ugly"];
//recover previously posted select item - if any
if($item = $this->session->validation_field_data['status']['postdata'])
{
$selected_status = [$item => $item];
}
$data['status_field'] = [
'name' => 'status',
'options' => $status_items,
'selected' => $selected_status
];
$this->load->view('testcase_view', $data);
}
/**
* This is the "action" that processes the form's posted data
*/
public function process()
{
//set rules and error messages at same time
$this->fv
->set_rules('username', 'User Name', ['trim', 'required', 'matches[usernameconf]'],
['required' => '<em>{field}</em> required.', 'matches' => "User Names don't match."])
->set_rules('usernameconf', '', ['trim', 'required'], ['required' => 'Retyping the User Name is required.'])
->set_rules('comment', "", ['trim', 'sanitize_str'])
->set_rules('project_lead', "", 'alwaysTrue')
->set_rules('status', "", 'alwaysTrue')
;
//So an uncheck checkbox will be part of the $_POST array
if(!isset($_POST['project_lead']))
{
$_POST['project_lead'] = 0;
}
if(FALSE == $this->fv->run('', TRUE))
{
redirect('viewstate');
}
else
{
//do something with field values e.g.
//$this->model->instert($_POST);
redirect('viewstate'); //to prove the page state is persistent
}
}
}
I included some actual field validation so readers can see how that works and how the validation results persist across a redirect.
Here is the view
File: application/views/textcase_view.php
<!DOCTYPE html>
<html>
<head>
<title>Test Persistent Page</title>
<style type="text/css">
p{
margin: 0;
}
.error {
color: #FF0000;
font-size: small;
}
.fld-label{
color: #555;
font-size: .9em;
}
.comment{
color: Blue;
font-weight: bold;
}
div{
margin-bottom: 1em;
}
div + .fld-label
/*div + .error*/
{
margin-bottom: 0;
}
</style>
</head>
<body>
<?= form_open('viewstate/process'); ?>
<span class="fld-label">User Name</span>
<div><?= form_input($username_field) ?>
<p><?= form_error('username'); ?></p>
</div>
<div class="fld-label">Retype User Name</div>
<div><?= form_input($confirm_username_field) ?>
<p><?= form_error('usernameconf'); ?></p>
</div>
<div class="fld-label">Comment</div>
<div><?= form_input($comment_field); ?></div>
<div class="fld-label">Project Lead?</div>
<div><?= form_checkbox($project_lead_field); ?></div>
<div class="fld-label">Status</div>
<div><?= form_dropdown($status_field); ?></div>
<p><input type="submit" value="Submit"></p>
<?= form_close(); ?>
</body>
</html>
The view makes heavy use of Form Helper functions such as form_open, form_close, form_input, etc.

Keeping modal dialog open after validation error laravel

So basically I have a blade.php, controller page and a form request page(validation). I'm trying to keep my modal dialog open if there is an error but I just cant figure it out, what part of code am I missing out on or needs to be changed?
blade.php
<div id="register" class="modal fade" role="dialog">
...
<script type="text/javascript">
if ({{ Input::old('autoOpenModal', 'false') }}) {
//JavaScript code that open up your modal.
$('#register').modal('show');
}
</script>
Controller.php
class ManageAccountsController extends Controller
{
public $userRepository;
public function __construct(UserRepository $userRepository)
{
$this->userRepository = $userRepository;
}
public function index()
{
$users = User::orderBy('name')->get();
$roles = Role::all();
return view('manage_accounts', compact('users', 'roles'));
}
public function register(StoreNewUserRequest $request)
{
// process the form here
$this->userRepository->upsert($request);
Session::flash('flash_message', 'User successfully added!');
//$input = Input::except('password', 'password_confirm');
//$input['autoOpenModal'] = 'true'; //Add the auto open indicator flag as an input.
return redirect()->back();
}
}
class UserRepository {
public function upsert($data)
{
// Now we can separate this upsert function here
$user = new User;
$user->name = $data['name'];
$user->email = $data['email'];
$user->password = Hash::make($data['password']);
$user->mobile = $data['mobile'];
$user->role_id = $data['role_id'];
// save our user
$user->save();
return $user;
}
}
request.php
class StoreNewUserRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
// create the validation rules ------------------------
return [
'name' => 'required', // just a normal required validation
'email' => 'required|email|unique:users', // required and must be unique in the user table
'password' => 'required|min:8|alpha_num',
'password_confirm' => 'required|same:password', // required and has to match the password field
'mobile' => 'required',
'role_id' => 'required'
];
}
}
Laravel automatically checks for errors in the session data and so, an $errors variable is actually always available on all your views. If you want to display a modal when there are any errors present, you can try something like this:
<script type="text/javascript">
#if (count($errors) > 0)
$('#register').modal('show');
#endif
</script>
Put If condition outside from script. This above is not working in my case
#if (count($errors) > 0)
<script type="text/javascript">
$( document ).ready(function() {
$('#exampleModal2').modal('show');
});
</script>
#endif
for possibly multiple modal windows you can expand Thomas Kim's code like following:
<script type="text/javascript">
#if ($errors->has('email_dispatcher')||$errors->has('name_dispatcher')|| ... )
$('#register_dispatcher').modal('show');
#endif
#if ($errors->has('email_driver')||$errors->has('name_driver')|| ... )
$('#register_driver').modal('show');
#endif
...
</script>
where email_dispatcher, name_dispatcher, email_driver, name_driver
are your request names being validated
just replace the name of your modal with "login-modal". To avoid error put it after the jquery file you linked or jquery initialized.
<?php if(count($login_errors)>0) : ?>
<script>
$( document ).ready(function() {
$('#login-modal').modal('show');
});
</script>
<?php endif ?>

Yii, Fancybox and ajax-loaded data

I have a link that looks like
<a class="fancy" href="/site/feedback">feedback</a>
Ajax call:
$('.fancy').fancybox({
wrapCSS: 'custom-fancy',
padding: 0,
type: 'ajax'
});
On click fancybox load content wich controller send.
$this->renderPartial('_feedback')
Feedback view:
<?php
/* #var $this Controller */
/* #var $model FeedbackForm */
/* #var $form CActiveForm */
$form = $this->beginWidget('CActiveForm', array(
'id' => 'feedback-form',
'enableClientValidation' => TRUE,
)); ?>
<div><?= $form->textArea($model, 'feedback') ?></div>
<?=$form->error($model, 'feedback')?>
<? $this->widget('CCaptcha') ?>
<?=$form->textField($model, 'verifyCode', array('placeholder' => 'Captcha code'))?>
<div><?=CHtml::submitButton('Send', array('class' => 'r button'))?></div>
<? $this->endWidget() ?>
The problem is that there is no javascript/ajax validation on this loaded form. I think, it is because some Yii scripts did not loaded after ajax call (yiiActiveForm.js maybe, I don't know).
What is the best solution for this situation?
We need to set $processOutput is true as a fourth parameter. (RenderPartial postprocess default value is false.) Then only $processOutput method will insert registered client scripts into the output at appropriate places.
$this->renderPartial('view file', array(data to be available to view file), false, true);
Well, you need to load some code with javascript
$output = $this->renderPartial('_feedback', array(), true)
// you need set layout to false for render only your form
Yii::app()->clientScript->render($output);
// where you need remove jquery for prevent double initiation's jquery script
// it's not worked example!!!
preg_replace('#<script type="text/javascript" src="jquery.js"></script>#mi', '', $output);
// well, we may output
echo $output;

Resources