get message without re open div - javascript

Im working in a chat system very simple. But i have a problem. I can only get the other user messages if i close and re open the chat conversation div, then the message appears.
How can I solve this? The problem should be in this piece of code. As I am not very comfortable with ajax I ask for your help.
JS:
$(document).ready(function(){
var snd = new Audio("images/new_msg.wav");
var open=Array();
$("#jd-chat .jd-online_user").click(function(){
var user_name = $.trim($(this).text());
var id = $.trim($(this).attr("id"));
if($.inArray(id,open) !== -1 )
return
open.push(id);
$("#jd-chat").prepend('<div class="jd-user">\
<div class="jd-header" id="' + id + '">' + user_name + '<span class="close-this"> X </span></div>\
<div class="jd-body"></div>\
<div class="jd-footer"><input id="textareabox" placeholder="escrever..."></div>\
</div>');
$.ajax({
url:'chat.class.php',
type:'POST',
data:'get_all_msg=true&user=' + id ,
success:function(data){
$("#jd-chat").find(".jd-user:first .jd-body").append("<span style='display:block' class='me'> " + data + "</span>");
}
});
});
$("#jd-chat").delegate(".close-this","click",function(){
removeItem = $(this).parents(".jd-header").attr("id");
$(this).parents(".jd-user").remove();
open = $.grep(open, function(value) {
return value != removeItem;
});
});
$("#jd-chat").delegate(".jd-header","click",function(){
var box=$(this).parents(".jd-user,.jd-online");
$(box).find(".jd-body,.jd-footer").slideToggle();
});
$("#search_chat").keyup(function(){
var val = $.trim($(this).val());
$(".jd-online .jd-body").find("span").each(function(){
if ($(this).text().search(new RegExp(val, "i")) < 0 )
{
$(this).fadeOut();
}
else
{
$(this).show();
}
});
});
$("#jd-chat").delegate(".jd-user input","keyup",function(e){
if(e.keyCode == 13 )
{
var $cont = $('.jd-body');
var box=$(this).parents(".jd-user");
var msg=$(box).find("input").val();
var to = $.trim($(box).find(".jd-header").attr("id"));
$.ajax({
url:'chat.class.php',
type:'POST',
data:'send=true&to=' + to + '&msg=' + msg,
success:function(data){
$('#textareabox').val('');
$(box).find(".jd-body").append("<span style='display:block' class='me'> " + msg + "</span>");
$cont[0].scrollTop = $cont[0].scrollHeight;
$cont.append('<span>' + $(this).val() + '</span>');
$cont[0].scrollTop = $cont[0].scrollHeight;
$(this).val('');
}
});
}
});
function message_cycle()
{
$.ajax({
url:'chat.class.php',
type:'POST',
data:'unread=true',
dataType:'JSON',
success:function(data){
$.each(data , function( index, obj ) {
var user = index;
var box = $("#jd-chat").find("div#2").parents(".jd-user");
$(".jd-online").find(".light").hide();
$.each(obj, function( key, value ) {
if($.inArray(user,open) !== -1 )
$(box).find(".jd-body").append("<span style='display:block' class='other'> " + value + "</span>");
else
snd.play();
$(".jd-online").find("span#" + user + " .light").show();
});
});
}
});
}
setInterval(message_cycle,1000);
});

How messages are displayed when you first open the chat conv div ?
I'm assuming message_cycle() is supposed to display new messages in your div every second, i suppose your problem is here...
I'm not really confortable with this :
var box = $("#jd-chat").find("div#2").parents(".jd-user");
A div can't have an id starting with a number, you need <div id="chat2"> instead of <div id="2">.
After your line add a console.log('Box found : '+box.length) ; just to make sure your box is correctly found in message_cycle.

Related

keep the memory of more than one index

