yii how textfield input call json action - json

I have a problem when I try to call the json action
First, in yii _form.php, I've got a form including a textfield to input a name, look like below:
<div class="row">
<?php echo $form->labelEx($model,'name'); ?>
<?php echo $form>textField($model,'name'); ?>
<?php echo $form->error($model,'name'); ?>
</div>
What I want is, when I am entering character “n”, the field implements(calls) actions
that I defined in an independent json file (e.g. index.php?r=user/getuserdata),
read: {
url:"index.php?r=user/getuserdata",
dataType: "json",
type:"post"
},
in UserController.php, there is an function called "actionGetUserData()",
which tells the details what this action exactly do.
public function actionGetUserData(){
$amount = User::model()->findAll("1 = 1 order by id DESC"); //為了排序
$count = count($amount);
for ($i=0;$i<$count;$i++){
$arr[$i]['id'] = $amount[$i]['id'];
$arr[$i]['username'] = $amount[$i]['username'];
$arr[$i]['userpwd'] = $amount[$i]['userpwd'];
$arr[$i]['usertype'] = $amount[$i]['usertype'];
$arr[$i]['modifytime'] = $amount[$i]['modifytime'];
$arr[$i]['createtime'] = $amount[$i]['createtime'];
$arr[$i]['allowip1'] = $amount[$i]['allowip1'];
$arr[$i]['allowip2'] = $amount[$i]['allowip2'];
$arr[$i]['allowip3'] = $amount[$i]['allowip3'];
$arr[$i]['allowip4'] = $amount[$i]['allowip4'];
$arr[$i]['allowip5'] = $amount[$i]['allowip5'];
/* $arr[$i][] = $amount[$i]->attributes; */
/* echo "<pre>";
print_r($amount[$i]->attributes);
echo "</pre>"; */
}
$result = json_encode($arr);
echo $result;
}
In this case, let's ignore what the function exactly do (just an example).
I want to know, how the textfield calls/triggers the getuserdata action index.php?r=user/getuserdata in json file.
That means how to build the relationship between textfield and json file's action.
Please tell me how to make this work in yii
_form.php(textfield) triggers json file (action)

Using javascript, you can implement a function which makes an ajax to your controller actioncall based on a certain javascript event...
<?php Yii::app->clientScript->registerScript('makeAjaxCall',
'function makeAjaxCall(){
$.ajax({
url:"index.php?r=user/getuserdata",
dataType: "json",
type:"post"
/*Any Other Ajax Options here, like the beforeSend, then, done and fail callbacks*/
})
});?>
<?php echo $form->textField($model,'name',array('onblur'=>'js:makeAjaxCall();')); ?>
To achieve this, you can study about the jQuery.ajax() function and the reference for jqXHR so you can buildthe asynchronous call and how your application revolves around it..

Related

Yii2 mpdf with barcode-generator

I'm using yii2 and installed two extension : mpdf , and yii2-barcode-generator-8-types.
Both of them were installed and configured properly and working well.
But what I can't do is to load barcode into pdf.
Here is my code :
Controller :
public function actionPdf()
{
$pdf = Yii::$app->pdf;
$pdf->content = $this->renderPartial('_pdf');
echo $this->renderPartial('_pdf');exit;
return $pdf->render();
}
View :
<div id="showBarcode"></div>
<?php
use barcode\barcode\BarcodeGenerator as BarcodeGenerator;
$optionsArray = array(
'elementId'=> 'showBarcode',
'value'=> '12345678',
'type'=>'code128',
);
echo BarcodeGenerator::widget($optionsArray);
?>
And it show something like this
but If I try to delete all code inside actionPdf() and just write
return $this->render("_pdf");
it show like this:
Please help!!!
I think your controller should be this
public function actionPdf()
{
$pdf = Yii::$app->pdf;
$pdf->content = $this->renderPartial('_pdf');
return $pdf->render();
}
The row with echo $this->renderPartial('_pdf');exit; don't must be used because it prevents the program to invoke correctly the render of the pdf page. If you use this instruction you displays only the render of "html like code" page like you see in result you posted moreover immediately after this instruction you exit form action without invoking the $pdf->render.

