Pusher notification with Laravel 5.4 not working as expected - javascript

So I'm really stuck for a while now, with Laravel event and pusher API.
I created event and broadcast, but when I access with pusher Javascript API it returns empty array, when I try to print it in the route it also returns empty array, meanwhile if I check Laravel log stoarage/logs/laravel.log I see exactly what I am expecting in the Javascript and route.
My code:
.env
BROADCAST_DRIVER=pusher
PUSHER_APP_ID=******
PUSHER_APP_KEY=524**************8
PUSHER_APP_SECRET=d2**************c
Boadcasting.php
'default' => env('BROADCAST_DRIVER', 'pusher'),
'connections' => [
'pusher' => [
'driver' => 'pusher',
'key' => env('PUSHER_APP_KEY'),
'secret' => env('PUSHER_APP_SECRET'),
'app_id' => env('PUSHER_APP_ID'),
'options' => [
'cluster' => 'us2',
'encrypted' => true
],
],
The event class: ProjectEvent.php
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class ProjectEvent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $username;
public $message;
/**
* Create a new event instance.
*
* #return void
*/
public function __construct($username)
{
$this->username = $username;
$this->message = "{$username} sent you a message";
}
/**
* Get the channels the event should broadcast on.
*
* #return Channel|array
*/
public function broadcastOn()
{
return ['project-update'];
}
}
Route:
Route::get('/test', function () {
print_r(event(new App\Events\ProjectEvent('Michel')));
//return "Event has been sent!";
});
Route::get('/view', function () {
return view('testevent');
});
testevent.blade.php
<!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">
</head>
<body>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="http://js.pusher.com/3.1/pusher.min.js"></script>
<script type="text/javascript">
Pusher.logToConsole = true;
var pusher = new Pusher('524************8', {
cluster: 'us2',
encrypted: true
});
var channel = pusher.subscribe('project-update');
channel.bind('App\\Events\\ProjectEvent', function(data) {
alert(data.message);
});
</script>
</body>
</html>
I really can't figure out where it all going wrong, since I am able to see the event in the log while the JS alert isn't working, also I try to dump the event on the route, it return empty array()

Related

Flutter webview with custom javascriptInterfaceAdapter or invoke JS using webview controller

