how to invoke JS/ajax with no submit button on the page? - php

i have a website page that contains only data of which one field gives the number of messages in your inbox, and i need to refresh this as new messages can some in at any time, so the user, while on this page can see there are new messages. how can i call my JS/ajax to do the refresh please?
i tried header("Refresh:10"); but client was not happy as it refreshes the whole page, he only wants the no of messages to refresh as they come in...can someone help please? thanks
my code for this page:
<?php use_stylesheets_for_form($search_form) ?>
<?php use_javascripts_for_form($search_form) ?>
<div id='div_longgray_gradient2'>
<div id='div_float_img'>
<br/>
<table width='96%' border='0'>
<tr>
<td colspan='2' align='right'>
<form action="<?php echo url_for('profiles/search' ) ?>" method="post" >
<table>
<tr>
<td>
<span class='spn_med_lightblue_rbc'>Profile Search
</span>
<?php echo $search_form['uc_other']->render(array('default')); ?> </td>
<td><input class='submit_img' type="image" src="/images/rainbow/gobuttonbluesmall.png" value="Submit" alt="Submit"></td>
</tr>
</table>
</form>
</td>
</tr>
<tr>
<td rowspan='2' width='40px' align='left'>
<img src='/images/rainbow/arrow.png'>
</td>
<td align='left'>
<span class='spn_big_black_rbc'>WELCOME <?php echo $usr_profile->getName() ?></span>
</td>
<td align='left'>
<?php
if (0)
{
// $filename = $usr_profile->getMsisdn();
$filename = $usr_profile->getProfilePicPath();
if ($filename && file_exists($filename))
{
$source = imagecreatefromjpeg($filename);
}
else
{
$filename = $usr_profile->getDefaultProfilePicPath();
$source = imagecreatefromjpeg($filename);
echo "<span class='spn_big_black_rbc'>You have not uploaded an image yet</span>";
}
}
if($usr_profile->existsProfilePic()==FALSE)
{
echo "<span class='spn_big_black_rbc'>You have not uploaded an image yet</span>";
echo "</br>";
}
if($usr_profile->checkForMissingInfo()== 1)
{
echo "<span class='spn_big_black_rbc'>You have some missing info</span>";
echo " ";
echo link_to('Edit','profile/edit','class=link_medium');
}
?>
</td>
</tr>
<tr>
<td align='left'>
<span class='spn_med_lightblue_rbc'>TO RAINBOW</span>
<span class='spn_med_black_rbc'>CODE</span>
<span class='spn_med_lightblue_rbc'>...SHINE ON</span>
</td>
<td>
</td>
</tr>
</table>
<br/>
<table class='table_border_light' width='820px'>
<tr>
<td class='td_header_blue' colspan='3' align='left'>
<span class='spn_big_black_rbc'>
MY FEEDS
</span>
</td>
<td class='td_header_blue' colspan='3' align='left'>
<span class='spn_big_black_rbc'>
RAINBOWCODE NEWS
</span>
</td>
</tr>
<tr>
<td valign='top' colspan='3' width='50%' align='left'>
<span class='spn_med_black_rbc'>You have <?php echo $new_mail_cnt ?> new </span>
<?php echo link_to('Messages','messagebox/list','class=link_medium_blue'); ?>
</br>
<span class='spn_med_black_rbc'>You have
<?php
echo sizeof($block_records);
?> blocked users </span>
</td>
<td valign='top'colspan='3' width='50%' align='left'>
<ul>
<li>
<a href="http://spreadsheets.google.com/a/miranetworks.net/spreadsheet/viewform?formkey=dEVlYTdJTzZiU0JPTnZqYWlZQTJRZ0E6MQ" class='link_medium_blue'> Rate us! Complete the online questionnaire</a></b>
</li>
<?php
foreach($news as $news_item)
{
echo "<li>".$news_item->getNews(). "</li>";
$newsId = $news_item->getId();
if ($newsId == 1)
{
//some echos here to display text
}
}
?>
</ul>
</td>
</tr>
<tr>
<td colspan='3' align='left'>
<span class='spn_big_black_rbc'>
MOOD BAROMETER
<?php echo link_to('how does it work?','util/barometer','class=link_medium_blue'); ?>
</span>
<?php
include_component('profile','moodmetershow');
?>
</td>
<td colspan='3' align='left'>
<?php
include_component('profile','moodmeter');
?>
</td>
</tr>
<tr>
<td colspan='3' align='left'>
</td>
</tr>
</table>
</div>
</div>
i added this for $new_mail_cnt:
echo $new_mail_cnt = '<script type="text/javascript">getMessages();</script>';
then i have:
<script language="JavaScript" type="text/javascript">
var receiveReq = getXmlHttpRequestObject();
var mTimer;
function getXmlHttpRequestObject()
{
if (window.XMLHttpRequest)
{
return new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
return new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
document.getElementById('p_status').innerHTML =
'Status: Cound not create XmlHttpRequest Object.' +
'Consider upgrading your browser.';
}
}
function getMessages()
{
receiveReq = getXmlHttpRequestObject();
if (receiveReq.readyState == 4 || receiveReq.readyState == 0)
{
receiveReq.open("POST", 'getMessage.php', true);
receiveReq.onreadystatechange = handleReceiveMessage();
receiveReq.send(null);
document.getElementById('new_messages').innerHTML = receiveReq.responseXML; //not sure here
}
mTimer = setTimeout('getMessage();',2000);
}
function handleReceiveMessage()
{
if (receiveReq.readyState == 4)
{
var chat_div = document.getElementById('div_chat');
var xmldoc = receiveReq.responseXML;
var message_nodes = xmldoc.getElementsByTagName("message");
}
}
</script>

