Tampilkan postingan dengan label javascript jquery. Tampilkan semua postingan
Tampilkan postingan dengan label javascript jquery. Tampilkan semua postingan

Minggu, 15 Januari 2012

How to update div on 1st page by jquery code on 2nd page?

I planned to post my question to stackoverflow.com to ask some experts from there. But when I was typing my question in very detail on stackoverflow.com, then only I realize my code "hideposting();" show on 2nd page and it works to hide the posting from 1st page although the code is on 2nd page, so I stated think "why???" and I suddenly realize 1st page call the code from 2nd page, so the code on 2nd page is still on 1st page, that's why the code on 2nd page is working on 1st page!

Sometime we just need to think deeply and go for very detail then we will realize our problem is not a problem actually.

Anyway, since I types so many words for my question on stackoverflow.com, but I cannot click "submit" button because it is not a question for me anymore since I got the answer already, I feel it is wasted if I delete my question from stackoverflow.com, so I print screen and save the picture here :

Set focus after last character textarea

I have tried many solutions from this discussion but only 1 of them is working for me. Here is the codes :

Kamis, 13 Oktober 2011

Php and Ajax prevent resubmitting form when page reload or when click "back" button

Problem : Resubmitting form when click "f5" to reload the page. There are 3 different solutions :
Solution 1 :
1) page1.php does 3 different tasks :
Task 1 is show a textbox and submit button in a form if $_Get['success']=="true".
Task 2 is show errors message such as "name is used by other" or "multiple inputs too fast" if $_Get['success']=="false".
Task 3 is show the records from database if $_Get['success']=="".

2) page2.php does the data processing. Process the data after the user click submit button on page1.php. Then :
Task 1 is redirect the user to page1.php?success=true by code header('Location: page1.php?success=true'); if data process successful.
Task 2 is redirect the user to page1.php?success=false by the code of header('Location: page1.php?success=false'); if data process fail.

How it works?
1) User submit data by clicking the "submit button on page1.php,
2) Post method <form name="frm_register" action="page2.php" method="post"> jump to page2.php to process the data.
3) After page2.php finish process the data, it redirect user to page1.php?successful=true by header('Location: page1.php?successful=true'); (If you use header to redirect, the page will not remember anything happened previously, it will not remember page1.php did submit the form before). That's why it will not resubmit form when click "f5" to refresh the page1.php.

4) User submit data fail (because the name is used by other or because multiple input too fast), redirect to page1.php?success=false, and error message pop up.

5) If the user reload the page, it will still pop up the error message. It will not resubmit the form, because of this two reasons :
Reason 1 : The page doesn't show the form when $_Get['success']=="false".
Reason 2 : Just now you redirect to page1.php by header(), so page1.php will not remember the form is sent before.

6) If the user click "back" button, the page url will change the url back to page1.php?success=true which shows records and doesn't show the form. If click "back" button again, it will change the url back to page1.php which shows the form, but it will not resubmit the form because just now page2.php had redirected to page1.php by using header() which make page1.php forget everything in the past.

Note that header('Location: http://localhost/plekz/page1.php'); must has spacing after the sign of : and must have full path of url which has http://.

Weakness of solution 1 : If display records must depend of php if else statement, then you need to wrap the html codes of displaying records by php echo. It will be a lot of works to wrap all html in php echo.


Solution 2 :
1) page1.php does 2 different tasks :
Task 1 is show a textbox and submit button in a form if $_SESSION['error123']=="".
Task 2 is show error message if $_SESSION['error123']="samename".
Task 3 is process the data after the user click submit button :
- If process data successful, redirect user to page2.php to view records by code header('Location: page2.php');
- If process data fail because of same name or multiple input too fast, redirect use to page1.php?error123=samename by code header('Location: page1.php?error123=samename');

2) page2.php displays the records from database.

How it works?
1) User submit data by clicking the "submit button on page1.php,
2) Post method <form name="frm_register" action="page1.php" method="post"> jump to page1.php (same page) to process the data.
3) After finish process the data, it will use header() to redirect user to page2.php if no error, it will redirect user to page1.php if there is error.
If the user press "f5" button to reload the page or click "back" button, it will not resubmit the form because just now page1.php use header() to redirect this page, so this page won't remember everything in the past. So It don't remember the form is submitted before, so it will not resubmit the form when the user press "f5" button and "back" button.

