phonegap chat application user can see others message - javascript

I am using phonegap to develop an one to one chat application. My problem is when user click a contact and send a message. Then user click go back button and click another contact it can still see the message which he just sent to the first user.
Here is a part of my code:
Here is using ajax to get contact from server.When it success,it will generate a list view to show all contacts.
$.each(contacts, function(i,item)
{
output += '<li data-name='+item+'>' + item + '</li>';
$('#contacts_list').html(output).listview('refresh');
//Show the contact name on the front of chat page
$('#contacts_list').children('li').on('click', function ()
{
var contact_name=$(this).attr('data-name');
$('#contact_name').html(contact_name);
get_name(contact_name);
});
});
<!--When someone click a user in contacts, it will show the chat page-->
<div data-role="page" id="chat_page" data-role="page" data-theme="a">
<div data-role="header">
<h1 id="contact_name"></h1>
</div>
<div data-role="content">
<div id="incomingMessages" name="incomingMessages" class="msgContainerDiv" >
</div>
<label for="messageText"><strong>Message:</strong></label>
<textarea id="messageText"></textarea>
</div>
<div data-role="footer">
<fieldset class="ui-grid-a">
<div class="ui-block-a">
Go Back
</div>
<div class="ui-block-b">
<button data-theme="a" id="chatSendButton" name="chatSendButton">Send
</input>
</fieldset>
</div>
</div>
And here is part of ajax code where I using ajax to get chat data, then append them in to my chat page.
success: function(data)
{
var get_data = JSON.parse(data);
$("#incomingMessages").append
(
"<div class='message'><span class='username'>" +
(get_data.from || 'Anonymous') +"</span> : " +
(get_data.message || ' ') + "</br>" +
(get_data.message_time || ' ')
+"</div>"
);
}
});
I know the reason is when user click contact it will always go to the same page and that is why message can be seen to all of users.
Is there any solution for this?
Thanks in advance.