AJAX is a technology which allows you to launch web requests to a server after the page is loaded. When using an AJAX request, the page does not have to reload (indeed, the user won't even notice a request is taking place).
You should launch an AJAX request to your server, which will check for any new messages.
To continuously check for new messages, you could create a timer using either the window.setTimeout, or the window.setInterval methods, to launch an AJAX request at designated periods.
Whilst I am not a big fan of promoting using libraries when a question does not mention any use of them, you may find that using one (such as jQuery), will greatly simplify the process of managing AJAX requests, as it comes with a complete module which does the hard work for you.
Regardless of whether you choose to use a library to perform your AJAX request or not, the workflow for the solution will be as follows:
On a timer (every 10 seconds say, launch an AJAX request) to a webpage on your server (e.g checkfornewmessages.php).
On your server, check for any new messages, and include what you want to display to the user in the output (e.g. the number of new messages, the title of the messages, whatever).
In your callback for your AJAX request, set the response of the AJAX call (which will contain the output you created in your PHP code), to the contents of one of the DOM elements on your page (e.g. <span class='spn_med_black_rbc'>You have <?php echo $new_mail_cnt ?> new </span>).

Try timer in javascript http://www.w3schools.com/js/js_timing.asp

I am assuming in your use_javascripts_for_form($search_form) you have a jQuery reference somewhere if not you can download it and include it in the headers
======NOTE UNTESTED======
Change the following line
<span class='spn_med_black_rbc'>You have <?php echo $new_mail_cnt ?> new </span>
to
<span class='spn_med_black_rbc'>You have <div id='newMessageDiv'><?php echo $new_mail_cnt ?></div> new </span>
Add something like the following into the HEAD tag
$(document).ready(function() {
$("#newMessageDiv").load
("newMessageCheck.php");
var refreshId = setInterval(function() {
$("#newMessageDiv").load('newMessageCheck.php?randval='+ Math.random());
}, 10000);
$.ajaxSetup({ cache: false });
});
This will attempt to refresh the div every 10 seconds with the contents of newMessageCheck.php, this file should just output a single value of just the amount of current new messages.

you put:
setTimeout(samefunction,milliseconds)
in the function that you want to auto-recharge and call the same
this create a infinite loop waiting x milliseconds

Related

In-Page Result Live Search

I need a search box that would throw a result just like how the CTRL+F works.
Right now, on my index.php page I have the ff format:
<table width="100%">
<thead>
<tr>
<th><strong>Client Name:</strong></th>
<th><strong>Nationality:</strong></th>
<th><strong>Birthday:</strong></th>
<th><strong>Address:</strong></th>
<th><strong>Gender:</strong></th>
<th><strong>Birthplace:</strong></th>
</tr>
</thead>
<?php
$sql=mysql_query(" select * from tenant order by id asc");
$count=0;
while($row=mysql_fetch_array($sql))
{
$client_id = $row['id'];
$clientName = $row['cname'];
$cbday = $row['bday'];
$cadd = $row['address'];
$cgender = $row['gender'];
$cbirth = $row['birthplace'];
if($count%2)
{
?>
<tbody>
<?php } else { ?>
<tr id="<?php echo $id; ?>">
<?php } ?>
<td>
<span class="text"><?php echo $client_id.". ".$clientName; ?></span>
</td>
<td>
<span class="text"><?php echo $cbday; ?></span>
</td>
<td>
<span class="text"><?php echo $cadd; ?></span>
</td>
<td>
<span class="text"><?php echo $cgender; ?></span>
</td>
<td>
<span class="text"><?php echo $cbirth; ?></span>
</td>
</tr>
</tbody>
<?php
$count++;
}//while-end
?>
</table>
I've already tried many JQuery and Ajax tutorials but none of them seems to work fine with a value. So I just got into conclusion that perhaps those tutorials could only work only if you have a pre-defined value for the table rows. Like this one for example:
<th>ClientName</th>
Anyway I can have a CTRL+F like search on my index page for the table rows?
Javascript, especially in combination with jQuery is very easy to learn and understand. No need for plugins or tutorials.
How to search the table?
Here is a jsfiddle I just wrote for you:
http://jsfiddle.net/j9U52/
$('#search-submit').on('click', function(event) {
var v = $('#search-value').val(); // get the search value
var t = $('.searchable td'); // WHERE to search
var c = 'highlight'; // css class to add to the found string
// for each td in the table
$.each(t, function(idx, el) {
// find the keyword
var regex = new RegExp("\\b" + v + "\\b", "gi");
// replace it and add a span with the highlight class
el.innerHTML = el.innerHTML.replace(regex, function(matched) {
return "<span class=\"" + c + "\">" + matched + "</span>";
});
});
});
I did not add to reset the highlighted matches when you enter a new search keyword, I leave this up to you :-) Hint: Add something like t.removeClass(c);