Yii 2 use same controller method / action in multiple controllers

I have a method checking whether user is logged in in my UserController.I need the same method in all the other controllers.How can I do the same without copy pasting the code to all controllers.
The controller method looks like
public function is_logged_in() {
$session = Yii::$app->session;
$cookies = Yii::$app->request->cookies;
//print_r($session);
$session->open();
$session_cookie_name = Yii::$app->params['cookie_name_session_var'];
$logged_in = false;
//echo "-memn-".$cook_name.' is halle - ';
//print_r($_SESSION);
if(($cook_name = $session->get($session_cookie_name))) {
//echo " - <pre>";
//print_r($cookies);
//exit;
$write_cookies = Yii::$app->response->cookies;
//echo "</pre>";
//echo $cookies->getValue($cook_name).' placenta';
if($u_token = $cookies->getValue($cook_name)) {
echo "b";
if($u_token) {
echo "c";
$write_cookies->remove($cook_name);
unset($write_cookies[$cook_name]);
$session->destroy();
$session->open();
$cookie_name = sha1($u_token).time();
$session[$session_cookie_name] = $cookie_name;
$write_cookies->add(new \yii\web\Cookie([
'name' => $session[$session_cookie_name],
'value' => $u_token,
'expire' => time() + 6000000
])); // around one hour expiry time
$session->close();
$logged_in = true;
//echo $u_token;
}
}
}
if(!$logged_in) {
$session->destroy();
}
return $logged_in;
}
1) You can create own component and put this method here or place it in the model (depends on logic of that method). Component can be placed for example in components folder (by default it doesn't exist). Then just use this component in any controllers you want.
2) If this code needs to be executed before or after certain actions, you can use behaviors.
3) You can use inheritance and create your custom controller that extends from yii\web\Controller, declare this method here and extend all other controllers where are you going to use this logic from your custom one.
In addition to arogachev's answer your code actually should sit in a class that extends the User component class http://www.yiiframework.com/doc-2.0/yii-web-user.html , not even to mention that the user identity class already does everything your code does (only much, much better). It comes with isGuest function.

Parse img from RSS-feed using PHP SIMPLE HTML DOM Parser

I am trying to parse this site (to get the img-link): http://statigr.am/feed/parishilton
This is my code:
include 'parse/simple_html_dom.php';
// Create DOM from URL or file
$html = file_get_html('http://statigr.am/feed/parishilton/');
// Find all images
foreach($html->find('img') as $element)
{
echo $element->src . '<br>';
}
The script doesn't return anything! Why is that ? I want the img link.
It's because all images are inside CDATA section and parser ignores it, so the solution is
$html = file_get_html('http://statigr.am/feed/parishilton/');
$html = str_replace("<![CDATA[","",$html); // clean-up
$html = str_replace("]]>","",$html); // clean-up
$html = str_get_html($html); // re-construct the dom object
// Loop
foreach($html->find('item description img') as $el)
{
echo $el->src . "<br />";
}
Replace all CDATA from the returned content and then use str_get_html to create DOM object from that string and loop through the images. (Tested and works).
Output :
http://distilleryimage3.s3.amazonaws.com/cc25d8562c9611e3a8b922000a1f8ac2_8.jpg
http://distilleryimage7.s3.amazonaws.com/4d8e22da2c8911e3a6a022000ae81e78_8.jpg
http://distilleryimage5.s3.amazonaws.com/ce6aa38a2be711e391ae22000ae9112d_8.jpg
http://distilleryimage3.s3.amazonaws.com/d64ab4c42bc811e39cbd22000a1fafdb_8.jpg
......
......

CKeditor returning 403 when submitting certain html tags