I have an old java project that performs in andorid webview with addJavascriptInterface
mWebView.addJavascriptInterface(new JavascriptAdapter(), "AndroidFunctions");
Within JavascriptAdapter class there is several #JavascriptInterface functions. as example
class JavascriptAdapter {
#JavascriptInterface
getMacAddress(){
DeviceInfo deviceInfo = new DeviceInfo(activity);
return deviceInfo.getMacAddress();
}
}
now after opening the webview within android applications, using JS we can access that function like this way -
var strMacAddress = AndroidFunctions.getMACAddress();
Now I would like to achieve this thing on flutter. for that, I am using the flutter inAppWebview plugin.
also, I have tried flutter_webview, WKWebview.
Please take a look in this documentation for InAppWebView.
JavScriptInterface are normally used to call native methods from webview. I am assuming that the webpage calls the method, so, you have to return the Mac Address as it is presented in the documentation. But you need to change the way for calling the method for flutter by adding this sample(provided in documentation) to you webpage source.
<script>
window.addEventListener("flutterInAppWebViewPlatformReady", function(event) {
window.flutter_inappwebview.callHandler('handlerFoo')
.then(function(result) {
// print to the console the data coming
// from the Flutter side.
console.log(JSON.stringify(result));
window.flutter_inappwebview
.callHandler('handlerFooWithArgs', 1, true, ['bar', 5], {foo: 'baz'}, result);
});
});
</script>
You can inspect this Webview from google chrome.
chrome://inspect/#devices
and don't forget to add flutter_inappwebview: ^5.3.2 in your pubspec.yaml
the answer is already given in this link
I have just added for a quick look on SO.
import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
Future main() async {
WidgetsFlutterBinding.ensureInitialized();
if (Platform.isAndroid) {
await AndroidInAppWebViewController.setWebContentsDebuggingEnabled(true);
}
runApp(new MyApp());
}
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => new _MyAppState();
}
class _MyAppState extends State<MyApp> {
InAppWebViewGroupOptions options = InAppWebViewGroupOptions(
android: AndroidInAppWebViewOptions(
useHybridComposition: true,
),);
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text("JavaScript Handlers")),
body: SafeArea(
child: Column(children: <Widget>[
Expanded(
child: InAppWebView(
initialData: InAppWebViewInitialData(
data: """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
</head>
<body>
<h1>JavaScript Handlers</h1>
<script>
window.addEventListener("flutterInAppWebViewPlatformReady", function(event) {
window.flutter_inappwebview.callHandler('handlerFoo')
.then(function(result) {
// print to the console the data coming
// from the Flutter side.
console.log(JSON.stringify(result));
window.flutter_inappwebview
.callHandler('handlerFooWithArgs', 1, true, ['bar', 5], {foo: 'baz'}, result);
});
});
</script>
</body>
</html>
"""
),
initialOptions: options,
onWebViewCreated: (controller) {
controller.addJavaScriptHandler(handlerName: 'handlerFoo', callback: (args) {
// return data to the JavaScript side!
return {
'bar': 'bar_value', 'baz': 'baz_value'
};
});
controller.addJavaScriptHandler(handlerName: 'handlerFooWithArgs', callback: (args) {
print(args);
// it will print: [1, true, [bar, 5], {foo: baz}, {bar: bar_value, baz: baz_value}]
});
},
onConsoleMessage: (controller, consoleMessage) {
print(consoleMessage);
// it will print: {message: {"bar":"bar_value","baz":"baz_value"}, messageLevel: 1}
},
),
),
]))),
);
}
}

Flutter Webview two way communication with Javascript