I have more than three TextBoxes. I want to send this data as in the code. The "indeks " value is always the last click. How do I keep the index?
click:function(e) {
var item = e.itemElement.index();
indeks = item;
}
var field= "";
onl: function () {
$.ajax({
type: "GET",
cache:true,
url: MYURL,
success: function (msg, result, status, xhr) {
var obje = jQuery.parseJSON(msg)
var i = 0;
field = " ";
$('#wrapper *').filter(':input').each(function () {
if (txtvalue != "") {
if (i)
field += " and ";
field = field + "[" + obje[indeks]+ "]" $(this ).val() + "'";
i++;
}
});
});
},
As I wasn't sure if I got your question right, I prefered to comment on your topic - but now it seems that my answer helped you, so I decided to post it as an actual answer:
1st step: declare an array outside your success handler
2nd step: push the index and the value for the element into this array
3rd step: loop through all entries of the array and build your 'select' statement
Here is your edited example:
https://jsfiddle.net/Lk2373h2/1/
var clickedIndexes = [];
click:function(e) {
var item = e.itemElement.index();
indeks = item;
}
var field= "";
onl: function () {
$.ajax({
type: "GET",
cache:true,
url: MYURL,
success: function (msg, result, status, xhr) {
var obje = jQuery.parseJSON(msg)
var i = 0;
field = " ";
$('#wrapper *').filter(':input').each(function () {
$(this).attr('id', i);
var txtvalue=$(this).val();
if (i)
clickedIndexes.push({
index: indeks,
value: $(this ).val()
});
var selectString = "";
for (var u = 0; u < clickedIndexes.length; u++) {
selectString += "[" + obje[clickedIndexes[u].index].ALAN + "]" + "=" + "'" + clickedIndexes[u].value + "'";
}
field = selectString;
i++;
});
});
},

Getting the currently active page id

BACKGROUND
My app consist of 2 static pages and x number of dynamically generated pages. The number of dynamically generated pages varies from time to time. My first static page is a login page. Once you login you are taken to the 2nd static page which is a welcome screen and then you can start swiping left to view the dynamically generated pages.
What i want to achieve
I basically want to get the page id of the currently active page. As in i want to get the id of the page i am currently viewing. i tried the following
pageId = $('body').pagecontainer('getActivePage').prop("id");
console.log('==========================>THIS IS ID: '+pageId);
It only gives me the page id of the 2nd static page and not the id of the dynamically generated pages because when i swipe left to view my dyanamically generated pages the console log does not print at all.
Here is the code for the entire relevant js
var widgetNames = new Array();
var widgetId = new Array();
//ActivePageId
var pageId = ''
$(document).on("pagecreate", function () {
$("body > [data-role='panel']").panel().enhanceWithin();
});
$(document).on('pagecreate', '#page1', function () {
$("#log").on('click', function () {
$.ajax({
url: "script.login",
type: "GET",
data: {
'page': 'create_user',
'access': 'user',
'username': $("input[name='username']").val(),
'password': $("input[name='password']").val()
},
dataType: "text",
success: function (html) {
console.log(html);
widgetNames = new Array();
widgetId = new Array();
var res = html.match(/insertNewChild(.*);/g);
for (var i = 0; i < res.length; i++) {
var temp = res[i].split(',');
if (temp.length >= 3) {
widgetNames[i] = (temp[2].replace('");', '')).replace('"', '');
widgetId[i] = temp[1].replace("'", "").replace("'", "").replace(/ /g, '');
}
}
var AllWidgets = ''
var testwidget = new Array();
var tempWidgetContent = html.match(/w\d+\.isHidden(.*)\(\) == false\)[\s\S]*?catch\(err\)\{ \}/gm);
for (var i = 0; i < tempWidgetContent.length; i++) {
var widgetContent = tempWidgetContent[i].substring(tempWidgetContent[i].indexOf('{') + 1);
testwidget[i] = widgetContent.replace("site +", "");
}
var widgetPart = new Array();
for (var i = 0; i < widgetNames.length; i++) {
var pageHeaderPart = "<div data-role='page' id='" + widgetId[i] + "' data-pageindex='" + i + "' class='dynPageClass'><div data-role='header' data-position='fixed'><a data-iconpos='notext' href='#panel' data-role='button' data-icon='flat-menu'></a><h1>BASKETBALL FANATICO</h1><a data-iconpos='notext' href='#page2' data-role='button' data-icon='home' title='Home'>Home</a></div> <div data-role='content'>";
var pageFooterPart = "</div><div data-role='footer' data-position='fixed'><span class='ui-title'><div id='navigator'></div></span></div></div>";
var check = "<div data-role='content'><ul data-role='listview'data-insert='true'><li data-role='list-divider' data-theme='b'>" + widgetNames[i] + "</div>";
widgetPart[i] = '<DIV style=\" text-align: center; background-color:#989797; font-size: 75pt;\" id=widgetContainer_' + widgetId[i] + '></DIV><SCRIPT>' + 'function UpdateWidgetDiv' + widgetId[i] + '() {' + testwidget[i] + '$(\"#widgetContainer_' + widgetId[i] + '").html(counterValue);' + '}' + 'setInterval(function(){UpdateWidgetDiv' + widgetId[i] + '()},3000)' + '</SCRIPT>';
AllWidgets += '<a href="#' + widgetId[i] + '" class="widgetLink" data-theme="b" data-role="button" >' + widgetNames[i] + '</a>';
var makePage = $(pageHeaderPart + check + widgetPart[i] + pageFooterPart);
makePage.appendTo($.mobile.pageContainer);
}
$('#items').prepend(AllWidgets).trigger('create');
//Get Active Page ID
$( ":mobile-pagecontainer" ).on( "pagecontainershow", function( event, ui ) {
pageId = $('body').pagecontainer('getActivePage').prop("id");
alert( "The page id of this page is: " + pageId );
});
}
});
});
});
Please advise and sorry if it is a bad question to ask as I am a beginner.
You were getting the active page from within the ajax call, not when swiping to a new page.
The detection code needs to fire when you are on one of the dynamic pages, show you could use pagecontainershow to detect the pageID as soon as the page displays (http://api.jquerymobile.com/pagecontainer/#event-show).
$( ":mobile-pagecontainer" ).on( "pagecontainershow", function( event, ui ) {
pageId = $(":mobile-pagecontainer" ).pagecontainer('getActivePage').prop("id");
});
UPDATE: Using pageid when updating pages:
It looks like you want an update every 3 seconds on the active page. so create a function for the entire page:
function UpdateActivePage(){
//get active page
pageId = $(":mobile-pagecontainer" ).pagecontainer('getActivePage').prop("id");
//figure out index
var idx;
for (var i=0; i<widgetId.length; i++){
if (widgetId[i] == pageid){
idx = i;
break;
}
}
//run your update
eval(testwidget[idx]);
$("#widgetContainer_" + pageid).html(updated stuff);
}
setInterval(UpdateActivePage, 3000);

jQuery - Loaded HTML Doesn't Respond to Clicks

Here is my original code:
<tr class="song" id="'.$this->i.'">
<td class="clickable" id="td1_'.$this->i.'">
...
</td>
</tr>
And the jQuery for that:
$(".clickable").click(function()
{
//
//Make only certain parts of songs clickable
//Hacky Way to Get Index
var temp = $(this).attr("id");
temp = temp.split('_');
var i = temp[1];
var status = $('#status_'+i).val();
alert('Clicked ' + i);
var maxid = $('#maxid').val();
if(status == "max") //if maximized
{
alert("max");
}
else
{
var user = $("#user_min"+i).val();
var ytcode = $("#ytcode_min"+i).val();
var title = $("#title_min"+i).val();
var artist = $("#artist_min"+i).val();
var genre = $("#genre_min"+i).val();
var score = $("#score_min"+i).val();
var ups = $("#ups_min"+i).val();
var downs = $("#downs_min"+i).val();
var id = $("#id_min"+i).val();
var upload_date = $("#upload_date_min+i").val();
//Maximizing New Song
dataString = 'user='+ user + '&ytcode=' + ytcode +
'&title=' + title + '&artist=' + artist +
'&genre=' + genre + '&score=' + score +
'&ups=' + ups + '&downs=' + downs +
'&id=' + id + '&upload_date=' + upload_date +
'&i=' + i;
$.ajax({
type: "POST",
url: "maxSongAjax.php",
data: dataString,
cache: false,
success: function(html){
$('#'+i).fadeIn(1000).html(html);
}
});
//Setting Max ID to New Song
$('#maxid').val(i);
}
return false;
});
I have the ajax returning identical html to what was replaced for testing purposes. However, after I click the loaded html, it does not respond to clicks. No pop-ups are shown from the alerts.
Why is this? How come the loaded html isn't responding like the first?
This is a very common issue for people new to jQuery; you have to use .live()
.click() only binds to existing elements.
An alternative to .live() is .delegate()

jquery get href and text from a tags on a page and show them in a div

This is my jquery code:
$(document).ready(function() {
var contentText = $.ajax({
url: "index.php",
async: false
}).responseText;
$("#defaultData").append(contentText);
$('img').each(function(){
$(this).remove();
});
//delegate?
var test = 0;
var href = 0;
var title = 0;
$('.btn').click(function(){
var href = $('a').each(function() {
$(this).attr('href');
});
console.log(href);
var test = $('a').each(function() {
$(this).text();
});
console.log(test);
$.each(href, function(i, val) {
$("#data").append(i + " => " + val + "<br/>");
});
$.each(test, function(i, val) {
$("#data").append(i + " => " + val + "<br/>");
});
});
//for (var i = 0; 50; i++) {
//var pageNum = $("a#specificLink").attr("href").match(/page=([0-9]+)/)[1];
});
What this code does:
It gets a page (index.php) prints it, removes the images and gets the href and text from all a-tags.
1st question:
text
should give me: link and text
but it gives me link and link :s
I realy don't get this
2nd question:
Alse I want to append the href and text to a div, seperated by semi colons.
So it looks like this:
link;text
link;text
...
Now I get:
link
link
text
text
...
This should give you all the link;text link;text
var test = "";
$('a').each(function() {
test += $(this).attr('href') + ';';
test += $(this).text() + ' ';
});
alert(test);
The reason you end up with link;link;link then text;text.. is because you are processing all links via
$.each(href, function(i, val) {
$("#data").append(i + " => " + val + "<br/>");
});
before even processing the texts. Add them at the same time as shown above.
I don't think that $('slector').each() is designed to return values. You should populate a viariable inside the loop like this:
var href = []
$('a').each(function() {
href.push($(this).attr('href'))
})
console.log(href)
Just to add, it appears that you're using .each the way that .map should be used:
var href = $('a').map(function() {
return this.href + ';' + $(this).text();
}).get();
$("#data").append(href.join(' '));

jquery javascript problem

Could you please take a look and tell why this isnt working i cant figure it out. the problem is with
$("#item_name").val(item_name);
$("#amount").val(course_price);
This should be adding info to 2 hidden inputs (
<input type="hidden" name="item_name" id="item_name"value="">
<input type="hidden" name="amount" id="amount" value="">
)
but they are coming up as blank
also the value from course_name.php?courseID=1 is Course Name,500
Full Javascript
<script>
$(document).ready(function() {
url = "date_range.php?courseID="+$('#course_name').val();
$("#dates").load(url)
url = "course_name.php?courseID="+$('#course_name').val();
var course_details;
$.get(url, function(data){
course_details= data;
});
split_course_details = course_details.split(',');
course_name=split_course_details[0];
course_price=split_course_details[1];
course_date=$("#date_range").val();
item_name=course_name+' - '+course_date;
$("#item_name").val(item_name);
$("#amount").val(course_price);
});
$('#course_name').change(function() {
url = "date_range.php?courseID="+$('#course_name').val();
$("#dates").load(url)
url = "course_name.php?courseID="+$('#course_name').val();
var course_details;
$.get(url, function(data){
course_details= data;
});
split_course_details = course_details.split(',');
course_name=split_course_details[0];
course_price=split_course_details[1];
course_date=$("#date_range").val();
item_name=course_name+' - '+course_date;
$("#item_name").val(item_name);
$("#amount").val(course_price);
});
</script>
Place your calculation inside the callback function of $.get(), like this:-
$(document).ready(function() {
url = "date_range.php?courseID=" + $('#course_name').val();
$("#dates").load(url)
url = "course_name.php?courseID=" + $('#course_name').val();
var course_details;
$.get(url, function(data) {
course_details = data;
split_course_details = course_details.split(',');
course_name = split_course_details[0];
course_price = split_course_details[1];
course_date = $("#date_range").val();
item_name = course_name + ' - ' + course_date;
$("#item_name").val(item_name);
$("#amount").val(course_price);
});
});
$('#course_name').change(function() {
url = "date_range.php?courseID=" + $('#course_name').val();
$("#dates").load(url)
url = "course_name.php?courseID=" + $('#course_name').val();
var course_details;
$.get(url, function(data) {
course_details = data;
split_course_details = course_details.split(',');
course_name = split_course_details[0];
course_price = split_course_details[1];
course_date = $("#date_range").val();
item_name = course_name + ' - ' + course_date;
$("#item_name").val(item_name);
$("#amount").val(course_price);
});
});
Try this:
$(function() {
var cname = $('#course_name'),
dates = $('#dates'),
iname = $('#item_name'),
amount = $('#amount'),
drange = $('#date_range');
cname.change(function() {
dates.load( 'date_range.php?courseID=' + this.value );
$.get('course_name.php?courseID=' + this.value, function(data) {
data = data.split(',');
iname.val( data[0] + ' - ' + drange.val() );
amount.val( data[1] );
});
}).change();
});
it seems like you're using url variable twice for different data...
try using additional variable..

Categories