I've created a page where I have two input textareas and I add CKeditor (ver. 4) to both of them.
The first editor works fine, I've set config.allowedContent = true; in the config.js to stop stripping tags like <script> and everything works as expected.
I have another editor right below it, same settings, same setup, I just changed the ID of the textarea field. It works when I submit normal text, but as soon as I add a <script> tag, for example, and press the submit button of the form in which the editors are in it seems to reload the page, doesn't submit any data and firebug tells me that the server returns 403.
I tried isolating the editor, adding personal configuration. Nothing. The first textarea works like a charm, second one returns 403 if the text has unsafe tags in it.
My setup is as follows, I'm using this ckeditor helper to insert the editors where I need. Page is created with CodeIgniter as you guessed.
I got a config.js file in ckeditor folder.
I'm using a regular form, nothing fancy about it. It looks like this
<form action="http://domain.com/admin/articles/edit/47" method="post">
<div id="cke_ckeditor_en_container">
<textarea cols="75" rows="7" id="ckeditor_en" name="text_en" class="input-text is-col-text"><?php echo set_value('text_en', isset($text_en) ? htmlspecialchars_decode($text_en) : ''); ?></textarea>
<?php echo display_ckeditor($ckeditor_en); ?>
</div>
<input type="submit" value="submit" />
</form>
The form has another part of html for the other editor which is the same, with changed id and other attributes, and a checkbox, nothing relevant.
And got this in my controller
public function edit(){
$this->load->helper('ckeditor');
$id = (int)$this->uri->segment(4);
if (empty($id)){
$this->session->set_flashdata('error', 'Empty ID!');
redirect('admin/articles');
}
$data = $this->articles_model->fetch_article($id);
$data['page_title'] = "Edit `" . $data['title'] . "`";
$data['form_url'] = "admin/articles/edit/" . $id;
$data['ckeditor'] = array(
'id' => 'ckeditor',
'path' => 'js/ckeditor');
$data['ckeditor_en'] = array(
'id' => 'ckeditor_en',
'path' => 'js/ckeditor');
$data['edit'] = true;
if($this->input->post('submit')){
$this->save_article("update",$id);
}
$this->load->view("admin/articles",$data);
}
private function save_article($type='insert', $id=0){
$this->load->library('form_validation');
$this->form_validation->set_rules('title','Title','trim|xss_clean|max_length[150]|min_length[1]');
$this->form_validation->set_rules('text','Text','trim');
$this->form_validation->set_rules('title_en','Title EN','trim|xss_clean|max_length[150]|min_length[1]');
$this->form_validation->set_rules('text_en','Text EN','trim');
$this->form_validation->set_rules('top_menu','Show in top menu','trim|xss_clean|max_length[1]');
if ($this->form_validation->run() === FALSE)
{
return FALSE;
}
// make sure we only pass in the fields we want
$data = array();
$data['title'] = $this->input->post('title');
$data['text'] = htmlspecialchars($this->input->post('text'));
$data['title_en'] = $this->input->post('title_en');
$data['text_en'] = htmlspecialchars($this->input->post('text_en'));
$data['url'] = $this->toAscii($this->input->post('title'));
$data['url_en'] = $this->toAscii($this->input->post('title_en'));
$data['top_menu'] = $this->input->post('top_menu');
if($type == "insert"){
$data['time'] = date("YmdHis");
}
if ($type == 'insert'){
if($this->articles_model->insert($data)){
$this->session->set_flashdata('success', 'Article added successfully!');
}else{
$this->session->set_flashdata('error', 'An error occured!');
}
}else if ($type == 'update'){
if($this->articles_model->update($id, $data)){
$this->session->set_flashdata('success', 'Article `' . $data['title'] . '` edited successfully!');
}else{
$this->session->set_flashdata('error', 'An error ecc!');
}
}
redirect("admin/articles");
}
Safety, or unsafeness, to be exact, of my code is not relevant
edit
Adding config.js for ckeditor.
CKEDITOR.editorConfig = function( config ) {
config.filebrowserBrowseUrl = '/js/kcfinder/browse.php?type=files';
config.filebrowserImageBrowseUrl = '/js/kcfinder/browse.php?type=images';
config.filebrowserFlashBrowseUrl = '/js/kcfinder/browse.php?type=flash';
config.filebrowserUploadUrl = '/js/kcfinder/upload.php?type=files';
config.filebrowserImageUploadUrl = '/js/kcfinder/upload.php?type=images';
config.filebrowserFlashUploadUrl = '/js/kcfinder/upload.php?type=flash';
config.removeButtons = 'Underline,Subscript,Superscript';
config.allowedContent = true;
// Se the most common block elements.
config.format_tags = 'p;h1;h2;h3;pre';
// Make dialogs simpler.
config.removeDialogTabs = 'image:advanced;link:advanced';
};
I'm stumped and stupified, I've got no ideas on what to do. It seems that the one input has been cursed.
Any help appreciated, thank you.
This would be the result of your mod_security rules. Depending on how strict they are they help better protect scripts from being hacked through vulnerabilities, generally those exploited via POST's.
As I understand you are trying to add something to your second textarea. And CKEditor removing some "unsafe" tags. I won't be very secure, but this can help you:
config.extraAllowedContent = '*{*}';
You will add this to your config.js. This code provides you to add anything you want. And CKEditor won't delete "unsafe" tags.
Documenation for this method
https://www.bilisimkitabi.com/403-error-on-submit-of-ckeditor
You can add to following code in your .htaccess file
#ckeditor Post 403 problem
<IfModule mod_security.c>
SecFilterEngine Off
SecFilterScanPOST Off
</IfModule>
#ckeditor Post 403 problem