I have an html file that I am loading in Flutter webview using flutter_webview_plugin. I am using evalJavascript to call function in my javascript code, meaning flutter(dart)->js. However, I also need some way to communicate back something to flutter(dart) layer, meaning js->flutter(dart).
I have tried using
- webkit.messageHandlers.native
- window.native
to support both platforms(Android,iOS) checking if those are available in JS. But, those comes as undefined. Using following code to get instance of native handler in JS.
typeof webkit !== 'undefined' ? webkit.messageHandlers.native :
window.native;
And even if I get that instance and post message using it, not sure how to handle it in flutter(dart) layer. I may need to use platform channels. Not sure, if I am in the right direction.
Is there any way through which I can do that? I have evaluated interactive_webview plugin. It works fine on Android. But, it has swift versioning issue and don't want to proceed further with that.
Any help would be appreciated.
Here is an example of communication from Javascript code to flutter.
In Flutter build your WebView like :
WebView(
initialUrl: url,
javascriptMode: JavascriptMode.unrestricted,
javascriptChannels: Set.from([
JavascriptChannel(
name: 'Print',
onMessageReceived: (JavascriptMessage message) {
//This is where you receive message from
//javascript code and handle in Flutter/Dart
//like here, the message is just being printed
//in Run/LogCat window of android studio
print(message.message);
})
]),
onWebViewCreated: (WebViewController w) {
webViewController = w;
},
)
and in Your HTMLfile:
<script type='text/javascript'>
Print.postMessage('Hello World being called from Javascript code');
</script>
When you run this code, you shall be able to see log "Hello World being called from Javascript code" in the LogCat/Run window of android studio.
You can try my plugin flutter_inappbrowser (EDIT: it has been renamed to flutter_inappwebview) and use addJavaScriptHandler({#required String handlerName, #required JavaScriptHandlerCallback callback}) method (see more here).
An example is presented below.
On Flutter side:
...
child: InAppWebView(
initialFile: "assets/index.html",
initialHeaders: {},
initialOptions: InAppWebViewWidgetOptions(
inAppWebViewOptions: InAppWebViewOptions(
debuggingEnabled: true,
)
),
onWebViewCreated: (InAppWebViewController controller) {
webView = controller;
controller.addJavaScriptHandler(handlerName: "mySum", callback: (args) {
// Here you receive all the arguments from the JavaScript side
// that is a List<dynamic>
print("From the JavaScript side:");
print(args);
return args.reduce((curr, next) => curr + next);
});
},
onLoadStart: (InAppWebViewController controller, String url) {
},
onLoadStop: (InAppWebViewController controller, String url) {
},
onConsoleMessage: (InAppWebViewController controller, ConsoleMessage consoleMessage) {
print("console message: ${consoleMessage.message}");
},
),
...
On JavaScript side (for example a local file assets/index.html inside the assets folder):
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Flutter InAppBrowser</title>
...
</head>
<body>
...
<script>
// In order to call window.flutter_inappwebview.callHandler(handlerName <String>, ...args)
// properly, you need to wait and listen the JavaScript event flutterInAppWebViewPlatformReady.
// This event will be dispatched as soon as the platform (Android or iOS) is ready to handle the callHandler method.
window.addEventListener("flutterInAppWebViewPlatformReady", function(event) {
// call flutter handler with name 'mySum' and pass one or more arguments
window.flutter_inappwebview.callHandler('mySum', 12, 2, 50).then(function(result) {
// get result from Flutter side. It will be the number 64.
console.log(result);
});
});
</script>
</body>
</html>
On Android Studio logs you will get:
I/flutter (20436): From JavaScript side:
I/flutter (20436): [12, 2, 50]
I/flutter (20436): console message: 64
I want to tell you about how to send messages from flutter WebView to JS:
In JS code you need to bind your function you need to fire to window
const function = () => alert('hello from JS');
window.function = function;
In your code in WebView widget implementation you need to declare onWebViewCreated method like this
WebView(
onWebViewCreated: (WebViewController controller) {},
initialUrl: 'https://url.com',
javascriptMode: JavascriptMode.unrestricted,
)
In class widget declare var _webViewController;
class App extends State<MyApp> {
final _webViewController;
}
In onWebViewCreated write this code
onWebViewCreated: (WebViewController controller) {
_webViewController = controller;
},
Then you can run code like this:
class App extends StatelessWidget {
var _webViewController;
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: Scaffold(
body: WebView(
onWebViewCreated: (WebViewController controller) {
_webViewController = controller;
},
initialUrl: 'https://url.com',
javascriptMode: JavascriptMode.unrestricted,
),
floatingActionButton: FloatingActionButton(
onPressed: () {
// When you click at this button youll run js code and youll see alert
_webViewController
.evaluateJavascript('window.function ()');
},
child: Icon(Icons.add),
backgroundColor: Colors.green,
),
),
);
}
}
But what if we want to share this _webViewController instance to other widgets like drawer?
In this case I decided to implement Singleton pattern and store _webViewController instance in it.
So
Singleton class
class Singleton {
WebViewController webViewController;
static final Singleton _singleton = new Singleton._internal();
static Singleton get instance => _singleton;
factory Singleton(WebViewController webViewController) {
_singleton.webViewController = webViewController;
return _singleton;
}
Singleton._internal();
}
Then
onWebViewCreated: (WebViewController controller) {
var singleton = new Singleton(controller);
},
And finally in our Drawer widget i.e. (here you can use whatever widget you want)
class EndDrawer extends StatelessWidget {
final singleton = Singleton.instance;
#override
Widget build(BuildContext context) {
return Drawer(
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
SizedBox(
width: 200,
child: FlatButton(
onPressed: () {
singleton.webViewController.evaluateJavascript('window.function()');
Navigator.pop(context); // exit drawer
},
child: Row(
children: <Widget>[
Icon(
Icons.exit_to_app,
color: Colors.redAccent,
),
SizedBox(
width: 30,
),
Text(
'Exit',
style: TextStyle(color: Colors.blueAccent, fontSize: 20),
),
],
),
)),
],
),
);
}
}
If you want to receive messages from JS code to your flutter App you need:
In your js code
window.CHANNEL_NAME.postMessage('Hello from JS');
In your flutter code.
When you're running JavascriptChannel(name: 'CHANNEL_NAME', ...)
flutter bind to your window WebView new MessageChannel with name you wrote in constructor (in this case CHANNEL_NAME)
so when we call window.CHANNEL_NAME.postMessage('Hello from JS'); we recieve a message we sent
WebView(
javascriptChannels: [
JavascriptChannel(name: 'CHANNEL_NAME', onMessageReceived: (message) {
print(message.message);
})
].toSet(),
initialUrl: 'https://url.com',
)
So here we are.
I'm new in flutter code
So if you have another better experience about this you can write in comments to help other people!
Full code example of Javascript callbacks using package flutter_inappwebview:
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
Future main() async {
WidgetsFlutterBinding.ensureInitialized();
runApp(new MyApp());
}
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => new _MyAppState();
}
class _MyAppState extends State<MyApp> {
InAppWebViewController _webViewController;
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('InAppWebView Example'),
),
body: Container(
child: Column(children: <Widget>[
Expanded(
child: InAppWebView(
initialData: InAppWebViewInitialData(data: """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
</head>
<body>
<h1>JavaScript Handlers (Channels) TEST</h1>
<button id='test' onclick="window.flutter_inappwebview.callHandler('testFunc');">Test</button>
<button id='testargs' onclick="window.flutter_inappwebview.callHandler('testFuncArgs', 1);">Test with Args</button>
<button id='testreturn' onclick="window.flutter_inappwebview.callHandler('testFuncReturn').then(function(result) { alert(result);});">Test Return</button>
</body>
</html>
"""),
initialOptions: InAppWebViewGroupOptions(
crossPlatform: InAppWebViewOptions(
debuggingEnabled: true,
)),
onWebViewCreated: (InAppWebViewController controller) {
_webViewController = controller;
_webViewController.addJavaScriptHandler(
handlerName: 'testFunc',
callback: (args) {
print(args);
});
_webViewController.addJavaScriptHandler(
handlerName: 'testFuncArgs',
callback: (args) {
print(args);
});
_webViewController.addJavaScriptHandler(
handlerName: 'testFuncReturn',
callback: (args) {
print(args);
return '2';
});
},
onConsoleMessage: (controller, consoleMessage) {
print(consoleMessage);
},
),
),
])),
),
);
}
}
There are two ways to communicate the answer:
First way From Flutter to the webview (javascript, react...)
From the flutter side (using a button or in a trigger method):
webViewController.evaluateJavascript('fromFlutter("pop")');
This fromFlutter will be the name of the method in your javascript, react, whatever and also you can send text, in this case "pop".
From the javascript side inside the html, in your body label:
<script type="text/javascript">
function fromFlutter(data) {
// Do something
console.log("This is working now!!!");
}
</script>
Second way From your webview (javascript, react...) to Flutter
In your Webview attribute javascriptChannels you can add:
javascriptChannels: Set.from([
JavascriptChannel(
name: 'comunicationname',
onMessageReceived: (JavascriptMessage message) async {
// Here you can take message.message and use
// your string from webview
},
)
]),
From the webview using the same communication name "communicationname" (your can use another name in both places):
window.communicationname.postMessage("native,,,pop,");
Flutter 3.0.5
webview_flutter: ^3.0.4
flutter_js: ^0.5.0+6
Another way to use JavascriptChannels is to tranfer data from the "App" to your Website.
Dart:
JavascriptChannel(
name: 'getFCMToken',
onMessageReceived: (JavascriptMessage message) async {
//print(message.message);
final token = (await FirebaseMessaging.instance.getToken())!;
final script = "var appToken =\"${token }\"";
_webViewController.runJavascript(script);
},
),
html:
<script type = "text/javascript">
window.onload = getFCMToken.postMessage('');
</script>
or Dart(Trigger):
OnPageFinished: (url) async {
try {
final token = (await FirebaseMessaging.instance.getToken())!;
var javascript = "var appToken=\"${token.toString()}\"";
} catch (_) {}
}
so in your website code you have a js var "appToken" wich you can use in PHP or whatever.
If you are using webviewx plugin which support web,ios and android than this is how we can do two way communication.
I have webpage which has index.html and other js,and css pages which I want to display in webview and communicate between flutter and web app.
1. From flutter to js listener
IconButton(
icon: Icon(Icons.developer_mode),
onPressed: () {
webviewController
.evalRawJavascript('window.myFunction()',
inGlobalContext: false)
.then((value) => print(value));
},
)
Note: myFunction is function defined in javascript or html page as below.
function myFunction() {
alert("I am an alert box!");
return 'working';
}
2. From js/html to flutter listener
In html/js add button with listener
function submitClick() {
var data = document.getElementById('data').value;
SubmitCallback(data) //defined in flutter
}
Now In flutter(add dartCallback):
WebViewX(
javascriptMode: JavascriptMode.unrestricted,
initialContent: '<h2> Loading </h2>',
initialSourceType: SourceType.HTML,
onWebViewCreated: (controller) {
webviewController = controller;
_loadHtmlFromAssets();
webviewController.addListener(() {});
},
dartCallBacks: {
DartCallback(
name: 'SubmitCallback',
callBack: (msg) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Submitted $msg successfully')));
},
),
},
)
PS. Happy Coding

