Firebase/Angular: Messages not showing in HTML, but contain the message objects - javascript

Good day SO,
I am trying to incorporate a basic firebase chat module into my system via angular js (I am honestly not proficient at all..)
I am facing a problem whereby my items are not showing in my HTML element although my firebase messages are being retrieved from my firebase database.
Here is my HTML code:
<html lang="en" ng-app="chatApp">
...
<section id="content3" class="tab-content">
<div class="card mb-3">
<div class="card-header">
<i class="fa fa-comments-o"></i>
Instant Chat Messenger – Crisis Management Office
</div>
<div class="card-body" ng-controller="ChatController">
<p ng-repeat="m in messages">{{m.message}}- </p>
<div class="form-row">
<div class="form-group col-md-11">
<input type="text" class="form-control" id="chatEntry" rows="14" placeholder="Type your message here" ng-model="messageText">
</div>
<div class="form-group col-md-1">
<button type="submit" class="btn btn-primary btn-block" id="sendBtn" ng-click="send()">Send</button>
</div>
</div>
</div>
</div>
</section>
And here is the angular.js code:
var app = angular.module('chatApp', ['firebase']);
app.controller('ChatController', function($scope, $firebaseArray) {
var crisis = "Crisis1";
//Query
var ref = firebase.database().ref().child(crisis).child('CMO-PMO');
$scope.messages = $firebaseArray(ref);
$scope.send = function() {
$scope.messages.$add({
sender: "PMO",
message: $scope.messageText,
date: Date.now()
})
}
})
And now, here is the funny thing.. My messages are being retrieved (I put a dash '-' behind {{ m.messages }} so that a dash will print for each message in my firebase database (To show that they are being retrieved), but my messages are not being shown.
Here is a screenshot of my firebase (Note: has 7 messages currently):
And here is a screenshot of my HTML page (It shows 7 dashes for 7 items in my firebase):
Although I have checked my scope in the javascript code, as well as the namings in my firebase database, my messages are still unable to show.. But I am able to send messages via my page to the firebase database. (The button and send functions are working!) The only problem now is showing the messages..
I am at a loss.. Please help me SO! I will promptly reply to any posts here :) Thank you so much!
Edit: If i use {{m|json}}:

I have solved the rendering problem using the {%verbatim%} tag.

Related

Making text disappear using laravel livewire by timing out the flash message

