Using PHP, loading coupon deals in chunks - php

A site I'm working on takes table data, counts that table data and uses a standard loop to display it. Here's some of the code:
<?php
$output='';
$count=count($deal_datas);
$face_value="";
$deal_price="";
//var_dump(400*20/100);
$save_value='';
$save_value_present='';
$category_name='';
$cat_ids=array();
$deal_link='';
$address_array=array();
$address='';
$website_name='';
$website_data=array();
if($count!=0) {
for($i=0;$i<$count;$i++) {
$website_data=get_single_row("web_sites",array("id"=>$deal_datas[$i]->site_id));
if(count($website_data)!=0) {
$website_name=$website_data[0]->name;
}
$address_array=array();
$cat_ids=explode(",",$deal_datas[$i]->sub_category_ids);
if(count($cat_ids)!=0) {
$where_class=array("id"=>$cat_ids[0]);
$category_names=get_single_row("sub_category",$where_class);
if(count($category_names)!=0) {
$category_name=$category_names[0]->name;
} else {
$category_name="All";
}
} else {
$category_name="All";
}
$face_value=str_replace("USD","",$deal_datas[$i]->deal_face_value);
$face_value=str_replace("$","",$face_value);
$face_value=(int)str_replace(",","",$face_value);
$save_value_present=(int)str_replace("%","",$deal_datas[$i]->deal_save_percent);
if($deal_datas[$i]->deal_price!="") {
$deal_price=str_replace("USD","",$deal_datas[$i]->deal_price);
$deal_price=(int)str_replace("$","",$deal_price);
$save_value=$deal_price;
} else {
$save_value=$face_value*$save_value_present/100;
}
$time_zone_utc=$deal_datas[$i]->deal_oe_end_date;
$end_date=$time_zone_utc;
if($website_name!="kgbdeals") {
$deal_link=base_url()."deals/iframe/".$deal_datas[$i]->slug;
} else {
$deal_link=$deal_datas[$i]->deal_link;
}
if($deal_datas[$i]->deal_address==0 or $deal_datas[$i]->deal_zip_code==0) {
$deal_datas[$i]->deal_address="";
$deal_datas[$i]->deal_zip_code="";
}
if($deal_datas[$i]->deal_zip_code!="") {
$address_array[]=$deal_datas[$i]->deal_zip_code;
}
if($deal_datas[$i]->deal_address!="") {
$address_array[]=$deal_datas[$i]->deal_address;
}
$address=implode(" ",$address_array);
if($deal_datas[$i]->deal_city!="") {
if(empty($address_array)) {
$address.=$deal_datas[$i]->deal_city;
} else {
$address.=" - ".$deal_datas[$i]->deal_city;
}
//Check for valid image
$deal_image=base_url().'uploads/deals/'.$deal_datas[$i]->slug.'.jpg';
if(getimagesize($deal_image)) {
$valid_image=1;
} else {
$valid_image=0;
}
if($i%2==0) {
$output.='<div class="clsDeal_Whole_Cont clearfix">
Then it outputs the tabled list of data, etc.
Problem is, sometimes that data is sometimes 120 entries that are placed on the screen and the load takes ages.
What I want to do display the data 4 or 8 entries at a time. Then, as the user scrolls, add more in.
Alternatively - to load 4. Display them. Then load 4 more, display them. And so on, so that way the user actually gets to view the contents rather than waiting for the whole list (if this is simpler). Is that possible?
I'm not using jquery for this, though I know I would need to for the whole scroll down bit. So, would there be a way to rewrite the above php in order to display chunks of 4 until the final result is reached?

You have several problems here, beginning with how you ask the question. Be sure to include all the relevant code. You have a truncated code listing that doesn't deal with the problem at hand; how to break up a long set of data into a human readable format. You do not describe how you're getting your initial data $deals_data. The implementation details of how your format your output is not relevant to this question. Further, your code is a bit of the mess and doesn't follow the Single Responsibility Principle.
You should put your data selection and display functionality into single functions:
//returns n through z rows of data. If '0' is provided for finish, returns all rows
function getData($start=0, $finish=0 {
$data = array();
if ($finish == 0) {
//get all data
} else {
//get limited amount of data
}
return $data;
}
//returns first $limit rows of data as an html-encoded output string
function displayDeals($deal_data, $limit) {
...
}
That function should call a separate function for each of your rows:
//Returns a string of html-encoded data for one row
function displayRow($row_data) {
...
}
This displayRow function will be called $limit number of times by displayDeals. Once you get that working, it becomes much simpler to use AJAX for infinite scrolling. You simply create a php function:
function getMoreRows($start, $numberOfRows) {
$data = getData($start, $start+$numberOfRows);
$output = displayDeals($data, $numberOfRows);
return $ouput;
}
This will return that output to the AJAX function that called the php code. Because it's encoded as HTML you simply replace whatever available div with that new string.
Note that JQuery will make this AJAX easy, but you will need some javascript in order to make this functional, or suffer a long round-trip call to a new php page each time. The latter is easy, but avoids making the user interface smooth and lazy-loaded like you want. Here is how:
$.ajax({ url: '/my/site',
data: {action: 'getMoreData'},
type: 'post',
success: function(output) {
//replace your div with new data
}
});
On the server side you need a php page to handle the request:
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
switch($action) {
case 'getMoreData' : getMoreRows($_POST['lastDataIndex'], $_POST['numberOfRowsToFetch']);break;
// ...etc...
}
}
As a minor post-script about style: you should be cautious about mixing if and if-else styles, in regards to brackets. Generally, you want you code to be tight and quickly readable, and you want to never be in doubt if code is in a block. Personally, I always use brackets with if and if-else, but you should avoid using brackets in your if statement and not in your else case at the very least. Keep an eye on human readability, or you will find that you'll be frustrated by random bugs that arise because you assume a thing is or is not in a block when it's the opposite case.

It seems to me that, ostensibly, you want to paginate the data. That's easy to do. Just have next and previous buttons on your page which are dynamically generated to link to offsets in your list (i.e. page?offset = 4, page?offset = 8). Then just load four items (offset+1, offset+2, offset+3, and offset+4) on each page.

Related

fetching a different query from mysql

So I have a database of artists and they all show by default, if I click photographers they become hidden and only the photographers load after that, same for the makeup artists.
I'm achieving this by creating 3 php pages for fetching each with a different sql query--is there a way to do that without having 3 separate pages?
Because when I want to update the fetch page I need to update 3 of them now.
//click to load ph/mk
$( "#ph" ).click(function() {
$(".feed_item").hide();
fetch = 'fetch_ph.php';
load_contents(1);
});
$( "#mk" ).click(function() {
$(".feed_item").hide();
fetch = 'fetch_mk.php';
load_contents(1);
});
The best way (in my opinion) to achieve this is by putting all three functions into one PHP file and calling the actual method by sending a trigger to activate that function and return the information.
So make three functions (fetch_ph(), fetch_mk(), fetch_artists()) and then use a trigger word to get one of the functions to call.
So from my understanding of your question, this would be the best thing to do.
<?php
$triggerword = $_POST['triggerword'];
if ($triggerword === "mk")
{
fetch_mk();
}
else if ($triggerword === "ph")
{
fetch_ph();
}
else if ($triggerword === "artists")
{
fetch_artists();
}
function fetch_artists()
{
//function to get artists here...
}
function fetch_mk()
{
//function to fetch makeup artists...
}
function fetch_ph()
{
//function to fetch photographers...
}
?>

MySQL Query not returning newest results on setInterval

I am having a problem with setInterval in the $(document).ready(function(){}
What I am doing is setting the interval to do is call a PHP script that runs some MySQL queries to check the condition of 4 switches and then updating the screen with the values are in the database like so:
$(document).ready(function(){
setInterval(function(){
<?php require('fetchSwitchStatuses.php'); ?>
$("#switch1").css('background', 'rgb(<?php echo $switchColor1 ?>)');
$("#switch1").html('<?php echo $switchState1 ?>');
$("#switch2").css('background', 'rgb(<?php echo $switchColor2 ?>)');
$("#switch2").html('<?php echo $switchState2 ?>');
$("#switch3").css('background', 'rgb(<?php echo $switchColor3 ?>)');
$("#switch3").html('<?php echo $switchState3 ?>');
$("#switch4").css('background', 'rgb(<?php echo $switchColor4 ?>)');
$("#switch4").html('<?php echo $switchState4 ?>');
},1000);
});
Here is the code for fetchSwitchStatuses.php:
$connect = mysqli_connect("localhost", "root", "root");
mysqli_select_db($connect, "db_name");
$fetch1 = mysqli_query($connect,
"SELECT SwitchStatus FROM Switches WHERE PinNumber = '3'"
);
$fetch2 = mysqli_query($connect,
"SELECT SwitchStatus FROM Switches WHERE PinNumber = '5'"
);
$fetch3 = mysqli_query($connect,
"SELECT SwitchStatus FROM Switches WHERE PinNumber = '6'"
);
$fetch4 = mysqli_query($connect,
"SELECT SwitchStatus FROM Switches WHERE PinNumber = '9'"
);
$i = 1;
while($row = mysqli_fetch_array(${'fetch'.$i}))
{
if($row['SwitchStatus'] == 0)
{
${'switchColor'.$i} = "255, 0, 0";
${'switchState'.$i} = "OFF";
}
else if ($row['SwitchStatus'] == 1){
${'switchColor'.$i} = "0, 255, 0";
${'switchState'.$i} = "ON";
}
else {
${'switchColor'.$i} = "100, 100, 100";
${'switchState'.$i} = "ERROR";
}
$i++;
}
mysqli_close($connect);
When the page is loaded the information is correct, whatever is in the database is what is reflected by the colors on the screen.
When I click on the object to change the value, all of the necessary changes are made and the database is updated. However, the problem arises when the Interval is repeated. The values are switched back to whatever the original values were when the page was loaded. So, although the information is correctly changed in the database, for some reason the colors of the buttons is always reset to the first value read by the queries.
How can I fix this so that the information that is reflected on the screen is accurate?
With AJAX technology you can:
Send a request and get results from server by requesting a page (a .txt .js .html or even php).
So with AJAX you can get result of a page save something to database, get something from data base, you can work with sessions and anything you can do with a php file.
When you send an AJAX request to a see a page(i.e /userData.php?userId=5) the page /userData.php?userId=5 will be executed and its output will be returned.(HTML or just a word ‘yes’ or ‘no’ or ‘you can’t access to this user’s information’).
You can send data to file with POST or GET. But the question is how you can get data from page. Because the result AJAX will give you is what the requested page echoed to page like this
<html>
….
</html>
Or
‘Yes’
Or
<?php echo ‘something’; ?>
So what about getting a row of Date or lots of data? Because the only thing you are getting is a text or maybe a long text.
For that you can use JSON which Is something like nested arrays.
[
{
"term": "BACCHUS",
"part": "n.",
"definition": "A convenient deity invented by the...",
"quote": [
"Is public worship, then, a sin,",
"That for devotions paid to Bacchus",
"The lictors dare to run us in,",
"And resolutely thump and whack us?"
],
"author": "Jorace"
},
…
And this is a string too. But you can get Data in it with $.getJSON in jQuery and you can generate JSON data in server side like this.
<?php
$arr=array(
‘data’=>’ffff’,
‘anotherData’=>array(‘rrrrr’,’sssss’);
);
Echo json_encode($arr);
?>
Json_encode() in PHP gets an array and returns json string of it. And we echo it.
Now we can use jQuery to get Data which will be retrieved from server.
This section if from
Learning jQuery 1.3
Better Interaction Design and Web Development with Simple JavaScript Techniques
Jonathan Chaffer
Karl Swedberg
Global jQuery functions
To this point, all jQuery methods that we've used have been attached to a jQuery object that we've built with the $() factory function. The selectors have allowed us to specify a set of DOM nodes to work with, and the methods have operated on them in some way. This $.getJSON() function, however, is different. There is no logical DOM element to which it could apply; the resulting object has to be provided to the script, not injected into the page. For this reason, getJSON() is defined as a method of the global jQuery object (a single object called jQuery or $ defined once by the jQuery library), rather than of an individual jQuery object instance (the objects we create with the $() function).
If JavaScript had classes like other object-oriented languages, we'd call $.getJSON() a class method. For our purposes, we'll refer to this type of method as a global function; in effect, they are functions that use the jQuery namespace so as not to conflict with other function names.
To use this function, we pass it the file name as before:
$(document).ready(function() {
$('#letter-b a').click(function() {
$.getJSON('b.json');
return false;
});
});
This code has no apparent effect when we click the link. The function call loads the file, but we have not told JavaScript what to do with the resulting data. For this, we need to use a callback function.
The $.getJSON() function takes a second argument, which is a function to be called when the load is complete. As mentioned before, AJAX calls are asynchronous, and the callback provides a way to wait for the data to be transmitted rather than executing code right away. The callback function also takes an argument, which is filled with the resulting data. So, we can write:
$(document).ready(function() {
$('#letter-b a').click(function() {
$.getJSON('b.json', function(data) {
});
return false;
});
});
Here we are using an anonymous function as our callback, as has been common in our jQuery code for brevity. A named function could equally be provided as the callback.
Inside this function, we can use the data variable to traverse the data structure as necessary. We'll need to iterate over the top-level array, building the HTML for each item. We could do this with a standard for loop, but instead we'll introduce another of jQuery's useful global functions, $.each(). We saw its counterpart, the .each() method, in Chapter 5. Instead of operating on a jQuery object, this function takes an array or map as its first parameter and a callback function as its second. Each time through the loop, the current iteration index and the current item in the array or map are passed as two parameters to the callback function.
$(document).ready(function() {
$('#letter-b a').click(function() {
$.getJSON('b.json', function(data) {
$('#dictionary').empty();
$.each(data, function(entryIndex, entry) {
var html = '<div class="entry">';
html += '<h3 class="term">' + entry['term'] + '</h3>';
html += '<div class="part">' + entry['part'] + '</div>';
html += '<div class="definition">';
html += entry['definition'];
html += '</div>';
html += '</div>';
$('#dictionary').append(html);
});
});
return false;
});
});
Before the loop, we empty out so that we can fill it with our newly-constructed HTML. Then we use $.each() to examine each item in turn, building an HTML structure using the contents of the entry map. Finally, we turn this HTML into a DOM tree by appending it to the .
This approach presumes that the data is safe for HTML consumption; it should not contain any stray < characters, for example.

PHP Tagging - Recall the same script to update an array and query

I'm implementing a tagging system for my comics site.
The tagging function should:
allow the user to select multiple tags and display their selected tags out, selected tags should filter the comics shown
allow the user to deselect chosen tags, which would update their selected tags and update the returned comics
The part I'm having trouble with is in blue in the above image:
How can I make a call back to the same php script if a user chooses to delete a selected tag?
Thanks!
assuming you're just pushing elements into the $_SESSION array under a known key, isn't it acceptable to just check if the element exists? something similar to
if(isset($_SESSION[$tag])) {
unset($_SESSION[$tag]);
} else {
$_SESSION[$tag] = 1;
}
to use it, just use array_keys(). No need to change the JS side.
The first thing you could do, is send an array of tags that are being manipulated. They might be being added or removed - doesn't matter.
Javascript
$.get("getTags.php", {tags:["tag1","tag2","tag3"]}, function(data) {
//have PHP return an updated list of tags.
});
Then, you iterate the tags that were sent, and check if they existed already. If they existed, you remove them. Otherwise, you add them.
PHP
$tags = $_GET["tags"];
foreach ($tags as $tag) {
if (array_key_exists($tag, $_SESSION['tags'])) {
unset($_SESSION['tags'][$tag]);
} else {
$_SESSION['tags'][$tag] = $tag;
}
}
//Return your updated list of tags here.
You could then return an updated list of tags if you wanted, just to make sure that everything was in sync.
Another option would be to explicitly state what action you are performing, by sending an "action" parameter in the AJAX call:
Javascript
$.get("getTags.php", {action: "remove", tags: ["tag1"]}, function(data) {
//Do whatever
}
Then, handle that case in your PHP:
PHP
$availableActions = array("add", "delete");
$action = $_GET['action'];
//Make sure it's a valid action
$action = array_key_exists($action, $availableActions) ? $action : "add"; //Set a default.
//Now handle each action
switch ($action) {
case "add":
//Do stuff.
break;
case "delete":
//Do stuff.
break;
default:
}

javascript if checkbox is checked, href to ?page2, if at ?page2: keep cb checked, when unchecked, href to ?page1

Im totally new to javascript and i have no clue how to get this to work... I modified the code a little, but note that line 6 makes no sense. That is the main reason for this post.
<script>
function checkReloading() {
if (window.location.href.split=="?showpastdate") {
document.getElementById("showpastdate").checked=true;
} else {
document.getElementById("showpastdate").checked=false;
}
}
function toggleAutoRefresh(cb) {
if (cb.checked) {
window.location.replace("?showpastdate");
} else {
window.location.replace("");
}
}
window.onload=checkReloading;
</script>
Ok i think this is pretty readable.
First of all window.location.href.split doesn't work because I have to give in the full path. But how can I make this dynamic, so it can be used on more websites? Everywhere I see: window.location.protocol + "//" + window.location.host + "/" + window.location.pathname; but how do I implement this line of code for dynamic webpages? Can someone give me an example?
What I want to achieve with this code is:
When showpastdate is checked, href to ?showpastdate, when at ?showpastdate stay checked so i can use php $_GET on ?showpastdate. This works (when i use static full url). But than...
How do I have to modify this code so that the checkbox remains checked at ?showpastdate untill clicked again, than url goes back to original .php state or other GET var?
Sorry for asking for code writing, but I bet some of u can write this simple lines in 2 minutes while I'm surfing around for 8 hours. Not about to learn javascript, but this really would be a nice option for my program to toggle item showing past date ON/OFF, nicer than having 2 checkboxes, 1 for ON and 1 for OFF :x EDIT: + a submit button #(O _o)#
Thanx in advance.
.split() is a function you can execute on a string object, to split it up in pieces, depending on a parameter provided:
"abcdefg|hijklmnop|qrstuvw".split('|')
would result in a array like this:
["abcdefg","hijklmnop","qrstuvw"]
Now, I am guessing you have added a "?showpastdate" parameter to the url, to change a checkbox's "checked" status.
The easiest way to do that would be:
document.getElementById("showpastdate").checked = (~window.location.href.indexOf("?showpastdate"))
This part: window.location.href.indexOf("?showpastdate") Searches the href for
"?showpastdate"
If the string has been found, it will return a index. if not, it will return -1.
The squiggly in front of it is to convert the -1 or 0 (or higher) to a true / false.
I'm not quite sure what the toggleAutoRefresh() is supposed to do, though
Edit 1
Ah, for the toggleAutoRefresh(), just add this:
if (cb.checked) {
window.location.href.replace("?showpastdate","");
}
instead of that if-else block you have there.
The .replace() function works on a string the same way .split() does. It takes 2 arguments: What to look for, and what to replace it with.
So, for example:
var someString = "words and stuff"
var result = someString.replace(" ","_");
//result will be "words_and_stuff"
Edit 2
These functions should work:
function checkReloading() {
document.getElementById("showpastdate").checked = (~window.location.href.indexOf("?showpastdate"))
}
function toggleAutoRefresh(cb) {
if (cb.checked) {
window.location.href.replace("?showpastdate","");
}else{
window.location.href += "?showpastdate";
}
}
Where are you calling toggleAutoRefresh() from?
Edit 3
What I can conclude from your last comment, is that you want to do something like this:
// If a checkbox named "cb" is checked, and the url contains "?showpastedate"
if ((cb.checked) && ~window.location.href.indexOf("?showpastdate")) {
//Uncheck the checkbox and remove the "?showpastedate" from the url
document.getElementById("showpastdate").checked = false;
window.location.href.replace("?showpastdate","");
} else {
// Else, check the checkbox and add the "?showpastedate" to the url
document.getElementById("showpastdate").checked = true;
window.location.href += "?showpastdate";
}
Note the use of the "~" in front of the indexOf.
If string.indexOf("text") finds "text" at the beginning of a string, like it would in "tekstbooks bla bla bla", it returns 0. First index, starting count at 0.
This zero is interpreted as a false, when implicitly casting it to a boolean. So, if the indexOf were to find a result at the first index, it should (In this situation) return true to indicate a string has been found. That's why we apply the Bitwise NOT ~ to the results of indexOf. -1, indexOf's "Not found" value returns false, and all other results return true.
URL Change Event - JavaScript
http://help.dottoro.com/ljgggdjt.php
I think you could also use the onchange() javascript event.
I'll explain a little bit more.
I have a JQuery datatable, and through CSS I have different <tr classes>. Depending on the information stored in the database, these <tr> get a different class, thus a different color in the datatable.
Now for one <tr class> I'd like to give the user the option to hide/show. I was thinking to do this with a checkbox, and the javascript would parse an url when checked, and remove it when unchecked again. This URL can be used for php to run different queries, if $_GET['parsedurl']: query to show all tables, elseif $_GET['empty']: query for not showing that 1 information.
But this is the worst way to do it. I need to find something to toggle the display: none on or off of the table class, since this is working client-side.
So Im now thinking to keep the parsing of the javascript in an URL and depending on the URL, I run the .php GET to echo out <tr style: display: none> or just simply <tr>
Therefore I need some javascript which does this:
If checkbox is checked, redirect to projectlist.php?showpastdate
When URL = projectlist.php?showpastdate, make checkbox checked.
When URL = projectlist.php?showpastdate and checkbox gets unchecked, redirect to projectlist.php, where the checkbox is unchecked.
I think these triggers are the best options?
With .PHP I'll do:
if (isset($_GET['showpastdate']))
{
<tr style: display: none>
}
else
{
<tr>
}
Maybe someone has an even better solution? I'd like to hear!
Thanks.
EDIT
The javascript I now have is:
<script>
function toggleAutoRefresh(cb) {
if (cb.checked) {
window.location.replace("?showpastdate");
}
// If a checkbox named "cb" is checked, and the url contains "?showpastedate"
if ((cb.checked) && !~window.location.href.indexOf("?showpastdate")) {
//Uncheck the checkbox and remove the "?showpastedate" from the url
document.getElementById("showpastdate").checked = false;
window.location.href.replace("?showpastdate","");
} else {
// Else, check the checkbox and add the "?showpastedate" to the url
document.getElementById("showpastdate").checked = true;
window.location.href += "?showpastdate";
}
}
</script>
After checking the checkbox, it goes to the page projectlist.php?showpastdate and gets unchecked there. When checking again, it goes to projectlist.php?showpastdate?showpastdate. It should remove the ?showpastdate, not add another.
This is could do with PHP too, but I really don´t like a submit button for this checkbox. Just check and execute.
Okay. I got it.
<script>
function toggleAutoRefresh(cb) {
if (~window.location.href.indexOf("?hidepastdate") == 0){
window.location.replace("?hidepastdate");
document.getElementById("showpastdate").checked == true;
}
if (~window.location.href.indexOf("?showpastdate") == 0){
window.location.replace("?showpastdate");
document.getElementById("showpastdate").checked == true;
}
}
</script>
Now the URL gets toggled every time at clicking and PHP does the CSS display work.
Thanks for the effort and for pointing me to the right direction, Cerbrus! Saved me alot of time.

Mysql query overloading VPS

I have a text based game site (Mafia game) written in old php/mysql style. I have no to very less knowledge of PHP/MYSQL i am learning it though. So i am having problems with one of file which reloads every 5 second via ajax , it contains few Mysql query which checks messages, forum messages,transfer,attacks etc and depending on the check it shows alert to users if they get any new message,forum messages,transfer,attacks etc. My site is using VPS right now and if i set the refresh rate to 5 seconds it overlaods the VPS within few minutes so i have to set the refresh time to 20 seconds or more. I would like to know if there is any problems with query or any suggestion to optimize query/php code. Below is code of my file ajax.php which needs to be reloaded every 5 seconds
<?php
include("funcs.php");
global $tab, $time, $id, $tru, $old;
$round=$_GET['tru'];
$tO=0;
$moFo='r'.$round.'_mafiosi';
$brd=$tab['board'];
$query="select msg,atk,ivt,transf from $moFo where id='$id'";
$result=mysql_query($query);
$ans=mysql_fetch_assoc($result);
foreach($ans as $key=>$value)
{
$tO+=$value;
}
$rtn='#'.$mafioMsg;
echo "$tO$rtn";
?>
#
and below is the jquery/javascript i am using :
<script type="text/javascript" >
var onOff=false;
var replyText='';
window.onload=mainF;
function hideRedNotif()
{
document.getElementById('redNotif').style.display='none';
}
function mainF()
{
fetchNotif();
Updtr=window.setInterval(fetchNotif,25000);
}
function toggleNotif()
{
document.getElementById('redNotif').style.display='none';
if(onOff==false)
{
document.getElementById('parentReply').style.display='';
onOff=true;
}
else
{
document.getElementById('parentReply').style.display='none';
onOff=false;
}
}
function getAjxObject()
{
try {
var o=new XMLHttpRequest();
}
catch(exception)
{
var o=new ActiveXObject('Microsoft.XMLHTTP');
}
return o;
}
function fetchNotif()
{
roundN=document.getElementById('roundName').value;
var o=getAjxObject();
o.open('GET','notifAjx.php?openSes=in&&tru='+roundN,true);
o.onreadystatechange=execute;
o.send();
function execute()
{
if(o.readyState==4 && o.status==200)
{
var countF=0;
resp=o.responseText;
rsp=resp.split('#');
dom=document.getElementById('notifM');
dom.innerHTML=rsp[0];
//document.getElementById('chatRoller').innerHTML=rsp[1];
//if(rsp[1]!=replyText )
//{
//document.getElementById('redNotif').style.display='';
//replyText=rsp[1];
//}
}
}
}
function sendReply()
{
var o2=getAjxObject();
roundN=document.getElementById('roundName').value;
m=document.getElementById('replyText').value;
msg='&&reply=1&&msg='+m;
url='notifAjx.php?tru='+roundN+msg;
o2.open('GET',url,true);
document.getElementById('replyText').value='';
o2.onreadystatechange=execute;
o2.send();
function execute()
{
if(o2.readyState==4 && o2.status==200)
{
}
}
}
</script>
UPDATE- Thanks to everyone for checking my issue, I took screenshots of my DB tables please check if it helps or let me know what else should i provide.
http://i.imgur.com/VJSU2.jpg
http://i.imgur.com/5O6T0.jpg
I will appreciate any suggestion/help.
Thanks & Regards
Prashant
please check for indexing in the table '$moFo'
and check whats the volume of the data you are dealing with, if its high then do archive them or use sharding.
I expect you may have issues because if your asynchronous request takes more than 5 seconds, you'll start to get a backlog. It might sound counter-intuitive, but I recommend making your asynchronous requests a bit more synchronous:
Currently you're using setInterval to run your check every five seconds, regardless of whether a response has come back. What you could do instead is use setTimeout to get it started and then set another timeout when your response has come back, whether it was successful or not. This way, your responses will never start to overlap.
In practice:
Change your mainF() function to be
function mainF()
{
fetchNotif();
Updtr=window.setTimeout(fetchNotif,25000);
}
Then change your fetchNotif() execute() function to set another timeout once it's processed
Updtr=window.setTimeout(fetchNotif,25000);
You may want to wrap that one in an if to check for readyState == 4 but don't check for status == 200 because you probably want it to try again even if the previous attempt failed.

Categories