jquery not working on using pagination

Am just trying to show all the list in the pagination. am using datatable plugin's pagination on my file, pagination is working fine, in the list i have an image that have a function delete on click. in my pagination 1'st five records is shown . and the other five records shown on click next, delete function working properly on 1'st five record when i click on next than delete function stop it's working .
my code:-
<script>
var conf = jQuery.noConflict();
conf(document).ready(function(){
conf(".delete").on( "click", function() {
alert('adfasdfasd');
//alert(conf(this).attr("id"));
custid = conf(this).attr("id");
var r=confirm("Are you sure");
if (r==true)
{
var url = "<?php echo Mage::getBaseUrl();?>turnkey/index/deleteuser/";
conf.ajax({
type:"POST",
url:url,
data: { 'custid':custid},
success: function(msz){
alert(msz);
if(msz=="deleted") {
conf("#hidepro"+custid).hide("slow");
}
else {
//conf("#hidepro"+proid).hide();
alert("product cant be deleted");
}
//console.log("chal hun");
}
});
}
else
{
return false ;
}
});
});
</script>
and the pagination code is :-
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$('#example').dataTable();
} );
</script>
<div id="container">
<div id="demo">
<table cellpadding="0" cellspacing="0" border="0" class="display" id="example" width="100%">
<thead>
<tr>
<th>Factory</th>
<th></th>
<th>Contact</th>
<th>URL</th>
<th>Remove</th>
</tr>
</thead>
<tbody>
<?php
foreach( $custemail as $custemail1 ) {
$customer = Mage::getModel("customer/customer");
$customer->setWebsiteId(Mage::app()->getWebsite()->getId());
$customer->loadByEmail($custemail1); //load customer by email id ?>
<tr class="odd gradeX" style=" border-bottom: 1px solid #FF0000;" id = "hidepro<?php echo $customer['entity_id'] ?>">
<td class="bodyText style4" ><a style=" color: #CC3300;float: left;margin-top: 42px !important;text-decoration: underline;" href="<?php echo Mage::getBaseUrl();?>turnkey/index/listuser?id=<?php echo $customer->getEntity_id();?>"><?php echo $customer->getFactory();?></a> </td>
<td class="bodyText style4">
<a href="<?php echo Mage::getBaseUrl();?>turnkey/index/listuser?id=<?php echo $customer->getEntity_id();?>">
<img style=" width:100px;height:100px;margin-bottom:5px ;" src = "http://lab.ghrix.com/turn-key-mart/media/<?php echo $customer->getUserImage();?>"></a>
</td>
<td class="bodyText style4" style="padding-top: 10px;">
<?php echo $customer->getFirstname();?><?php //echo $customer->getUser_address();?><br><?php echo $customer->getmobile();?><br><?php echo $customer->getEmail();?></td>
<td class="bodyText style4" style="float: left;margin-top: 42px !important;" >
<a target="_blank" style="color:#005580;" href="<?php echo $customer->getWebsite();?>"><?php echo $customer->getWebsite();?></a></td>
<td class="bodyText style4"><div style= "cursor:pointer;" class = "delete" id = "<?php echo $customer['entity_id'] ?>"><img width="60px" src="<?php echo $this->getSkinUrl('images/trash.jpg'); ?>"</div></td>
</tr>
<?php }?>
</tbody>
</table>
</div>
</div>
please suggest where mistake is happen.
Without a live example, I can't be sure, but try this:
replace
conf(".delete").on("click", function() ...
with:
conf(document).on("click", ".delete", function() ...
The reason is that conf(".delete") only attaches to elements available at the time the function is run. It might be that your dataTable plugin runs first, removes the extra elements, then the delete binder is run and only works on the first 5. The second method binds to the document, and checks each click to see if it matches the .delete selector. This used to be known as jQuery.live()

Sql query on clicked button

I would like to ask how can I call Sql query when HTML button is pressed. I watched a couple tutorials, but never got it to work correct, thats why I would like to ask here.
So..I have a list of items displayed, and the list is generated from database. Here is how the code looks like:
<table width="100%" border="1" cellspacing="1" cellpadding="5" style="background-color:#FFC" >
<td>Id</td>
<td>Text</td>
<td>Solved?</td>
<td></td>
<?php
while( $array = mysql_fetch_assoc($queryRun) ) {
?><tr>
<td><?php echo $id = $array['id'].'<br />';?></td>
<td><?php echo $text = $array['text'].'<br />';?></td>
<td><?php echo $reseno = $array['solved'].'<br />';?></td>
<td><input type="button" value="Solve it" /></td>
</tr><?php
}?>
</table>
Now each item that is generated inside this loops has a button "Solved" at the end of the table, and I want to make it so when user click on that button, do a Sql query which changes a value of solved from 0 (false) to 1 (true).
You need ajax. write button onclick and make ajax call.
I've not tested this, but it should work.
Basically I've applied a class to anything to easily select stuff in jQuery:
<?php while ($array = mysql_fetch_assoc($queryRun)) { ?>
<tr class="row">
<td class="cell_id">
<?php echo $array['id']; ?>
</td>
<td class="cell_text">
<?php echo $array['text']; ?>
</td>
<td class="cell_solved">
<?php echo $array['solved']; ?>
</td>
<td class="cell_solve_it">
<input class="button_solve_it" type="button" value="Solve it" />
</td>
</tr>
<?php } ?>
Then I've created this short jQuery script:
$('.row').each(function(){
$('.button_solve_it', this).click(function(e){
e.preventDefault();
$.post(
'solve_query.php',
{
id: $('.cell_id', this).html(),
text: $('.cell_text', this).html()
},
function (data) {
$('.cell_solved', this).html('1');
}
);
});
});
In short:
when you click a .button_solve_it button, you make an AJAX request to solve_query.php, where you perform your SQL query.
Then, it sets the content of the row in Solved? column to 1 (or to true or whatever you want).

Changing Values in MYSQL By Clicking on Text?

I'm working on a small little social network project. So far i have a message system that all works fine, users can send and receive messages. I'm looking for a way to let users delete their own messages.
A 'delete' row has been set to display down the side of each message through an echo command.
Is there a way to make this text clickable so that when a user clicks it this then changes the value in the database from '0' to '1'?
Code:
<?php
$page_title = "Messages";
include('includes/header.php');
confirm_logged_in();
include('includes/mod_login/login_form.php');
?>
<div class="modtitle">
<div class="modtitle-text">Inbox</div>
</div>
<div class="modcontent">
<strong>Inbox</strong> | Sent Messages
| Deleted <br /><br />
<table
width="100%" border="0" cellpadding="5" cellspacing="0">
<tr
bgcolor="#CCCCCC">
<td width="30%"><strong>Recieved</strong></td>
<td width="20%"><strong>From</strong></td>
<td width="28%"><strong>Subject</strong></td>
<td width="0%"><strong>Read/Unread</strong></td>
<td width="0%"><strong>Delete</strong></td>
</tr>
<?php
$inbox_set = get_inbox();
while ($inbox =
mysql_fetch_array($inbox_set)) {
?>
<?php if ($inbox['read'] == 0) { ?> <tr bgcolor="#6666B3"> <?php }
if ($inbox['read'] == 1) { ?> <tr>
<?php } ?>
<td><?php
$datesent1 = $inbox['date_sent'];
echo "$datesent1"; ?></td>
<a href="profile.php?id={$inbox['from_user_id']}"><td><?php echo "<a
href=\"profile.php?id={$inbox['from_user_id']}\">{$inbox['display_name']}";
?></td></a>
<td><?php echo "<strong>{$inbox['subject']}</strong>";
?></td>
<td><?php if ($inbox['read'] == 0) {
echo "Unread";
}
if ($inbox['read'] == 1) {
echo "Read";
}
?></td>
<td>
<?php
if ($inbox['delete'] == 0) {
echo "Delete";
}
if ($inbox['delete'] == 1) {
echo "$deleted_set;";
}
; ?></td>
</td>
<?php }
?>
</tr> </table>
</div>
<?php include('includes/footer.php'); ?>
Use AJAX request to trigger proper action on server side.
Remember to check authorization otherwise one may delete messages owned by other users.
Use jQuery + Ajax to do this task similar like this
$.ajax({
type:"POST",
url: url, // action page url
data: "id="+id,
success: function(msg){
if(msg) {
//action here
}
});

Using jquery to load items on quiz. Why am I losing button to select next item when loaded?

I am dynamically loading question content into a div using jquery . This is my first attempt and it does load when I click the "Get Question"-button. However, the "Get Question"-button disappears when the question loads. I want the button to stay and eventually use it as a next question button.
Here is the jquery code:
<script type="text/javascript" src="../jquery/jquery/jquery-1.7.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(
$("#GetQuest").click(function(){
$.post("CCRN/question.php", {num : parseInt($("input#q_num").val()) + 1}, function (data) {
$("div#question").html(data);
$("input#q_num").val() = parseInt($("input#q_num").val()) + 1;
});
});
});
</script>
<input type="button" id="GetQuest" value="Get Question" />
<input type="hidden" id="q_num" value=1 />
<p>Question: <div id="question"> </div></p>
<p>Answer: <div id="answer"> </div></p>
Here is the question creating code (though the question loads and display fine)
<table width="100%"><?php
$i = $q_num;
if ($row["image"] <> NULL) { ?>
<tr align="center">
<td colspan="2" align="center">
<img src="<?php $pic = $row["image"]; echo $base_path . $pic; ?>" />
</td>
</tr><br />
<tr>
<td colspan="3"> </td>
</tr>
<?php
} ?>
<tr id="Qu<?php echo $i; ?>" class="Qu<?php echo $i; ?>">
<td width="7%"><?php echo $i.") " ?></td>
<td width="93%" ><?php echo $row["question"]; ?></td>
</tr>
<?php
for ($j=1;$j<=6;$j++) {
$bracket= "answer_" . $j;
if ($row[$bracket] !== NULL) {?>
<tr>
<td align="center" class="row<?php echo $j % 2; ?>" width="7%">
<input type="radio" <?php echo ($_POST["Q".$i] == $j) ? 'checked="checked"' : '' ; ?> name="Q<?php echo $i; ?>" value="<?php echo $j; ?>" /><?php echo chr(64 + $j); ?>
</td>
<td class="row<?php echo $j % 2; ?>" width="93%">
<?php echo $row["answer_".$j]; ?>
</td>
</tr> <?php
}
} ?>
</table><hr size="2" width="95%">
I do not understand why the button disappears when I load the question content. I am SURE it is something embarassing simple, which is why I am coming to a safe haven to minimize the ridicule! :)
Live test site http://www.GrowingSpeakers.com/index2.php to see the disappearing button.
You are using div with id "question" before.
<div class="TabbedPanelsContent" id="question">
and
<p>Question: <div id="question"> </div></p>
It does not matter even though the id's come from different files as long as they are displayed in the same DOM tree - they will be treated as one and the same.
You have 2 div's with the ID question and the javascript is going to replace the content of the first one found when you run:
$("div#question").html(data);
if you change the id for the first one it should work fine.

Categories