Flash Builder: Get the result of HTTPService request with AS3 in Flex Mobile App - flash-builder

really drives me insane to get the results of a HTTPService object. When the call to the server is completed, a result event will be triggered.
That all is working OK and the server can serve XML data or JSON data without errors. But what to do with the event object "ResultEvent", it is not clear to me.
Let me show you some code:
<fx:Declarations>
<s:HTTPService id="hsConfig"
url="{IR_BASE_URL}/getconfig.json"
result="onGetConfig(event)"
fault="onGetConfigError(event)"
method="POST"
showBusyCursor="false"
resultFormat="array"
makeObjectsBindable="true"
>
<s:request xmlns="">
<post1>Hello</post1>
<post2>World</post2>
</s:request>
</s:HTTPService>
</fx:Declarations>
And then some actionscript:
protected function onGetConfig(e:ResultEvent):void
{
//var adata:XMLList = XML.(e.result);
var data:Object = e.result,
oo : HTTPService = (e.currentTarget as HTTPService);
trace( oo.lastResult );
trace( e.result.lastResult );
trace( data.cfg );
trace( e.result.length );
if( e.result.length )
{
trace( e.result[0].length );
}
}
xml returned by server:
<?xml version="1.0" encoding="UTF-8"?>
<cfg>
<param1>Hello</param1>
<param2>World</param2>
</cfg>
for example trace( e.result.cfg ) raises an error that the name does not exist. Tried several things and use the debugger to see what is inside the property e.result. I can see that the result is a ArrayCollection with one element [0] and the element is an ObjectProxy.
I saw some 'solutions' on the internet but all of the using a datagrid to show the results but that is not what i want. I want to access it like a simple array or object.
How can i do this?

try changing resultFormat="array" to resultFormat="e4x"
now e.result.param1 should return "Hello" and e.result.param2 should return "World" You can stick them in an array, custom class or bind it to a view

Related

fill datatable with vueJS

i´m trayin to fill my data table with vueJS and all my data from DB. I´m usign this library:
https://jamesdordoy.github.io/laravel-vue-datatable
It´s ok if i use this in my controller:
User::all()
return response()->json($query);
and in my component:
<div class="">
<data-table :data="data" :columns="columns" #on-table-props-changed="reloadTable"></data-table>
</div>
this library contain method to sortBy, orderBy, search by name, etc... with this:
use JamesDordoy\LaravelVueDatatable\Http\Resources\DataTableCollectionResource;
public function index(Request $request)
{
$length = $request->input('length');
$sortBy = $request->input('column');
$orderBy = $request->input('dir');
$searchValue = $request->input('search');
$query = User::eloquentQuery($sortBy, $orderBy, $searchValue);
$data = $query->paginate($length);
return new DataTableCollectionResource($data);
}
but if i use this in my controller in laravel 8 returned me:
Call to undefined method App\Models\User::eloquentQuery()
i don´t know if this it means to use get(), all().
Also, if i´m not use this and i to do all search manually, for example:
if(isset($sortBy)){
$query = User::all()->sortBy($sortBy);
$data = $query->paginate($length);
}
return response()->json($query);
returned me that:
Method Illuminate\Database\Eloquent\Collection::paginate does not exist
if i removed paginate and return $query, return all my data en my web browser console in network tab, but my table it´s empty...
for back-end i´m using laravel-8
in my web browser console return this message:
Invalid prop: type check failed for prop "data". Expected Object, got Array
if i change :data in my component for :items error in web browser console disappear
i don´t understand that i´m doing wrong for in one case i can fill my table and in other not...
Thanks for read and help me
i resolve my question with this:
$query = \DB::table('users')->orderBy($sortBy, $order)->paginate(10);
with model i can´t

Get HTML Data,HTML Tags from API in React-Native