Registering custom WordPress widgets

I have created a custom widget in my themes plugin directory and it seems to be working as expected but when I register a second custom widget the 1st one seems to get overridden and I no longer have access to it. Below is my code for the widgets:
add_action( 'widgets_init', create_function( '', 'register_widget( "staffWidget" );' ) );
class staffWidget extends WP_Widget{
function staffWidget() {
parent::WP_Widget(true, 'Staff');
}
function widget($args, $instance){
echo "test widget";
}
function update($new_instance, $old_instance){
return $new_instance;
}
function form($instance){
$instance = wp_parse_args( (array) $instance, array( 'title' => '' ) );
if($instance['title']){
$title = $instance['title'];
}
else{
$title = "Add title here";
}
?>
<p><label for="<?php echo $this->get_field_id('title'); ?>">Title: <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo attribute_escape($title); ?>" /></label></p>
<?php
}
}
Both widgets have this kind of code structure but with different class names and both widgets have been activated in the plugins section of the WP dashboard. Any help or suggestions would be very much appreciated. Thanks in advance :)
You are calling the class WP_Widget with the wrong parameters.
/**
* PHP5 constructor
*
* #param string $id_base Optional Base ID for the widget, lower case,
* if left empty a portion of the widget's class name will be used. Has to be unique.
* #param string $name Name for the widget displayed on the configuration page.
* #param array $widget_options Optional Passed to wp_register_sidebar_widget()
* - description: shown on the configuration page
* - classname
* #param array $control_options Optional Passed to wp_register_widget_control()
* - width: required if more than 250px
* - height: currently not used but may be needed in the future
*/
function __construct( $id_base = false, $name, $widget_options = array(), $control_options = array() ) {
If you put false (default value) or a string, it'll work. So, supposing we have a widget Staff and another Stuff, this would do:
parent::WP_Widget('staff', 'Staff', array(), array() );
parent::WP_Widget('stuff', 'Stuff', array(), array() );
Your code is using attribute_escape, which is deprecated. If you enable WP_DEBUG, you'll see the warning. Anyway, it's a good practice to develop always with it turned on.
All this indicates that you are using a bad source as example. This one is the article about custom widgets.