Example of codes :

If you want to redirect user to page2.php after user click "OK" button on javascript alert box, u can use this codes : echo "<script type='text/javascript'>alert('Your info FAIL to be saved for this time, because each visitor can save info for 1 time per minute.'); document.write('Loading....'); window.location='page2.php'; </script>";

Note that header('Location: http://localhost/plekz/page1.php'); must has spacing after the sign of : and must have full path of ur which has http://


Solution 3 : You can use onclick to call ajax function to submit the form. So it will not recall the funtion to resubmit the form until u click submit button again. Example of codes :
Reference at http://stackoverflow.com/questions/7747569/prevent-resubmit-form-after-click-back-button/7747700

Jumat, 10 Juni 2011

Javascript detect active window and mouse moving / stop

Facebook won't update the new post on wall if you didn't move your mouse on the screen. It is because Facebook want to save bandwidth when you are not viewing facebook website. For example, if you open facebook website, but you away from keyboard/computer for 3 hours, maybe u go toilet or go out to work, facebook will not waste bandwidth to update new posts on wall. Facebook know you are afk by detecting your mouse movement. The same as Gmail switches your chat status from away to online / busy when you weren't having your gmail tab active for a while.

For my case, my website keep auto reload a javascript function for every 10 seconds by setInterval( "checklatestmsgidLive();", 10000 ); The function will still keep reloading the function even when the user is viewing other website on other tab. How to stop reloading it when the user is on other tab? How to make it reload the function only when the user is viewing my website? To do that, I just need to use window.onfocus and window.onblur function, but too bad IE cannot support it, so need modify the codes, adding if (/*@cc_on!@*/false) to detect whether or not the browser is IE. So now I can detect the user is on other tab or is active on my website. I also added mouse movement detection to determine the user is viewing my website by document.onmousemove. Too bad there is no document.onmousestop function, so need to do some trick on document.onmousemove function. Below is the codes :

<div id="test" style="color: black;">
mouse is stop</div">

<div id="test2" style="color: black;">
pause</div">


<script type="text/javascript">
document.onmousemove = (function() {                   
  var onmousestop = function() {
   document.getElementById('test').innerHTML="mouse is stop!!!";
  }, thread;

  return function() {
      document.getElementById('test').innerHTML="mouse is moving!!!";
    clearTimeout(thread);
    thread = setTimeout(onmousestop, 200);
  };
})();

function onBlur() {
    document.getElementById('test2').innerHTML="window is inactive, pause everything!";
};
function onFocus(){
     document.getElementById('test2').innerHTML="window is active";
};

if (/*@cc_on!@*/false) { // check if it is Internet Explorer the double c on is jsript that only ie has
    document.onfocusin = onFocus;
    document.onfocusout = onBlur;
} else {
    window.onload=window.onfocus = onFocus;
    window.onblur = onBlur;
}
</script>

You can view the Demo here.

Cannot have the same name of Javascript function on 3 differents pages!

Today I have spent 5 hours to find out the bug on my websites. My page structure is something like this : main page has 3 boxes - man, woman, animal. On the main page, I use jquery to fetch the information from man.php, woman.php, animal.php and display them onto the 3 boxes. Each of 3 pages (man.php, woman.php, animal.php) have a javascript function :
function showresponddiv(messagedivid){
        jQuery.get("showRespLive.php, function(data2) {
            $('#dialog .poptext').append(data2);
        });
};


The bug was when a user click on an information in the box of man by onclick=\"javascript:showresponddiv(this.id)\", supposedly it should call the function showresponddiv() on man.php, but it fail to do so. It will call the function showresponddiv() on other page like woman.php or animal.php. Why? It is because I use jquery to show them 3 pages together into 1 main page. So actually the function showresponddiv() was declare 3 times on the main page.

To fix the bug, just change the name of the functions to showresponddiv2() and showresponddiv3().

Selasa, 07 Juni 2011

How to check if receive new response on the posts that user responsed before?

Let's say there are 10 messages, I have posted 3 responses onto 7 messages. There are 3 messages that I never responded. The system need to check if the 7 messages receive a new response from other users, the system should not check the 3 other messages.

Question 1 : SELECT msg-id FROM responsesLive WHERE username='{$myUsername}'; //This will output many duplicated msg-id if I sent multiple responses onto a particular message. How to prevent the duplicated msg-id?
Answer : SELECT DISTINCT msg-id FROM responsesLive WHERE username='{$myUsername}';