I'm making mobile app with React-Native and i wanna get data from my API.But my API's datas , databases has html tags (you can see them in images which i shared) and some character codes because there are also Turkish characters.I already was using this API from my web site and there was no problem but when i try to get data to my react native app , it is getting data as a plain text as you see in my images.How can i get this datas without problem
It's called HTML entity. This is the code that works on browser (not on your case)
var decodeEntities = (function() {
// this prevents any overhead from creating the object each time
var element = document.createElement('div');
function decodeHTMLEntities (str) {
if(str && typeof str === 'string') {
// strip script/html tags
str = str.replace(/<script[^>]*>([\S\s]*?)<\/script>/gmi, '');
str = str.replace(/<\/?\w(?:[^"'>]|"[^"]*"|'[^']*')*>/gmi, '');
element.innerHTML = str;
str = element.textContent;
element.textContent = '';
}
return str;
}
return decodeHTMLEntities;
})();
The code are copied from here HTML Entity Decode
But it only works on the browser because the browser are automatically translate the characters for you.
I don't think passing around unserialized data like this is a good idea. You might want to encode data in server side using url encode or something then decode it in the react-native side
Reference
https://www.w3schools.com/charsets/ref_utf_punctuation.asp
Actually i solved it with this : https://github.com/archriss/react-native-render-html
Thanks

implement a simple inbox with notifications in yii

I want to implement a simple inbox in yii. it reads messages from a database table and show it.
but i don't know how i should show read and unread messages in different styles and how i can implement a notification for new messages.
i searched a lot but only found some extensions and i don't want to use them.
it is so important to find how i can show unread messages in a different way
any initial idea would help me
a part of mailbox extension code :
public function actionInbox($ajax=null)
{
$this->module->registerConfig($this->getAction()->getId());
$cs =& $this->module->getClientScript();
$cs->registerScriptFile($this->module->getAssetsUrl().'/js/mailbox.js',CClientScript::POS_END);
//$js = '$("#mailbox-list").yiiMailboxList('.$this->module->getOptions().');console.log(1)';
//$cs->registerScript('mailbox-js',$js,CClientScript::POS_READY);
if(isset($_POST['convs']))
{
$this->buttonAction('inbox');
}
$dataProvider = new CActiveDataProvider( Mailbox::model()->inbox($this->module->getUserId()) );
if(isset($ajax))
$this->renderPartial('_mailbox',array('dataProvider'=>$dataProvider));
else{
if(!isset($_GET['Mailbox_sort']))
$_GET['Mailbox_sort'] = 'modified.desc';
$this->render('mailbox',array('dataProvider'=>$dataProvider));
}
}
First of all the scripts things should be in the view. For you problem I would do something like
In the controller
$mailbox = Mailbox::model()->inbox($this->module->getUserId()); //I assume this returns the mailbox from that user?
$this->renderPartial('_mailbox',compact('mailbox ')); //compact is the same as array('mailbox'=>$mailbox) so use whatever you prefer.
In the view I would simply do something like this
<?php foreach($mailbox->messages as $message):
$class = ''; //order unread if you want to give both a different class name
if($message->read): //if this is true
$class = 'read';
endif; ?>
<div id='<?= $message->id ?>'class='message $class'> <!-- insert whatever info from the message --></div>
<?php endforeach; ?>
So now it will add the class read to every message that has been read. Then in CSS you can simply change it style. I hope this is enough information? I use foreach(): endforeach; and if(): endif; in the view files, but you could use foreach() {}, but I prefer foreach, as it looks better combined with HTML.
EDIT about you second question, how do they become read. This you could do with JQUERY. example.
$(".message").on("click", function() {
var id = $(this).attr('id');
$.ajax {
type:"POST",
url: "controller/action/"+id; //the controller action that fetches the message, the Id is the action variable (ex: public function actionGetMessage($id) {})
completed: function(data) {
//data = the message information, you might do type: 'JSON' instead. Use it however you want it.
if(!$(this).hasClass("read"))
$(this).addClass("read"); //give it the class read if it does not have it already
}
}
});
This simply gives the div the class read and it should look like the other items with the class read.

Calling member functions on click/tap within sencha touch 2 templates

I am rather new to sencha touch, I've done a lot of research and tutorials to learn the basics but now that I am experimenting I have run into a problem that I can't figure out.
I have a basic DataList which gets its data from a store which displays in a xtemplate.
Within this template I have created a member function which requires store field data to be parsed as a parameter.
I would like to make a thumbnail image (that's source is pulled from the store) execute the member function on click/tap.
I can't find any information on this within the docs, does anyone know the best way to go about this?
Here is a code example (pulled from docs as I can't access my actual code right now).
var tpl = new Ext.XTemplate(
'<p>Name: {name}</p>'
{
tapFunction: function(name){
alert(name);
}
}
);
tpl.overwrite(panel.body, data);
I want to make the paragraph clickable which will then execute the tapFunction() member function and pass the {name} variable.
Doing something like onclick="{[this.tapFunction(values.name)]} " does not seem to work.
I think functions in template are executed as soon as the view is rendered so I don't think this is the proper solution.
What I would do in your case is :
Add a unique class to your < p > tag
tpl : '<p class="my-p-tag">{name}</p>'
Detect the itemtap event on the list
In your dataview controller, you add an tap event listener on your list.
refs: {
myList: 'WHATEVER_REFERENCE_MATCHES_YOUR_LIST'
},
control: {
myList: {
itemtap: 'listItemTap'
}
}
Check if the target of the tap is the < p > tag
To do so, implement your listItemTap function like so :
listItemTap: function(list,index,target,record,e){
var node = e.target;
if (node.className && node.className.indexOf('my-p-tag') > -1) {
console.log(record.get('name'));
}
}
Hope this helps

Yii renderpartial (proccessoutput = true) Avoid Duplicate js request

Im creating a site who works with ajaxRequest, when I click a link, it will load using ajaxRequest. When I load for example user/login UserController actionLogin, I renderPartial the view with processOUtput to true so the js needed inside that view will be generated, however if I have clientScriptRegister inside that view with events, how can I avoid to generate the scriptRegistered twice or multiple depending on the ajaxRequest? I have tried Yii::app()->clientScript->isSCriptRegistered('scriptId') to check if the script is already registered but it seems that if you used ajaxRequest, the result is always false because it will only be true after the render is finished.
Controller code
if (Yii::app()->request->isAjaxRequest)
{
$this->renderPartial('view',array('model'=>$model),false,true);
}
View Code
if (!Yii::app()->clientScript->isScriptregistered("view-script"))
Yii::app()->clientScript->registerScript("view-script","
$('.link').live('click',function(){
alert('test');
})
");
If I request for the controller for the first time, it works perfectly (alert 1 time) but if I request again for that same controller without refreshing my page and just using ajaxRequest, the alert will output twice if you click it (because it keeps on generating eventhough you already registered it once)
This is the same if you have CActiveForm inside the view with jquery functionality.. the corescript yiiactiveform will be called everytime you renderPartial.
To avoid including core scripts twice
If your scripts have already been included through an earlier request, use this to avoid including them again:
// For jQuery core, Yii switches between the human-readable and minified
// versions based on DEBUG status; so make sure to catch both of them
Yii::app()->clientScript->scriptMap['jquery.js'] = false;
Yii::app()->clientScript->scriptMap['jquery.min.js'] = false;
If you have views that are being rendered both independently and as HTML fragments to be included with AJAX, you can wrap this inside if (Yii::app()->request->isAjaxRequest) to cover all bases.
To avoid including jQuery scripts twice (JS solution)
There's also the possibility of preventing scripts from being included twice on the client side. This is not directly supported and slightly more cumbersome, but in practice it works fine and it does not require you to know on the server side what's going on at the client side (i.e. which scripts have been already included).
The idea is to get the HTML from the server and simply strip out the <script> tags with regular expression replace. The important point is you can detect if jQuery core scripts and plugins have already been loaded (because they create $ or properties on it) and do this conditionally:
function stripExistingScripts(html) {
var map = {
"jquery.js": "$",
"jquery.min.js": "$",
"jquery-ui.min.js": "$.ui",
"jquery.yiiactiveform.js": "$.fn.yiiactiveform",
"jquery.yiigridview.js": "$.fn.yiiGridView",
"jquery.ba-bbq.js": "$.bbq"
};
for (var scriptName in map) {
var target = map[scriptName];
if (isDefined(target)) {
var regexp = new RegExp('<script.*src=".*' +
scriptName.replace('.', '\\.') +
'".*</script>', 'i');
html = html.replace(regexp, '');
}
}
return html;
}
There's a map of filenames and objects that will have been defined if the corresponding script has already been included; pass your incoming HTML through this function and it will check for and remove <script> tags that correspond to previously loaded scripts.
The helper function isDefined is this:
function isDefined(path) {
var target = window;
var parts = path.split('.');
while(parts.length) {
var branch = parts.shift();
if (typeof target[branch] === 'undefined') {
return false;
}
target = target[branch];
}
return true;
}
To avoid attaching event handlers twice
You can simply use a Javascript object to remember if you have already attached the handler; if yes, do not attach it again. For example (view code):
Yii::app()->clientScript->registerScript("view-script","
window.myCustomState = window.myCustomState || {}; // initialize if not exists
if (!window.myCustomState.liveClickHandlerAttached) {
window.myCustomState.liveClickHandlerAttached = true;
$('.link').live('click',function(){
alert('test');
})
}
");
The cleanest way is to override beforeAction(), to avoid any duplicated core script:
class Controller extends CController {
protected function beforeAction($action) {
if( Yii::app()->request->isAjaxRequest ) {
Yii::app()->clientScript->scriptMap['jquery.js'] = false;
Yii::app()->clientScript->scriptMap['jquery-2.0.0.js'] = false;
Yii::app()->clientScript->scriptMap['anything.js'] = false;
}
return parent::beforeAction($action);
}
}
Note that you have to put the exact js file name, without the path.
To avoid including script files twice, try this extension: http://www.yiiframework.com/extension/nlsclientscript/
To avoid attaching event handlers twice, see Jons answer: https://stackoverflow.com/a/10188538/729324