A simple solution will be to use local storage to store the history (#incomingMessages) and #messageText for each user.
Then you can clear #messageText and just reload it when the user reopens the chat.

You should clear #incomingMessages when you switch users. You are likely leaving the HTML content in that div when you want to be replacing it with the new user's messages.
Something like
$('#incomingMessages').html('')

Related

Clicking the browser back button after getting the confirmation page

I have a page where I have to fill the student details for example name, email and department. Once I fill the details and click the submit my button it goes to next page and it shows the entered student details in the next page.
Here I have shown the code step by step.
The below code after entering the details and clicking the submit button.
<div class="top-space-20">
<input class="btn btn-info" type="button" onclick="submitEvent()" class="btn" value="submit my details">
</div>
This is the script code for clicking the submit my details button.
function submitEvent() {
form = document.createElement("form");
form.method = "POST";
form.action = "/confirmation";
}
Once I clicked the button it goes to backend and fetch some details and it displays the confirmation.html page.
#app.route("/confirm",methods=['GET','POST'])
def confirm():
"Confirming the event message"
response_value = request.args['value']
return render_template("confirmation.html", value=json.loads(response_value))
#app.route("/confirmation", methods=['GET', 'POST'])
def ssubmit_and_confirm():
"submit an event and display confirmation"
if request.method == 'POST':
return redirect(url_for('confirm', value=value))
The below code is the confirmation.html page
<body style="background-color:powderblue;">
<div class="panel panel-default" style="max-width:1000px;max-height: 800px;margin-left:auto;margin-right:auto;">
<div class="panel-heading " style="text-align: center;">submit student details</div>
<div class="panel-body" id="resultDiv">
<div class="panel-group">
<div class="panel panel-default">
<div class="panel-body">
<label class="col-md-8" for="Date:">Date:
{{ value }}</br> Time :{{value}}</label>
<label class="col-md-8" for="dateApplied"></label>
</div>
</div>
<div class="panel panel-default">
<div class="panel-body">
<label class="col-md-8" for="student email:">
student email id:{{value}}</label>
</div>
</div>
</div>
</div>
</body>
So the problem here is once I come to the confirmation.html and if I click the browser back button it goes to the form and it lets me add the same details.
To avoid this I tried including this lines in the confirmation.html
</div>
<div><input type="hidden" id="reloadPage" /></div>
<script type="text/javascript">
$(document).ready(function() {
function reloadPage(){
location.reload(true); ; // RELOAD PAGE ON BUTTON CLICK EVENT.
// SET AUTOMATIC PAGE RELOAD TIME TO 5000 MILISECONDS (5 SECONDS).
var timerId = setInterval('refreshPage()', 5000);
}
});
function refreshPage() { clearInterval(timerId); location.reload(); }
</script>
But it's not working. I tried one more method which is given in the link
How to stop re submitting a form after clicking back button
This is also not working.
So what do I need is if I click the back button in the browser I should display the confirmation page only or it should tell this is not the authourized page.
Step 1:
On the form submission page, initially set the form submission value to false.
sessionStorage.setItem('form-submit', false)
Step 2:
And when submitting the form in previous page, check:
function submitEvent() {
formSubmitted = sessionStorage.getItem('form-submit')
if (!formSubmitted){
// Write your code here
}
}
Step 3:
On confirmation.html page, you can store a submission value in sessionStorage.
sessionStorage.setItem('form-submit', true)
You could add HTML5 history api. Use following code .
name = document.title
history.pushState(null,name,name)//add this code in your configuration.html file in document ready block
$(window).on("popstate",()=>{
//....Do whatever you want
/*If you want to display unauthorized page then
$(document).html("Unauthorized page")
*/
})
store the form data and reset the form just before the form data is sent to the server. Assuming that you are using $.ajax() to submit the form.
function submitEvent() {
form = document.createElement("form");
form.method = "POST";
form.action = "/confirmation";
// Add id attribute to the form
form.id = "student_details_form";
// Collect form data
// reset your form just before calling $.ajax() or $.post()
document.getElementById('student_details_form').reset();
// call $.ajax() or $.post()
$.ajax({
url: form.action,
// snipps
};
}

Random Quote Machine - Cant tweet quote

I have to tweet a quote that I randomly generated using APIs, but my code isn't working. Here is my code, I added comments trying to make it look clearer. I am a novice in coding so it probably has a terrible sintax.
I manage to get my quote by clicking on the "Get another quote" button, but when i want to tweet my quote, clicking on the "Tweet quote" button it wont work and i get the "Uncaught ReferenceError: data is not defined
at pen.js:10" error.
I dont know what i am doing wrong.
(This is a task for FreeCodeCamp). Thanks to everyone who will answer!
<link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet" type="text/css">
<h2 class="title">Random Quote Generator</h2>
<h4 class="subtitle">A project for the FreeCodeCamp challenge</h4>
<div class="container-box">
<div class="container-quote">
<p class="quote" id ="quote"></p>
<div class="container-author" id="author">
<p></p>
</div> <!--closing div for container author-->
<div class="row">
<div class="col-md-6">
<button id="tweetQuote" href="https://twitter.com/intent/tweet?text=data.quoteText">Tweet this quote!</button>
</div>
<div class="col-md-6">
<button id="newQuote">Get another quote</button>
</div>
</div> <!--row-->
</div> <!--closing div for container quote-->
</div> <!--closing div for container-->
And now the javascript
//setting html elements to variables
var $newQuote = $('#newQuote');
var $quote = $('#quote');
var $tweetQuote = $('#tweetQuote');
//execute function by clicking on button
$newQuote.click(getQuote);
$tweetQuote.click(tweetIt);
var text = data.quoteText;
var author = data.quoteAuthor;
//when getQuote is called call the APIs and get the quote by executing
getQuoteFromAPI
function getQuote() {
$quote.empty();
getQuoteFromAPI();
};
function getQuoteFromAPI() {
var url='https://api.forismatic.com/api/1.0/?
method=getQuote&format=jsonp&lang=en&jsonp=?';
//when the APIs are completely called execute the parseQuote function
$.getJSON(url).done(parseQuote);
//log the datas on the console and transform them into real html elements
function parseQuote (response) {
console.log(response);
document.getElementById('quote').innerHTML = response.quoteText;
document.getElementById('author').innerHTML = response.quoteAuthor;
};
};
function tweetIt() {
var url='https://api.forismatic.com/api/1.0/?
method=getQuote&format=jsonp&lang=en&jsonp=?';
$('#tweetQuote').attr('href', 'https://twitter.com/intent/tweet?text=' + text + '-' + author);
};

Dynamically Populate JQUERY Mobile Multi-Page Page

JQUERY Mobile Beginner Question: I have two pages in my simple multi-page JQUERY Mobile 'App'. When the user navigates to PAGE2, I want to do an AJAX call to get a JSON object containing a list of people + DB ID pairs. I want to present the list of people as buttons on PAGE2.
Code Snippet:
<div id="PAGE2" data-role="page">
<div class="ui-content">
// I want buttons to appear sequentially here
</div>
</div>
PAGE2 is my "placeholder" to populate with:
<input type="button" id="id1" name="id1" value="Bob Smith"/>
<input type="button" id="id2" name="id2" value="Jane Doe"/>
<input type="button" id="id3" name="id3" value="Kayla Kaye"/>
I'd also need to add a 'click' event handler in the script to react to the buttons. The reaction will be the same for all buttons (dynamically populate a PAGE3 with people detail, but I think I can figure that out if I see how PAGE2 population is correctly handled). What is the proper way to go about dynamically "creating" PAGE2 using the skeleton in place?
if jquery is allowed:
var elements = { id1:'Bob Smith', id2:'Jane Doe', id3:'Kayla Kaye'};
$.each( elements, function( key, value ) {
$("#PAGE2 .ui-content").append('<input type="button" id="' + key + '" name=" + key " value " + value +'"/>');
}
You can try this
$('#PAGE2').on('pagebeforeshow', function(){
var people = [
{ name:'Bob Smith', age:'56', place:'London'},
{ name:'John', age:'65', place:'USA'},
];
var btns;
$.each(people,function(indx,ppl){
btns = btns + '<input type="button" name="id1" value="' + ppl.name +'"/>';
});
$('#content_div').html(btns);
});
set id to div content to content_div
Here is a DEMO
With your 3 pages setup like this (I have added container divs for the buttons and details):
<div data-role="page" id="PAGE1">
<div data-role="header">
<h1>PAGE 1</h1>
</div>
<div role="main" class="ui-content">
Go to page 2
</div>
</div>
<div data-role="page" id="PAGE2">
<div data-role="header">
<h1>PAGE 2</h1>
</div>
<div role="main" class="ui-content">
<div id="thePeople"></div>
</div>
</div>
<div data-role="page" id="PAGE3">
<div data-role="header">
<a data-rel="back" class="ui-btn ui-btn-icon-left ui-icon-back">Back </a>
<h1>PAGE 3</h1>
</div>
<div role="main" class="ui-content">
<div id="theDetails"></div>
</div>
</div>
You can use the pagecontainer widget's beforeshow event to make your ajax call:
http://api.jquerymobile.com/pagecontainer/#event-beforeshow
In my example, I am checking where you are coming from and where you are going to. So coming from PAGE1 to PAGE2, I make the AJAX call and create the buttons. But if returning from PAGE3 to PAGE2, I just leave the already created buttons alone. Ater adding the buttons to the page, make sure and call .enhanceWithin() on the container so that jQM enhances the buttons.
$(document).on( "pagecontainerbeforeshow", function( event, ui ) {
var prevID = ui.prevPage.prop("id");
var newID = ui.toPage.prop("id");
if (prevID == "PAGE1" && newID == "PAGE2") {
//we have come from page 1 to page 2, so make AJAX call and populate page 2
var data = [
{ "id": "id1", "name":'Bob Smith'},
{ "id": "id2", "name":'Jane Doe'},
{ "id": "id3", "name":'Kayla Kaye'},
];
var buttons = '';
$.each(data, function(indx){
buttons += '<input type="button" name="' + this.id + '" value="' + this.name +'"/>';
});
$("#thePeople").empty().append(buttons).enhanceWithin();
}
});
Finally, when PAGE2 is created, I use event delegation to create a click event for any buttons that might be added (with event delegation, the buttons don't have to exist at the time the event is bound). In the event, get the id/name for the button that is clicked, get the details (Another AJAX call?), populate PAGE3, and then navigate to PAGE3 using the pagecontainer widget change method:
http://api.jquerymobile.com/pagecontainer/#method-change
$(document).on("pagecreate","#PAGE2", function(){
$(document).on('click', '#thePeople input[type="button"]', function(e){
var personid = $(this).prop("id");
var name = $(this).val();
$("#theDetails").text('Details for ' + name);
$( ":mobile-pagecontainer" ).pagecontainer( "change", "#PAGE3", { transition: "slide" });
});
});
DEMO

jQuery pass dynamically created variable to another function

I have form partial in Rails, laid out like so:
<div class"row">
<div class="col-md-6" id="top_level">
</div>
</div>
<div class"row">
<div class="col-md-2" id="sub_category1">
</div>
</div>
<div class"row">
<div class="col-md-2" id="sub_category2">
</div>
</div>
<div class"row">
<div class="col-md-2" id="sub_category3">
</div>
</div>
<div class"row">
<div class="col-md-3" id="sub_category4">
</div>
</div>
<div class"row">
<div class="col-md-3" id="sub_category5">
</div>
</div>
It is for selecting categories and sub-categories of items.
listings_controller:
def new
#product_listing = Listing.new
#product_ = Product.find(params[:product_id])
# gon.categories = EbayCategory.all
gon.top_level = EbayCategory.top_level
end
In the model:
scope :top_level, -> { where('category_id = parent_id').order(:id) }
Each category record (17989 of them) has a unique category_id, and a parent_id. As indicated above, the top level category_id = the parent_id for the same record. All the subcategories have their own category_ids, which are the parent_ids of the next level down, and so on, varying between 1 and 5 sub-levels.
I've tried a cascade of view files, which works fine (it renders the correct categories and sub-categories) but I can't pass the listing id that way because I don't know how to transmit 2 ids (one for the parent category, one for the listing id) through the params hash using the link_to url helper, so I lose the id for the listing I'm trying to create while navigating all the sub-categories.
So I'm trying it with jQuery, using the Gon gem. Not only does this mean loading the entire db table (about 7 MB, once I un-comment the line for use in level 2 thru 5) into ram, but I can't figure out how to pass the category_id from the dynamically created top_level list when one of its elements is clicked. There are many levels to go, but right now I'm just trying to console.log the category_id for ONE level, so I can see that it's registering. So far unsuccessful, after trying many different syntaxes and methods, of which this is the latest:
<script type="text/javascript">
$(gon.top_level).each(function(){
$("#top_level").append('<h5>' + this.main_category + " >" + '</h5>').data($(this).category_id);
})
$("#top_level").on('click', 'a', function(){
console.log($(this).data());
});
</script>
...returns
Object {}
to the console.
Any suggestions on how to store ids dynamically with the text category titles?
$('gon.top_level').each(function(){
var lnk = $('<h5>' + this.main_category + " >" + '</h5>')
.find('a').data({'category':$(this).category_id,'anotherKey':'value'});
$("#top_level").append(lnk);
});
$("#top_level").on('click', 'a', function(){
console.log($(this).data('category'));
console.log($(this).data('anotherKey'));
});
To set data use $(elment).data({key:value});
To get data use $(elment).data(key);

Displaying jQuery checkbox selection

This web page is currently displaying data from an "all" category from an rss feed once the page is loaded. My question is there are several categories which I would like the user to select and display. There are a total of 10 categories, and each correspond to a separate rss feed. Can anyone explain how I handle this event? Also, if one of the categories is selected, will it automatically override the current data being displayed? I will elaborate any unclear parts if needed. Thank you!
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$.ajax({
type: 'GET',
url: '/example',
dataType: 'xml',
success: function (xml) {
$(xml).find("item").each(function () {
var title = $(this).find("title").text();
var description = $(this).find("description").text();
var linkUrl = $(this).find("link").text();
//var link = "<a href='" + linkUrl + "' target='_blank'>Read More<a>";
var displaytitle = "<a href='" + linkUrl + "' target='_blank'>" + title + "</a>"
$('#feedContainer').append('<h3>'+displaytitle+'</h3><p>'+description+'</p>');
});
}
});
});
</script>
</head>
<body>
<div data-role="page" id="page">
<!-- /field panel -->
<div data-role="panel" id="fieldpanel" data-position="left" data-display="push">
<ul data-role="listview" data-inset="true" data-filter="false">
<fieldset data-role="controlgroup">
<legend>Categories</legend>
<input type="checkbox" name="checkbox-bio" id="checkbox-bio">
<label for="checkbox-bio">Bioengineering</label>
<input type="checkbox" name="checkbox-com" id="checkbox-com">
<label for="checkbox-com">Communications</label>
<input type="checkbox" name="checkbox-eleP" id="checkbox-eleP">
<label for="checkbox-eleP">Electrical/Power</label>
<input type="checkbox" name="checkbox-eleD" id="checkbox-eleD">
<label for="checkbox-eleD">Electronics/Design</label>
<input type="checkbox" name="checkbox-nano" id="checkbox-nano">
<label for="checkbox-nano">NanoEngineering</label>
<input type="checkbox" name="checkbox-opt" id="checkbox-opt">
<label for="checkbox-opt">Optics/Display</label>
<input type="checkbox" name="checkbox-semi" id="checkbox-semi">
<label for="checkbox-semi">Semiconductors</label>
</fieldset>
</ul>
</div><!-- /field panel -->
<!-- /settings panel -->
<div data-role="panel" id="settingspanel" data-position="right" data-display="push">
<ul data-role="listview" data-inset="true" data-filter="false">
<li>Join IEEE</li>
<li> subscription services</li>
</ul>
</div><!-- /settings panel -->
<div data-role="header" data-theme="b">
Menu
Settings
<h1>MOBILE</h1>
</div>
<div data-role="content">
<div id="feedContainer"></div>
<h3></h3>
<p></p>
</div>
<div data-role="footer">
<h4>Advertisements</h4>
</div>
</div>
</body>
</html>
I will assume you want to get the basic information about this code!
Ok, the first thing to handle is the type of the data to be shown.
<input type="checkbox" id="1" />
<input type="checkbox" id="2" />
Lets start with 2 instead of 10! The jQuery code for this would be easy to understand.
$('input[type=checkbox]').click(function () { // click on checkbox
var val = $(this).attr('id'); // get its id as value
if(val == '2') {
$('someelement).html('2 was selected');
$('#1').prop('checked', false); // unselect the other one
}
}
So, this is the basic code which will execute when a click event occurs on a checkbox. Now in your code you'll be using something like ajax then add the ajax request code before the .html() thing and write the response there.
To update the content being displayed you will be needed to use only one element as the basic clipboard for your app. Why? Because everytime you will get the data, you will be needed to replace the current content with that one and this way you will get only the current data; the selected data.
Lets try one checkbox from your code:
<input type="checkbox" name="checkbox-bio" id="checkbox-bio">
<label for="checkbox-bio">Bioengineering</label>
<input type="checkbox" name="checkbox-com" id="checkbox-com">
<label for="checkbox-com">Communications</label>
Now lets handle the jQuery
$('input[type="checkbox"]').click(function () {
// and all others will be here just as they are.. to check the id
// your ajax request is perfect, just copy paste that here..:)
});
But just need to make a change there, instead of sending the same request try to add one more thing there,
$.ajax({
// url and datatype here,
data: value
// success function goes here
});
Note that the value was the variable that we took from the checkbox. Which will be sent with the request so that you can process only the necessary part of the RSS and leave all other, just like an if else block.
Here is a working fiddle for this http://jsfiddle.net/afzaal_ahmad_zeeshan/KU9JT/.
But I am sorry, I didnot include the if else block to make the code work as it was meant to be. But you'll understand how to manipulate this.

Categories

Resources