Question 2 : After I got the msg-id, I need to get the rsp-id of last response in each of the messages. How to do that?
Answer :
$query3 = "SELECT msg-id, response, max(rep-id) FROM responseslive WHERE msg-id in (SELECT DISTINCT msgid FROM responsesLive WHERE username='{$myUsername}') GROUP BY msg-id";
$result3 = mysql_query($query3,$connection) or die (mysql_error());
confirm_query($result3);
while($rspinfo = mysql_fetch_array($result3)){
     $latestrsp-id= $rspinfo['max(rsp-id)'];
     echo $latestrsp-id . " | ";
}


Question 3 : Isn't I need to loop through all the posts that user responded before? Let's say the user responded on 99999 posts before, i need to check all the 99999 posts to see whether any of them receive a new response? Sure it will slow down the entire page. May I know how did facebook.com or plurk.com do that? I saw plurk.com can tell the user when a very very very old post received a new response. Maybe my steps are wrong? I guess what they do are something like this :

Let's say there are 10 messages, Peter posted comments onto 7 messages. Next time when a user post a new comment onto any 3 of the 7 messages, the website will show the count button "3 new comments". When peter click on the button, the website will show the 3 messages which has the new comments.
Step 1 : Select the message id when a user post a new comment onto the message.
Step 2 : Select all username of users that have posted comment onto the message before.
Step 3 : Add username and message id onto table "new_response_count" in database.
Step 4 : Compare logged in username to the username in table of "tblNew_response_count" in database :
If ($username-login == $username-in-new-rsp-count) {
    $query3 = "SELECT msgid FROM tblNew_response_count WHERE username='{$username-login}'";
    $result3 = mysql_query($query3,$connection) or die (mysql_error());
    confirm_query($result3);
    $numCount = mysql_num_rows($result3);
}


Step 5 : <a href="javascript:;" id="newrspbtn"><</a>

Step 6 : Pass msgid from php variable to javascript variable then jquery bind click like :
$('#newrspbtn').bind('click',function(){
    jQuery.get("showRSPtest.php?lastmsgID=" + love2, function(newitems){
        $('#div123').append(newitems);
    });
});

Step 7 : Every 10 seconds will auto reload the function of Step 4.

Note that when the user click the button, two tasks will be carried out : 1) all messages that has new response will be displayed, 2) delete the records (username and msgid) on tblNew_response_count in database.

Minggu, 05 Juni 2011

window.onload = function(){} VS $(document).ready (function(){}

$(document).ready(function(){
   //your code here
});

$(function(){
   //your code here
});

To wait until the page is finish loaded before execute particular code, you can use any one of jquery codes above. The both codes above are 99% the same. They are just make sure the codes of the pages are finish loaded, but they can't make sure the images on the pages are finish loaded. To detect images, you need to use the codes below :
window.onload = function(){
   //your code here
};

$(window).load(function(){
   //your code here
});

The 1st code above window.onload is normal javascript which is bad idea because it prevents you from setting onload from anything else or will erase any other "onload". To avoid overwriting the hooks that are already attached to the window.onload, attach your function with jQuery: $(window).load(function(){});

Selasa, 24 Mei 2011

javascript / jquery scroll to bottom of div when the page is loaded (IE problem)

In order scroll to bottom of div, you need to know the height of the div. The more contents inside the div, the more value of height. So basically you need to wait for all contents finish display on the div, then only you can get the height of the div, then only you can execute the function scrolling to bottom of div.

To scrolling to bottom, you just need javascript codes below :
<script type="text/javascript">
function asd(){
d = document.getElementById('div_id');d.scrollTop = d.scrollHeight;
}

asd();
</script>

It work perfectly on Firefox, but it is not working on IE. Why? Because the contents are not finish displayed inside the div before execute asd();. You need to wait for all contents finish rendered into the div, then only execute asd();. To do that, you can use either 1 of them :
1 - <body onload="asd()"> or
2 - jquery $(document).ready(function(){asd();}); or
3 - jquery $(function(){asd(); });.

The 3 methods above work perfectly when the contents of div are not fetched from other page by AJAX or Jquery. If you use ajax or jquery to fetch the contents from other page into the div. For example, jQuery.get("showMsg.php, function(data) { $('#div_id.span_class').append(data); });, you will have another problem on IE. The 3 methods are just to make sure the body/document is finish rendered, too bad they can't detect whether or not ajax/jquery has finish fetching data from other page into the div. To detect it, you can use this javascript functions :
function countdivnum(){
    var totalItems=$('#content div').length;
        if (totalItems<20){ // make sure all 20 items are loaded, then only start execute scroll funtion.   
        setTimeout("countdivnum();",1000);       
    } else if (totalItems==20){
        //alert("asdw");
        updatestatus();
        scrollalert();
    }
}

$('document').ready(function(){
    countdivnum();   
});

Let me explain the codes above. As I use ajax/jquery to fetch multiple <p>...</p> from other page into the div. When the page is loaded, I call countdivnum() which counting the number of <p>(s) inside the <div id="content">. If (totalItems<20) mean the contents are not finish loaded, so wait for 1 seconds then call coundivnum() again to count the number of divs again.

Minggu, 06 Februari 2011

Comment Tags For Every Coding

Html
<!-- comment here -->

Css
/*comment here*/

Javascript
<!-- comment 1 here
javascript code here
// comment 2 here -->
Without the <!-- and -->, the browser will display "comment here 1" as normal text. So if it is html document, you need to put <!-- and -->, if it is js document, you don't need to put <!-- and -->.

The two slash // tell the browser's JavaScript interpreter that the rest of the line is not valid JavaScript code.


Ajax
// comment here

Php
1) // comment here
2) # comment here
3) /* comment here */

