I've posted a question about it already, but I've figured out what is the exact problem. Now, I need a solution for that :)
Here's my code:
$('input[type="text"][name="appLink"]').unbind('keyup').unbind('ajax').keyup(function() {
var iTunesURL = $(this).val();
var iTunesAppID = $('input[name="iTunesAppID"]').val();
$.ajax({
type: 'POST',
url: jsonURL,
dataType: 'json',
cache: false,
timeout: 20000,
data: { a: 'checkiTunesURL', iTunesURL: iTunesURL, iTunesAppID: iTunesAppID },
success: function(data) {
if (!data.error) {
$('section.submit').fadeOut('slow');
//Modifying Submit Page
setTimeout(function() {
$('input[name="appLink"]').val(data.trackViewUrl);
$('div.appimage > img').attr('src', data.artworkUrl512).attr('alt', data.trackName);
$('div.title > p:nth-child(1)').html(data.trackName);
$('div.title > p:nth-child(2)').html('by '+data.sellerName);
$('span.mod-category').html(data.primaryGenreName);
$('span.mod-size').html(data.fileSizeBytes);
$('span.mod-update').html(data.lastUpdate);
$('select[name="version"]').html(data.verSelect);
$('input[name="iTunesAppID"]').attr('value', data.trackId);
}, 600);
//Showing Submit Page
$('section.submit').delay('600').fadeIn('slow');
} else {
$('.json-response').html(data.message).fadeIn('slow');
}
},
error: function(jqXHR, textStatus, errorThrown) {
//$('.json-response').html('Probléma történt! Kérlek próbáld újra később! (HTTP Error: '+errorThrown+' | Error Message: '+textStatus+')').fadeIn('slow');
$('.json-response').html('Something went wrong! Please check your network connection!').fadeIn('slow');
}
});
});
The Problem and Explanation:
Every time a key is triggered up it loads this ajax. If my JSON file finds a keyword it returns with error = false flag. You see, if it happens, it loads the effects, changing, etc...
The problem is that when you start to type, for example asdasdasd and just after that I paste / write the keyword there'll be some ajax queries which ones are still processing. These ones are modifying and loading the fadeOut-In effects X times.
So I'd need a solution to stop the processing ajax requests, while an other key is pressed!
Thanks in advance,
Marcell
Personally I would have the script wait so it didn't fire on each keyup. Actually I would probably use http://jqueryui.com/autocomplete/
But you can just abort the ajax before trying again.
...
var iTunesAppID = $('input[name="iTunesAppID"]').val();
if (typeof req!='undefined' && req!=null) req.abort();
req = $.ajax({
...
try adding the option async: false to your ajax this will prevent any other calls until the current one is finished.
Related
I have created a long polling using jQuery / PHP. and it is working perfectly. The issue is when a user click on other links or refresh the current page, it will hang on the current page till it get response from last AJAX request from server.
I have set about 30 sec in the server side to pick the latest data, means if someone sent a request to get the latest data, he cannot go to another page or refresh the current page till it returns the response. The worse case is, if the server didnt find the latest data, it will send the response after 30 sec.
I have use the following code to abort the request.
window.onbeforeunload = function(event) {
xhr.abort();
}
I have check on the console before and after execute xhr.abort() it shows readyState=1 and then readyState=0. Does this means xhr.abort() executed successfully? But why still the page hang on the current page till it returns the response.
Please help me to solve my issue. I don't want to wait until the server response when user click on other link or refresh page or do other stuff on the page.
This is my jQuery code
function setNoti(ntotal)
{
var t;
xhr = $.ajax({
type: "POST", url: myURL, data: "", dataType: "JSON", cache: false, async: true,
success: function(data) {
// do my work here
clearInterval(t);
t = setTimeout(function() {
setNoti(20);
}, 1000);
return false;
},
error: function()
{
clearInterval(t);
t = setTimeout(function() {
setNoti(0);
}, 40000);
return false;
}
});
}
You are assigning an xhr which can then be used to abort the request on subsequent calls to the function.
function setNoti(ntotal)
{
if (xhr) {
xhr.abort();
}
var t;
xhr = $.ajax({
type: "POST", url: myURL, data: "", dataType: "JSON", cache: false, async: true,
success: function(data) {
// do my work here
clearInterval(t);
t = setTimeout(function() {
setNoti(20);
}, 1000);
return false;
},
error: function()
{
clearInterval(t);
t = setTimeout(function() {
setNoti(0);
}, 40000);
return false;
}
});
}
No need for the window.onbeforeunload handler, which being a separate event is likely being called at the wrong time.
I have added session_write_close() in the server side and it is working perfectly. Following post helped me to find the solution :)
Multiple AJAX requests delay each other
I'm having trouble with lag and script execution.
I have the following code:
$(function(){
$("#results").html("Loading work order queue...");
setInterval("showWorkOrders();", 15000)
});
function showWorkOrders()
{
$.ajax({
url: '/ajax/job_queue_ajax.php',
type: 'POST',
cache: false,
data: 'update=true',
success: function(data)
{
$("#results").html(data);
$('span#ref_msg').html('');
},
error: function()
{
a = new customModal('ajax');
$("#results").html("<font class='msgDivError'>"+a.ajaxError+"</font>");
$('span#ref_msg').html('');
}
});
}
My backend PHP (only an example):
$SQL = MySQL_query("SELECT * FROM table")
while($data = MySQL_fetch_array($SQL))
{
//// OUTPUTS A TABLE WITH INFORMATION
}
Now, this whole thing executes however with a lot of lag (takes very long to load) and sometimes creates an script error because it took too long to load. If I extend the refresh interval, things start getting better (the lag remains) and I don't get the execution error. I need to have a short interval for what I need, but I cannot figure out an efficient way of doing so. Any suggestions on how to improve this?
Also, after a while of being on the page that has the refresher, the browser becomes extremely slow to the point where it locks...
I would solve it using setTimeout instead:
$(function(){
$("#results").html("Loading work order queue...");
showWorkOrders();
});
function showWorkOrders()
{
$.ajax({
url: '/ajax/job_queue_ajax.php',
type: 'POST',
cache: false,
data: 'update=true',
success: function(data)
{
$("#results").html(data);
$('span#ref_msg').html('');
setTimeout("showWorkOrders();", 5000)
},
error: function()
{
a = new customModal('ajax');
$("#results").html("<font class='msgDivError'>"+a.ajaxError+"</font>");
$('span#ref_msg').html('');
setTimeout("showWorkOrders();", 5000)
}
});
}
This would mean that it waits 5s before doing a new ajax request, the previous one can take however long it wants. Still waits 5s before it tries again.
Try this. Start next request only after response from server.
$(function(){
$("#results").html("Loading work order queue...");
showWorkOrders();
});
function showWorkOrders()
{
$.ajax({
url: '/ajax/job_queue_ajax.php',
type: 'POST',
cache: false,
data: 'update=true',
success: function(data)
{
$("#results").html(data);
$('span#ref_msg').html('');
setTimeout(showWorkOrders, 15000);
},
error: function()
{
a = new customModal('ajax');
$("#results").html("<font class='msgDivError'>"+a.ajaxError+"</font>");
$('span#ref_msg').html('');
setTimeout(showWorkOrders, 15000)
}
});
}
Instead of Ajax on interval, I'd suggest next Ajax after completion.
Since the ajax request takes an indeterminate amount of time to complete, I would suggest that you trigger the next ajax request when the first one completes using setTimeout() and so on like this so that you never have multiple ajax requests going at once and so each subsequent ajax call starts a known time from when the previous one completed.
You probably want to troubleshoot why your server is taking so long to respond to the request, but you can also extend the timeout for the ajax call if your server sometimes takes a long time to respond:
function showWorkOrders()
{
$.ajax({
timeout: 15000,
url: '/ajax/job_queue_ajax.php',
type: 'POST',
cache: false,
data: 'update=true',
success: function(data)
{
$("#results").html(data);
$('span#ref_msg').html('');
setTimeout(showWorkOrders, 5000);
},
error: function()
{
a = new customModal('ajax');
$("#results").html("<font class='msgDivError'>"+a.ajaxError+"</font>");
$('span#ref_msg').html('');
setTimeout(showWorkOrders, 5000);
}
});
}
$(function(){
$("#results").html("Loading work order queue...");
showWorkOrders();
});
I have a confirmation dialog that leads to an update query when the user clicks a link.
<div class="ui-bar">
<a id="confirm" href="#" data-strid="<?php echo $str_info['str_id'] ?>">Confirm</a>
</div>
What I am looking to do is run an update query, then reload the previous page with the updated information on it.
I thought I accomplished this, but some sort of error keeps popping up in firebug and the ajax doesnt seem to be successful. The error only comes when I reload the page...and when I put a delay on it, there is no error, so I can't even read what it is.
<script>
$('#confirm').click(function (){
var str_id = $("#confirm").data("strid");
$.ajax({
type: "POST",
async: true,
url: '../../ajax/add_land',
dataType: 'json',
data: { str_id: str_id },
success: function(){
}
});
$('.ui-dialog').dialog('close')
setTimeout(
function()
{
location.reload()
}, 750);
return false;
});
</script>
Is there any good way of accomplishing this? Again, in summary, I am looking to perform an update query, then reload the last viewed page (not the dialog) so that the changed info is displayed. ../../ajax/add_land is in PHP.
There are few better ways of achieving this but that is beyond the point, in your case you should do this:
<script>
$('#confirm').click(function (){
var str_id = $("#confirm").data("strid");
$.ajax({
type: "POST",
async: true,
url: '../../ajax/add_land',
dataType: 'json',
data: { str_id: str_id },
success: function(){
$('.ui-dialog').dialog('close');
location.reload();
}
});
return false;
});
</script>
When ajax call is successfully executed it will call code inside a success callback. Ajax call is asynchronous action, that means rest of the code is not going to wait for it to finish. Because of this success callback is used. So there's need for the timeout.
One more thing, there's also an error callback, use it to debug ajax problems:
error: function (request,error) {
alert('Network error has occurred please try again!');
},
I'm programming a site, and I've got a problem.
I have the following jQuery code:
$('input[type="text"][name="appLink"]').keyup(function() {
var iTunesURL = $(this).val();
var iTunesAppID = $('input[name="iTunesAppID"]').val();
$.ajax({
type: 'POST',
url: jsonURL,
dataType: 'json',
cache: false,
timeout: 20000,
data: { a: 'checkiTunesURL', iTunesURL: iTunesURL, iTunesAppID: iTunesAppID },
success: function(data) {
if (!data.error) {
$('section.submit').fadeOut('slow');
//Modifying Submit Page
setTimeout(function() {
$('input[name="appLink"]').val(data.trackViewUrl);
$('div.appimage > img').attr('src', data.artworkUrl512).attr('alt', data.trackName);
$('div.title > p:nth-child(1)').html(data.trackName);
$('div.title > p:nth-child(2)').html('by '+data.sellerName);
$('span.mod-category').html(data.primaryGenreName);
$('span.mod-size').html(data.fileSizeBytes);
$('span.mod-update').html(data.lastUpdate);
$('select[name="version"]').html(data.verSelect);
$('input[name="iTunesAppID"]').attr('value', data.trackId);
}, 600);
//Showing Submit Page
$('section.submit').delay('600').fadeIn('slow');
} else {
$('.json-response').html(data.message).fadeIn('slow');
}
},
error: function(jqXHR, textStatus, errorThrown) {
//$('.json-response').html('Probléma történt! Kérlek próbáld újra később! (HTTP Error: '+errorThrown+' | Error Message: '+textStatus+')').fadeIn('slow');
$('.json-response').html('Something went wrong! Please check your network connection!').fadeIn('slow');
}
});
});
Sometimes (randomly) the content fades out-in twice.
Could you let me know what's wrong?
Thanks in advance.
I guess the page is dynamically generated from javascript,
If you execute the following function twice, then there be two events since it executes twice,
so a better way is to unbind all previus 'keyup' event and bind it again.
Try this,
$('input[type="text"][name="appLink"]').unbind('keyup').keyup(function() {
});
I have a have a button that calls a JavaScript method that looks like this:
processSelection = function(filename) {
//alert('method reached');
$.ajax({
url: "sec/selectUsers.php",
data: "filename="+filename,
cache: false,
dataType:'html',
success: function(data) {
//$('#uploader').html(data);
$('#noUsers').sortOptions();
values = $('#noUsers').children();
for (i = 0; i < values.length; i++) {
$(values[i]).bind('dblclick',switchUser);
}
$('#addButton').bind('click',addSelection);
$('#removeButton').bind('click',removeSelection);
$('#submitButton').bind('click',addUsersToFile);
},
error: function (request, textStatus, errorThrown) {
alert('script error, please reload and retry');
}
}); /* ajax */
}
It is not going to the selectUsers.php script, nor is it posting the error message. When I click on my button 'add users' it does nothing. The other methods: switchUser, removeSelection, addSelection, and addUserstoFile are already defined.
I am fairly new to JavaScript and php and have been assigned this project running maintenance on our website. My php_error.log shows no error either. If anyone has any advice on this specific problem, or debugging in general I would very much appreciate it.
here is the click event:
<input type="button" value="add users" onclick="processSelection('<?=$drFile['name']?>')"/>
Okay,
To simplify my problem, I have done this:
processSelection = function(){
//alert('method reached');
$.ajax({
url: "sec/testPage.php",
cache: false,
success: function() {
alert('success');
},
dataType:'html',
error: function (request, textStatus, errorThrown) {
alert('script error, please reload and retry'); }
});
}
where testPage.php is just a table with some values in it.
Now when I click the button it show 'success', but never shows testPage.php
dataType: 'HTML'
has to be before your success method as far as i know. If still does not work try the following:
it will not show the test page because you are not appending anything to your current body. Your script executes successfully if you see "success"on your screen. All you need to do is if you have html generated in your testPage, assign all html to a php variable and then just echo it instead of returning it like
echo $myhtmlgenerated
and change
success: function() { ....
TO
success: function(result) {
$(body).append(result);
}
or you can play around with it and specify a special div which will hold the content from that page.