I have a simple social networking site with chat functionality. I have used $.post a lot in multiple pages.
The code works well on all pages except message.php where the user message is posted and fetched multiple times with
$.post
(used to work well on local server).
When the messaging between users occur simulateously, the website stops to respond. On reload, the server goes down and ERR_EMPTY_RESPONSE message is shown. The website again comes into operation after a couple of minutes. To what I learnt, this is happening on pages that use $.post frequently.
To summarize the situation, I have created a live test page. An ERR_EMPTY_RESPONSE occurs when input is given continuously for some seconds.
The page contents:
a.php
<script>
$(document).ready(function(e) {
$(".abc").keyup(function(){
var a = $(this).val();
$(".showoff").text("wait..");
$.post('bbs.php',{a:a},function(abc){
$(".showoff").html(abc);
});
});});
</script>
<input type="textbox" class="abc">
<div class="showoff">Type to Change Me!</div>
bbs.php
<?php
echo $_POST['a'];
?>
I am hitting my head hard on the wall for a week. So, Please help me with this problem.
Thanks in Advance.
Sorry for my lame English as well.
As you appear to want an autocomplete type setup, use a timer. Reset it on each keypress and after a delay send your post. In this example it will send 3 seconds after the last keypress.
$(document).ready(function(e) {
var timer;
$(".abc").keyup(function() {
var $input= $(this);
// Start timer
clearTimeout(timer);
// Start a new 3 second timer
timer = setTimeout(function() {
// Once the
var a = $input.val();
$(".showoff").text("wait..");
$.post('bbs.php', {
a: a
}, function(abc) {
$(".showoff").html(abc);
});
}, 3000);
});
});
JSFiddle: https://jsfiddle.net/TrueBlueAussie/Locpnk35/
This will avoid overloading your server as no more than 1 request every 3 seconds can come from the same user. If the response is slower than 3 seconds you may also need to disable the key handler while an Ajax request is in progress.
Simplest answer would be you allow your server to be spammed to the point that it stops responding (yet still recieving new connections). If the connections are not closed(resolved) in time you will also hit limitation of concurrent browser connections to domain (which I think is really happening - browser blocking you in making those request).
You either switch to sockets, or send text to server on set interval of time. Alternatively you dont allow next post, till previous is resolved.
Instead of allowing your server to be spammed, you can remove the handler before the first post and set it back again when the post returns.
$(document).ready(function(e) {
var $abc = $('.abc'); //good idea to cache those jQuery selectors!
function abcPost() {
$abc.off('keyup', abcPost)
var a = $(this).val();
$(".showoff").text("wait..");
$.post('bbs.php', {
a: a
},
function(abc) {
$(".showoff").html(abc);
$abc.on('keyup', abcPost)
});
}
$abc.on('keyup', abcPost);
});
Ajax syncronous: Make the ajax call syncronous. This will stop its thread untill the response is back, easy to implement but comes with the downside that the user cannot type anymore untill request is solved
$.ajax({
url: 'bbs.php',
data: {a:a},
success: function(abc){
$(".showoff").html(abc);
},
async: false
});
Global variable check: make a global variable that checks the state of previous request and doesn't allow future ones until it is resolved:
var waiting=false;
$(".abc").keyup(function(){
if(!waiting){
waiting = true;
// code
$.post('bbs.php',{a:a},function(abc){
$(".showoff").html(abc);
waiting=false;
});
}
});
This is good.
var waiting=false;
$(".abc").keyup(function(){
if(!waiting){
waiting = true;
// code
$.post('bbs.php',{a:a},function(abc){
$(".showoff").html(abc);
waiting=false;
});
}
});
Related
I wanted to program a sort of panel from where i can send command to user For a live game that came to mind using jquery, javascript and php.
I take as a reference for every user using SESSION of php.
The initial user will have a
setInterval(function(){
var xml = new xmlHTTPRequest();
xml.open('GET','http://samepage.php?data= I don't know',false)
xml.send()
if(xml.responseText=="color"){
hideloader();
ShowFavoriteColorForm();
}
}, 3000);
The point is that I can't figure out how to use ajax to do a function that is waiting for something from another page (a string for example) and then perform other operations.
If there were examples or documentation in this regard, thank you very much.
Good afternoon,
I have the following functions that shows and hides a page busy loader:
busyStatusDelay = 1000; //milliseconds
var timer = null;
var show = false;
function busyShow(nodelay,delay) {
timer = setTimeout('busyDelayShow()',busyStatusDelay);
}
function busyDelayShow() {
if ($.active > 0) {
$('#json-overlay').css('display', 'table');
show = true;
}
}
function busyHide() {
clearTimeout(timer);
timer = null;
show = false;
$('#json-overlay').css('display', 'none');
}
This works great for normal ajax queries, we however have a new function that should send emails with SMTP, but this SMTP connection takes a few seconds too long to connect and send the emails.
To avoid this I want the ajax function to not trigger this loader, the function does not call the function to open the loader, but the issue is that when another function gets called that should open the loader, it picks up that there is an active connection so the loader comes back up and does not go away.
I tried to use the following so that the JS does not see it as an active request:
xhr.abort(); busyHide();
but when the ajax gets aborted the php aborts with it.
Note that the functions to send the emails should run in the background and should not wait for a response.
I have been searching for a way to disconnect from the server request without affecting the server's functions running and send the email.
I saw ignore_user_abort in another post so will be doing some reading up on this to see if this will work without affecting the rest of the system.
Thanks in advance for any tips on how to continue!
A good approach to this would be to execute your SMTP as a background process using some sort of queuing mechanism. So basically, whenever a JS triggers AJAX to mail, the PHP push the email request to a queue and send a response back to the XHR immediately. This way, your AJAX execution won't be blocked for long.
If you are using some sort of PHP framework like Laravel, it makes easier to manage queues otherwise have a look at this post.
My problem is basically the following: I have a webpage running an online radio on another subdomain (Airtime sourcefabric). Now I figured out that this radio plugin has a nice real-time API, so I can access the prevoius, the current, and the next track (and show) infos in JSON from this URL: http://music.wickedradionet.com/api/live-info .
I need to show these infos on the webpage. I can make it work with a javascript interval, updating the infos from the API URL every second (or every 5 second, doesn't matter), but I think there must be a better way doing this.
Is there any way to check if the file was changed, and update the infos only if they aren't the same? I think it can be done with some tricky PHP like setting up a CRON job, or maybe with a WebSocket thing. Any better way than checking it in a JS interval?
The javascript I use now for updating: http://wickedradionet.com/js/wickedradio-playlist.js
Below describes two ways on how you can improve your polling:
1) More efficient AJAX Polling
Instead of constantly performing an ajax request every second (whether or not you get the data), you can create a hacky open connection with the server to poll once the request is completed as shown below. The important part of the $.ajax() call is the complete option. The timeout (i.e. 30 seconds) is to make sure the polling continues if the cycle ever breaks.
(function betterPoll(){
$.ajax({ url: 'http://music.wickedradionet.com/api/live-info/', success: function (data) {
// do something with "data"
}, dataType: "json", complete: betterPoll, timeout: 30000 });
})();
2) WebSocket Connection
An even better alternative is WebSocket. This allows for a full-duplex, low-latency connection to stay open between the client and server, enabling "real time" communication.
If you're using Node.js, the docs provide examples on how you can use Socket.IO for WebSocket communication. If you're using PHP, a quick search led me to Ratchet and PHP WebSockets.
Below is an example using Socket.IO:
In your HTML:
<script src="https://cdn.socket.io/socket.io-1.3.5.js"></script>
<script src="example.js"></script>
In "example.js", you can have something like this:
var socket = io.connect('http://music.wickedradionet.com/api/live-info/');
socket.on('an event', function (data) {
// do something with "data"
socket.emit('another event', { other: 'data' });
});
On the server, you would do something similar using .on('another event', function () {}) and .emit('an event', function () {}).
You have exact time when the file will change, it is the time when next song starts. All you need to do is to calculate time difference to schedule new request.
function stringToDate(s) {
s = s.split(/[-: ]/);
return new Date(s[0], s[1]-1, s[2], s[3], s[4], s[5]*1);
};
function getPlaylistData() {
$.ajax({
dataType: "jsonp",
url: "http://music.wickedradionet.com/api/live-info/",
success: function (result) {
/* Change your DOM, than calculate time for next request this way: */
var requestTime = stringToDate( result.schedulerTime ).getTime() - result.timezoneOffset*1000;
var nextChange = stringToDate( result.next.starts ).getTime();
var differenceInMiliseconds = nextChange-requestTime;
console.log( differenceInMiliseconds );
setTimeout(getPlaylistData, differenceInMiliseconds);
}
});
};
$(document).on('ready', function () {
getPlaylistData();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
I'm building a forum and I use this code to load all the comments forum_retrieve.php and this works fine at this point.
$(document).ready(function() {
$('#results_holder').load('forum_retrieve.php<? echo ' ? forum_id = ' . urlencode($forum_id) ?>').show();
});
But when a user submits the form to forum_handle.php (to save the comment to sql) and gets redirected back using:
if ($connect->query($sql) === TRUE) {
header('Location: forums.php?id=' . $_POST['forum_id']);
} else {
the Ajax wont load the new results, even if I submit 5 comments, they wont load until I refresh the page or click on another page and come back.
I have even tried putting the ajax on a time delay of 30 seconds and it still wont load the new results even though I can see it in sql before the timer is up.
I have tried using no caching headers. I have also tried $(window).ready.
Shouldn't a new query be made every time the document is loaded?I don't get why its choosing not to. Any suggestion will be greatly appreciated.
First things first: load() is not intended to be used as you imagined, not at all. It just fires a function when your $('#results_holder') is loaded. That's it. You are passing no function there, hence you get no result.
Then, as pointed out by Daniel, the load() function is fired only once, as soon as the document is ready. Then the script stops to run, so there's no chance for it to work as you want it.
What you want to do is to fetch, from time to time, the content from forum_retrieve.php and display it in a proper container.
Try something like this:
$(document).ready(function() {
var forumID = '<?= urlencode($forum_id) ?>';
setInterval(function() {
$.get({
url: 'forum_retrieve.php',
data: {forum_id: forumID}
})
.done(function(data) { $('#results_holder').html(data); });
}, 10000);
});
This fires a function every 10000ms (= 10sec) to retrieve the content from forum_retrieve.php and inject it into the $('#results_holder') element. Let me know if it works!
I use Jquery-ajax calls to post information to a page and display the returned info. The problem I encounter is the following:
When a user makes the first ajax call everything seems normal. When a user does not reload the page and makes the same request for a second time the post-call is made 2 times and the get-call as well. The 3th time there are 4post+4get requests. 4th time 8Post/8Gets. And so on.. until the browser (firefox latest v.) freezes for a while.
I'm a beginning programmer and I don't know what the cause might be. I don't know where to look inside my code. Prehaps you guys can give me a hint. My other ajax requests are fine and only post+get once.
Firebug log:
This is a piece of my code:
$(document).ready(function() {
$('#datepicker').change(function()
{
sendDate($('#datepicker').val());
});
});
function sendDate(str)
{
$.ajax(
{
type: "POST",
url: "manage_processor.php",
data: { chosendate: str },
success: function(data)
{
$('#printdiv').html(data);
}
});
}
Hope anyone can shine some light on this situation.
If I might venture a guess, I suspect the returned data contains a script tag referencing your javascript file. This would explain the GET request you are seeing. Every time the request data is put into #printdiv your script is loaded again and an identical javascript handler would be bound to the same event. This would explain the number of handlers doubling after every request.
Quick test: put console.log( 'script loaded' ); at the top of manage_functions.js. If I'm right it will log after every request.