Laravel, Vue.js array empty

I'm totally new to the laravel and vue.js frameworks. For a school project with have to create an app that uses laravel for the back-end and vue.js for the front-end. So I created an API to use it afterwards in my vue.Js. But the problem is that when I want to get the data in my Vue.JS it tells me it has an empty array which should show all the values I have in my database (about 20). I have been struggling since 2 days on it and now, I'm totally lost, I don't know what to do or what goes wrong.. I tried my API into postman and it works perfect.
Specs:
-> Laravel 5.6
-> Vue 2.5.7
My API Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Note;
use App\Http\Resources\Note as NoteResource;
class NotesApiController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$notes = Note::all();
return NoteResource::collection($notes);
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$note = new Note;
$note->user_id = $request -> input('user_id');
$note->course_id = $request -> input('course_id');
$note->title = $request -> input('title');
$note->body = $request -> input('body');
$note->file_name = $request -> input('file_name');
$note->save();
return new NoteResource($note);
return response() -> json('success', 200);
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$note = Note::findOrFail($id);
return new NoteResource($note);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$note = Note::find($id);
$note->user_id = $request -> input('user_id');
$note->course_id = $request -> input('course_id');
$note->title = $request -> input('title');
$note->body = $request -> input('body');
$note->file_name = $request -> input('file_name');
$note->save();
return new NoteResource($note);
return response() -> json('success', 200);
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$note = Note::find($id);
$note -> delete();
return response() -> json('success', 200);
}
}
My Note Resource:
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class Note extends JsonResource
{
/**
* Transform the resource into an array.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'user_id' => $this->user_id,
'course_id' => $this->course_id,
'title' => $this->title,
'body' => $this->body,
'file_name' => $this->file_name,
'created_at' => $this->created_at->format('d/m/Y'),
'updated_at' => $this->updated_at->diffForHumans(),
];
}
}
API Routes:
<?php
use Illuminate\Http\Request;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
// Route::middleware('auth:api')->get('/user', function (Request $request) {
// return $request->user();
// });
//Index Page Vue
Route::get('/', 'PagesControllerApi#index');
//Afficher la liste de toutes les notes
Route::get('notes', 'NotesApiController#index');
//Montre une note selon son id
Route::get('notes/{id}', 'NotesApiController#show');
//Enregistre la note
Route::post('notes', 'NotesApiController#store');
//Mise-à-jour d'une note
Route::put('notes/{id}', 'NotesApiController#update');
//Effacer une note
Route::delete('notes/{id}', 'NotesApiController#destroy');
APP.JS of Vue:
/**
* First we will load all of this project's JavaScript dependencies which
* includes Vue and other libraries. It is a great starting point when
* building robust, powerful web applications using Vue and Laravel.
*/
require('./bootstrap');
window.Vue = require('vue');
/**
* Next, we will create a fresh Vue application instance and attach it to
* the page. Then, you may begin adding components to this application
* or customize the JavaScript scaffolding to fit your unique needs.
*/
Vue.component('notes', require('./components/notes.vue'));
Vue.component('navbar', require('./components/navbar.vue'));
Vue.component('paginate', require('vuejs-paginate'));
const app = new Vue({
el: '#app'
});
My Note Component in Vue
<template>
<div>
<h2 class="m-4">Notes</h2>
</div>
</template>
<script>
export default {
data() {
return{
notes: [],
note: {
id: '',
user_id: '',
course_id: '',
title: '',
body: '',
file_name:'',
},
note_id: '',
pagination: {},
edit: false
};
},
created() {
this.fetchArticles();
},
methods: {
fetchArticles(page_url) {
let vm = this;
page_url = page_url || '/api/notes';
fetch(page_url)
.then(res => res.json())
.then(res => {
this.articles = res.data;
})
.catch(err => console.log(err));
},
}
}
</script>
index.blade.php
<!DOCTYPE html>
<html lang="{{ app()->getLocale() }}">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- CSRF Token -->
<meta name="csrf-token" content="{{ csrf_token() }}">
<script>window.Laravel = { csrfToken: "{{ csrf_token() }}" }</script>
<title>{{ config("app.name", "Laravel") }}</title>
<!-- Scripts -->
<script src="{{ asset('js/app.js') }}" defer></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<!-- Fonts -->
<link rel="dns-prefetch" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css?family=Raleway:300,400,600" rel="stylesheet" type="text/css">
<!-- Styles -->
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>
<body>
<div id="app">
<navbar></navbar>
<div class="container">
<notes>
</notes>
</div>
</div>
</body>
</html>
API
Results
What the VUE Develope shows
Empty Array
Because of that I can't show any value on my page..
Thanks in advance!
It should be this.notes = res.data but you have this.articles = res.data;
Then you just need to loop over the array and access properties on the object, something like this:
<div v-for="(note, index) in notes" :key="`note-${key}`">
<h2 v-text="note.title"></h2>
<p v-text="note.body"></p>
<p v-text="note.filename"></p>
</div>

Laravel 5.3 not sending Events to pusher

I'm using laravel 5.3 for my website. I needed to add real time functionality to my app so I used pusher. but the problem is when the event has been triggered nothing happened and no events sent to pusher.
my pusher configuration in broadcasting.php file :
'pusher' => [
'driver' => 'pusher',
'key' => env('PUSHER_KEY'),
'secret' => env('PUSHER_SECRET'),
'app_id' => env('PUSHER_APP_ID'),
'options' => [
'cluster' => 'eu',
'encrypted'=>true
],
],
my event class:
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class ChatEvent implements ShouldBroadcast
{
use InteractsWithSockets, SerializesModels;
public $data;
/**
* Create a new event instance.
*
* #return void
*/
public function __construct($data)
{
$this->data = $data;
}
/**
* Get the channels the event should broadcast on.
*
* #return Channel|array
*/
public function broadcastOn()
{
// return new PrivateChannel('test-channel');
return ['test-channel'];
}
and my pusher javascript code:
Pusher.logToConsole = true;
var pusher = new Pusher('pusher_id', {
cluster:'eu',
encrypted: true
});
var channel = pusher.subscribe('test-channel');
channel.bind('App\\Events\\ChatEvent', function(data) {
console.log(data);
alert(data);
});
Check your Pusher credentials in your .env file.
PUSHER_KEY should be PUSHER_APP_KEY
PUSHER_SECRET should be PUSHER_APP_SECRET

JQuery nested $.when ... then statements

I'm trying to do a FreeCodeCamp exercise where I call the Twitch TV API. For each channel I make a call to the API to get the channel data. I then make a subsequent call to get the streaming data. The call for the channel information is wrapped in a $.when ... then loop and seems to work fine. I then added a second call to get the stream data and code does not seem to wait for that call to complete.
$(document).ready(function() {
'use strict';
var dataArray = []; // This holds all the channels that I find. I then sort to get the most popular first.
$.when(
// TODO this should be some sort of loop to make it more flexible
getChannelData("https://api.twitch.tv/kraken/search/channels?api_version=3&q=all&limit=10&offset=0&callback=?") // First 10
).then(function() {
sortData();
displayData();
});
function getChannelData(channelStatement) {
return $.getJSON(channelStatement, function(channelData) {
channelData.channels.forEach(function(element) {
// Get stream details
var channel;
channel = {
logo: (element.logo === null) ? "https://upload.wikimedia.org/wikipedia/commons/3/33/White_square_with_question_mark.png" : element.logo, // Channel: Url for image
displayName: element.display_name, // Channel: Broadcaster name
channelName: element.name, // Channel: Channel name
url: element.url, // Channel: Used to generate link to twitch page
game: element.game, // Channel: As the name suggests
status: element.status, // Chaneel: Description of the stream
views: element.views, // Channel: As the name suggests
onLine: true
};
//dataArray.push(channel);
var streamUrl = "https://api.twitch.tv/kraken/streams/" + element.name + "?api_version=3&callback=?";
$.when(
getStreamData(streamUrl, channel)
)
.then(function() {
dataArray.push(channel);
});
}); // channel data forEach
});
}
function getStreamData(streamUrl, channel) {
return $.getJSON(streamUrl, function(stream) {
channel.onLine = (stream.stream === null) ? false : true;
});
}
function sortData() {
}
function displayData() {
}
}); // end ready
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7"
crossorigin="anonymous">
<link href='https://fonts.googleapis.com/css?family=Roboto' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="style.css">
<title>Twitch TV</title>
</head>
<body>
<div class="container-fluid">
<ol id="twitchList">
</ol>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="TwitchTV.js"></script>
</body>
</html>
This JSBin link shows the code. Line 51 shows the second ajax call.
The code should populate an array and then on completion of all the calls display the data. I appreciate that with a production system waiting for all these calls to complete will lead to a less than idea user experience.
You need to re-oganize it slightly so that the promise you return from getChannelData is waiting on the promises created within your forEach.
function getChannelData(channelStatement) {
return $.getJSON(channelStatement).then(function(channelData) {
return $.when.apply(null, channelData.channels.map(function(element) {
// Get stream details
var channel = {
logo: (element.logo === null) ? "https://upload.wikimedia.org/wikipedia/commons/3/33/White_square_with_question_mark.png" : element.logo, // Channel: Url for image
displayName: element.display_name, // Channel: Broadcaster name
channelName: element.name, // Channel: Channel name
url: element.url, // Channel: Used to generate link to twitch page
game: element.game, // Channel: As the name suggests
status: element.status, // Chaneel: Description of the stream
views: element.views, // Channel: As the name suggests
onLine: true
};
//dataArray.push(channel);
var streamUrl = "https://api.twitch.tv/kraken/streams/" + element.name + "?api_version=3&callback=?";
return getStreamData(streamUrl, channel);
}); // channel data map
});
}
you would then use it like:
getChannelData(whatever).then(function () {
console.log(arguments); // this is dataArray
});

Categories

Resources