I've written some code using laravel livewire that makes a modal appear whenever a user successfully subscribes or volunteers to join my website. I've tried writing some code that delays the modal, but now it's just making my code slower instead of making some text disappear after a few seconds. Here's the code that I've written on my blade file.
<div wire:loading.delay.short class="bg-white shadow" style="border-radius: 30px">
#if (session()->has('subscription_message'))
#include('livewire.frontend.subscribe.success')
#endif
</div>
I want the subscription_message to disappear and I've also written the subscription_message on another blade file.
<div wire:loading id="modal" class="alert alert-success" role="alert">
<h6 class="alert-heading">Thank you for your Subscription!🤗</h6>
<p>{{ session('subscription_message') }}<i class="fa fa-check"></i></p>
<p class="mb-0">Kind Regards,<br>
{!! 'Ben's Team' !!}
</p>
</div>
Here's the livewire component that controlls all the code on those two blade files.
public function save()
{
$this->validateForm();
Subscription::create([
'name' => $this->name,
'email' => $this->email
]);
$name = $this->name;
$email = $this->email;
$message = "Dear $name ! Thank you for subscribing with Us, Please check your email:($email) for more information.";
$this->resetInput();
// Sent Welcome email to subscriber
Mail::to($email)->send(new WelcomeSubscriberNotification());
session()->flash('subscription_message',$message);
}
I don't know how to timeout the flash message that appears after a user has subscribed. Can any assist me on a way to solve this problem? I want to use livewire, but if that doesn't work, I'm willing to use either Jquery or Javascript.
I've got it. On the blade file which shows the success message after clicking the submit button, I just added the following js code.
Blade file
<div id="modal" class="alert alert-success" role="alert">
<h6 class="alert-heading">Thank you for your Subscription!🤗</h6>
<p>{{ session('subscription_message') }}<i class="fa fa-check"></i></p>
<p class="mb-0">Kind Regards,<br>
{!! 'Ben's Team' !!}
</p>
</div>
JS Code
var timeout = 3000; // in miliseconds (3*1000)
$('.alert').delay(timeout).fadeOut(300);</script>

Return multiple templates

I am currently trying open multiple pages on a POST request. Basically, what I am doing is searching for a job number in the database by sending a POST request and then (trying) opening the multiple pages that correspond with that job number (ex.: a webpage for job location, one for material, etc.) However, I can only return one template for the browser to open. I have looked at many, many questions like this one:
Render multiple templates at once in Flask
However, I am not finding the answer to my question (most likely because I am asking the wrong question...)
Anyway, my code so far is something like this:
HTML:
<form action="/testing" method="POST" id="existBidFormOne" name="existBidFormOne" autocomplete="off">
<!-- Row one holds Title-->
<div class="center row" style="width: 100%;">
<h1>Enter a Job Number or a Project Name:</h1>
</div>
<!-- Row two holds job number-->
<div class="row">
<!-- Column one holds Job number-->
<div class="col-m-6">
<div class="row centerInput">
<div class="col-m-4 inputPad"><b>Job Number:</b></div>
<div class="col-m-8 noPad">
<input type="text" id="exb_jobNumber" name="exb_jobNumber" class="input maxWidth" />
</div>
</div>
</div>
</div>
<div class="centerInput row">
<span>
<button type="submit" id="exb_searchOne" class="srchBtn">Search</button>
</span>
</div>
</form>
FLASK:
#app.route('/testing', methods=["GET", "POST"])
def testing():
if request.method == 'POST':
job_num = request.form.getlist('exb_jobNumber')
if job_num:
session = Session()
results = ds.get_job_info(session, job_num) # returns dict
results2 = ds.get_job_material(session, job_num) #returns dict
session.close()
# open page one
return render_template('pageOne.html', **results)
The above code works well opening one page, however I would also like to open:
render_template('pageTwo.html', **results2)
Thank you!
opening the multiple pages If you want to open multiple pages on a single webpage (i.e. in a single browser tab), then you can combine and render as many separate templates as you want with template inheritance. You can have single base page and nest many sub-pages with any content you want.
If you want to open multiple pages in multiple browser tabs, then you should return only a single main HTML page (i.e. single template), but set variable in that webpage with links of all pages you want to open in new browser tabs. Then, with the help of JavaScript and browser API method window.open() you can open those pages.

How to create dynamic share popup

I have some post which are fetch by php while loop & each of the post has a link of share this post for e.g
Post 1 - share this post
Post 2 - share this post
Post 3 - share this post
there are many more post
I read out an jquery article and i got this->
jquery part
$('body').on('click','.js_share',function(){
var post=$(this).parents('.post');
var id=post.attr('data-id');
confirm(__['Share Post'],__['Are you sure you want to share this post?'],function(){
$.post(api['posts/reaction'],{'do':'share','id':id},function(response){if(response.callback){eval(response.callback);}
else{modal('#modal-success',{title:__['Success'],message:__['This has been shared to your Timeline']});}}).fail(function(){modal('#modal-message',{title:__['Error'],message:__['There is some thing went worng!']});});});});
html Part
<script id="modal-success" type="text/template">
<div class="modal-body text-center">
<div class="big-icon success">
<i class="fa fa-thumbs-o-up fa-3x"></i>
</div>
<h4>{{title}}</h4>
<p class="mt20">{{message}}</p>
</div>
</script>
The above script doesn't work in console it shows nothing
I have added the reference __ by
<script type="text/javascript">var __=[];__["Follow"]='Follow';__["Share Post"]='Share Post';__["Remove"]='Remove';__["Error"]='Error';__["Success"]='Success';__["Loading"]='Loading';__["Like"]='Like';__["Unlike"]='Unlike';__["Delete Comment"]='Delete Comment';__["There is some thing went worng!"]='There is some thing went worng!';__["This has been shared to your Timeline"]='This has been shared to your Timeline';</script>

Content tools gives save confirmation but does not save on php project

Objective
To make my website editable using Content Tools
Background
I added Content Tools to my website Package Mules. I have sections that can be edited by the public. Security is not a concern at this point, it is a very small site.
Problem
It gives me a checkmark that it saved, unlike before where I would get an "X" meaning error. As you can see in this screencast. But when I refresh the page it seems that it did not actually save.
Code
Repo
https://github.com/JGallardo/package-mules
HTML (for index.php)
<!DOCTYPE hmtl>
<html lang="en">
<?php include 'includes/head.html';?>
<body>
<?php include 'includes/nav.html';?>
<section class="container">
<div class="row">
<div class="col-md-12">
<h1>Package Mules</h1>
<p>Welcome to the future home of package mules. Our mission is to help bring movers together with low cost options for moving.</p>
<p>We set up an editable page so we can get public feedback. Please be considerate and only post appropriate content.</p>
</div>
</div>
</section>
<section class="container">
<div class="row">
<div class="col-md-12">
<h2>The thing you hate most about moving is?</h2>
</div>
<div class="col-md-12">
<div data-editable data-name="moving-1">
<blockquote>
[Enter content here]
</blockquote>
<p>[your name]</p>
</div>
<div data-editable data-name="moving-2">
<blockquote>
[Enter content here]
</blockquote>
<p>[your name]</p>
</div>
<div data-editable data-name="moving-3">
<blockquote>
[Enter content here]
</blockquote>
<p>[your name]</p>
</div>
<div data-editable data-name="moving-4">
<blockquote>
[Enter content here]
</blockquote>
<p>[your name]</p>
</div>
<div data-editable data-name="moving-5">
<blockquote>
[Enter content here]
</blockquote>
<p>[your name]</p>
</div>
<div data-editable data-name="moving-6">
<blockquote>
[Enter content here]
</blockquote>
<p>[your name]</p>
</div>
</div>
</div>
</seciton>
<?php include 'includes/footer.html';?>
<?php include 'includes/scripts.html';?>
<script>
window.addEventListener('load', function() {
var editor;
ContentTools.StylePalette.add([
new ContentTools.Style('Author', 'author', ['p'])
]);
editor = ContentTools.EditorApp.get();
editor.init('*[data-editable]', 'data-name');
editor.bind('save', function (regions) {
var name, payload, xhr;
// Set the editor as busy while we save our changes
this.busy(true);
// Collect the contents of each region into a FormData instance
payload = new FormData();
for (name in regions) {
if (regions.hasOwnProperty(name)) {
payload.append(name, regions[name]);
}
}
// Send the update content to the server to be saved
function onStateChange(ev) {
// Check if the request is finished
if (ev.target.readyState == 4) {
editor.busy(false);
if (ev.target.status == '200') {
// Save was successful, notify the user with a flash
new ContentTools.FlashUI('ok');
} else {
// Save failed, notify the user with a flash
new ContentTools.FlashUI('no');
}
}
};
xhr = new XMLHttpRequest();
xhr.addEventListener('readystatechange', onStateChange);
xhr.open('POST', '/index.php');
xhr.send(payload);
var_dump($_POST);
});
});
</script>
</html>
I believe the problem here is the var_dump($_POST); call in you're JavaScript. I'm not a PHP coder but I'm assuming that's a PHP call and that it should be within PHP tags.
The reasons this appears to work is that the onStateChange callback is called after this error. So the process of events looks a bit like this:
You click the save button.
The editor triggers the save event calling your save code.
The editor is put in busy state by the save code.
The save code binds a callback function to your index.php request and then sends it to the server.
An error is raised due to the var_dump($_POST); statement. This error causes the execution of the code to stop and so never return to the editor which means the editor doesn't actually leave edit mode.
The request sent succeeds and on a response from the server the callback registered earlier (onStateChange) is called.
The onStateChange callback sets the editor to a non-busy state and fires the OK message because you got a 200 response from index.php.
This gives the illusion that everything went OK when actually an error occurred in your JavaScript. Checking the console you should see the error.

JSON data not showing up when I change http.jsonp() URL

I'm trying to read data from an external JSON file using AngularJS.
Here is my HTML
<div class="panel panel-default" ng-controller="MyAppController">
<div class="panel-heading">
<div class="input-group">
<input ng-model="query" type="text" placeholder="What file are you looking for?" class="form-control"><span ng-click="clearFilter()" ng-disabled="query.length == 0" class="input-group-addon"><i class="glyphicon glyphicon-remove"></i></span>
</div>
</div>
<div class="panel list-group">
<span data-ng-repeat="cat in cats | filter: query" class="list-group-item animate-repeat">{{cat.title}}
</span>
<div class="clearfix"></div>
</div>
</div>
It works fine when I use this in my JS file and data shows up in a list.
function MyAppController($scope, $http) {
var url = 'http://jobs.github.com/positions.json?callback=JSON_CALLBACK';
$http.jsonp(url).success(function(data) {
$scope.cats = data;
});
}
But when I change the URL to my personal site nothing shows up even though I literally just copied and pasted everything in the github JSON file to a local JSON file. (just to test it out)
function MyAppController($scope, $http) {
var url = 'http://ciagent.com/Website-files/positions.json?callback=JSON_CALLBACK';
$http.jsonp(url).success(function(data) {
$scope.cats = data;
});
}
http://ciagent.com/Website-files/positions.json?callback=JSON_CALLBACK &
http://jobs.github.com/positions.json?callback=JSON_CALLBACK have the same exact content but only the github one works with my angular app for some reason.
Any reasons as to why it's doing this?
Assuming you are using a static resource file you need to realize that the string 'JSON_CALLBACK' is a placeholder and gets modified within each $http.jsonp() request to something else.
You should be able to see this in the actual request URL in network tab of browser dev tools.
You can also open the github version in browser and change the value to see that it is not static on their server and will adjust to whatever value is sent.
If you want to use jsonp server side it needs to return dynamic value of the callback GET parameter value.
+1 to what #charlietfl said. Also, be sure to set Content-Type:application/javascript;charset=utf-8 in your response headers.

Categories