Mysql
/* comment here */

Asp
'comment here

Jumat, 14 Januari 2011

Animated Mouse Cursor On Mozilla Firefox

Only IE can support .ani and .gif animated cursor. All other browsers like Firefox, Maxthon, Opera, Safari, Chrome are not support animated cursor. If you still want to show animated cursor on all browsers, you can use Javascript to make an animated picture to follow the movement of the mouse cursor. The complete codes are below :

Remember change the value of 3 variables below to fit your need :
<script type="text/javascript">
var trailimage=["http://2aek.com/images/cursors/cur1.gif", 32, 32] //image path, plus width and height
var offsetfrommouse=[8,27] //image x,y offsets from cursor position in pixels. Enter 0,0 for no offset
var displayduration=0 //duration in seconds image should remain visible. 0 for always.

if (document.getElementById || document.all)
document.write('<div id="trailimageid" style="position:absolute;visibility:visible;left:0px;top:0px;width:1px;height:1px"><img src="'+trailimage[0]+'" border="0" width="'+trailimage[1]+'px" height="'+trailimage[2]+'px"></div>')

function gettrailobj(){
if (document.getElementById)
return document.getElementById("trailimageid").style
else if (document.all)
return document.all.trailimagid.style
}

function truebody(){
return (!window.opera && document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}

function hidetrail(){
gettrailobj().visibility="hidden"
document.onmousemove=""
}

function followmouse(e){
var xcoord=offsetfrommouse[0]
var ycoord=offsetfrommouse[1]
if (typeof e != "undefined"){
xcoord+=e.pageX
ycoord+=e.pageY
}
else if (typeof window.event !="undefined"){
xcoord+=truebody().scrollLeft+event.clientX
ycoord+=truebody().scrollTop+event.clientY
}
var docwidth=document.all? truebody().scrollLeft+truebody().clientWidth : pageXOffset+window.innerWidth-15
var docheight=document.all? Math.max(truebody().scrollHeight, truebody().clientHeight) : Math.max(document.body.offsetHeight, window.innerHeight)
if (xcoord+trailimage[1]+3>docwidth || ycoord+trailimage[2]> docheight)
gettrailobj().display="none"
else
gettrailobj().display=""
gettrailobj().left=xcoord+"px"
gettrailobj().top=ycoord+"px"
}

document.onmousemove=followmouse
if (displayduration>0)
setTimeout("hidetrail()", displayduration*1000)
</script>


If you want to add this codes to your blogspot layout, you will have a lot of problem because blogspot html editor cannot accept some syntax of the codes. So it is better you write the code on a notepad file, save the file as blablabla.js then you link your blogspot to the js file. I did it for my own blog too. Here is my code : <script src='http://2aek.com/images/cursors/cursor.js' type='text/javascript'/>.