It's a php while with javascript codes. I want that this:
Check every 1 seconds that chat_status.html -text's: status = "offline"
Full code:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script type="text/javascript">
// jQuery Document
$(document).ready(function(){
function loadChatStatus(){
var status = ("http://tulyita.hu/chat/chat_status.html".text);
if(status == "offline"){
//this happens 1#
} else {
//this happens 2#
}
}
setInterval (loadChatStatus, 1); //Reload file every 1 seconds
});
</script>
but it isn't worked. :( Can someone help me?
I need the text from the "chat_status.html".
function loadChatStatus(){
$.ajax({
url: "chat_status.html",
cache: false,
success: function(html){
$("#status").html(html); //Insert status into the #status div
},
});
if($("#status") == "offline"){
//this happens #1
} else {
//this happens #2
}
}
??
You can use $.get() to load the contents from your server and do something with it in the callback. Example (not tested):
$.get('http://tulyita.hu/chat/chat_status.html', function (data) {
if (data === 'chat = off' {
// happens when offline
}
else {
// happens when online
}
}, 'text');
Note that the page's current content is chat = off and not offline. Please check the exact contents of data after implementing this in your code.
Also note that your HTML page has to be on tulyita.hu or you have to add an Access-Control-Allow-Origin header because of the same-origin policy.
First, don't declare the loadChatStatus function in .ready() but outside of it. Leave only the setInterval inside the .ready() function. And 1 second is 1000 ms. setInterval expects ms.
Second, use .load() to get the contents of the url, put it in a (hidden) div,and then check what it is. You cannot just do "string".text , as a string has no .text member.
Related
Hello I have this script that moves from one page through a href without page load.
It works perfectly, but I want to redirect to the requested page if Ajax takes longer than 5 seconds to respond, usually caused by probably slow internet connection.
In this case: Stop the script and load the page normally.
Firstly the href:
new
New 1
This is the script:
<script>
$(function(){
$("a[rel='tab']").click(function(e){
pageurl = $(this).attr('href'); //get the href clicked
$.ajax({url:pageurl+'?rel=tab',
success: function(data){
$('#mole').html(data);
}
});
if(pageurl!=window.location){
window.history.pushState({
path:pageurl
},'',pageurl);
}
return false;
});
});
$(window).bind('popstate', function(){
$.ajax({
url:location.pathname+'?rel=tab',
success: function(data){
// here how do I detect if the success takes longer than 5 seconds
// stop the script and load the page normally which is the URL parameter in ajax
$('#mole').html(data);
}
});
});
</script>
First, we need to add a timeout to the ajax handler so it will cancel the request after 5 seconds (here we use 5000 for milliseconds). Then, based on the docs, head to error and you can see the second param is textStatus. If it was a timeout, this will be equal to "timeout". This is probably your easiest path to what you need to do. Update the error handler as needed for your functionality.
$(window).bind('popstate', function() {
var url = location.pathname + '?rel=tab';
$.ajax({
timeout: 5000,
url: url,
success: function(data) {
$('#mole').html(data);
},
error: function(jqXHR, textStatus) {
if (textStatus === 'timeout') {
// we know the ajax failed due to a timeout,
// do what you need here, below is an example.
window.location = url;
}
}
});
});
I have an ajax function, and I expect it to run 1912 times, but it only runs once, for some reason. I'm using startAt, and stopAt to determine when it should stop running, but it's not working for some reason. What am I doing wrong?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
function callAjax(gotoUrl, link, startAt, stopAt, output) {
$.ajax({
type: "POST",
url: gotoUrl,
data: { link : link },
error: function(xhr,status,error){
alert("error");
},
success:function(data) {
document.getElementById(output).innerHTML += startAt;
},
complete:function(data) {
startAt++;
var link = data;
if (startAt < stopAt) {
setTimeout(function(){
callAjax(gotoUrl, link, startAt, stopAt, output)
}, 100);
}
}
});
} //end of function callAjax()
</script>
<body onload = 'callAjax("test1.php", "link", 1, 1912, "output")'>
<div id = "output"></div>
Result:
1
Expected Result:
1912
The issue is on this line:
var link = data;
you are reassigning the value of link to be the returned data.
You then immediately call this inside the timeout:
callAjax(gotoUrl, link, startAt, stopAt, output)
But link isn't a link any more its an object, hence jquery errors out, and silently dies after one iteration.
Removing that line makes the code function fine, you just need to store the data in another variable and it'll work.
Here's a fiddle with the functional code with just that line commented out.
This topic is covered in a few other questions, but I had some difficulty applying the suggested approaches into this use case. I have a checkbox list, where a user can select n sub-sites to publish their post to. since this list could grow to be 100+, I need an efficient way to perform an expensive task on each one. It's okay if it takes awhile, as long as Im providing visual feedback, so I planned to apply an "in progress" style to each checkbox item as its working, then move to the next item int he list once it is successfully published. Also note: I'm working in the WordPress wp_ajax_ hook but the PHP side of things is working well, this is focused on the JS solution.
This code is working right now (console.logs left in for debug), but I've seen multiple warnings against using async: true. How can I achieve a waterfall AJAX loop in a more efficient way?
//Starts when user clicks a button
$("a#as_network_syndicate").click( function(e) {
e.preventDefault(); //stop the button from loading the page
//Get the checklist values that are checked (option value = site_id)
$('.as-network-list').first().find('input[type="checkbox"]').each(function(){
if($(this).is(':checked')){
blog_id = $(this).val();
console.log(blog_id+' started');
$(this).parent().addClass('synd-in-progress'); //add visual feedback of 'in-progress'
var process = as_process_syndication_to_blog(blog_id);
console.log('finished'+blog_id);
$(this).parent().removeClass('synd-in-progress');
}
});
});
function as_process_syndication_to_blog(blog_id){
var data = {
"post_id": $('#as-syndicate_data-attr').attr("data-post_id"), //these values are stored in hidden html elements
"nonce": $('#as-syndicate_data-attr').attr("data-nonce"),
"blog_id": blog_id
};
var result = as_syndicate_to_blog(data);
console.log('end 2nd func');
return true;
}
function as_syndicate_to_blog(data){
$.ajax({
type : "post",
dataType : "json",
async: false,
url : ASpub.ajaxurl, //reference localized script to trigger wp_ajax PHP function
data : {action: "as_syndicate_post", post_id : data.post_id, nonce: data.nonce, blog_id: data.blog_id},
success: function(response) {
if(response.type == "success") {
console.log(response);
return response;
} else {
}
},
error: {
}
});
}
Indeed, doing synchronous AJAX request is bad because it will block the browser during the whole AJAX call. This means that the user cannot interact with your page during this time. In your case, if you're doing like 30 AJAX calls which take say 0.5 seconds, the browser will be blocked during 15 whole seconds, that's a lot.
In any case, you could do something following this pattern:
// some huge list
var allOptions = [];
function doIntensiveWork (option, callback) {
// do what ever you want
// then call 'callback' when work is done
callback();
}
function processNextOption () {
if (allOptions.length === 0)
{
// list is empty, so you're done
return;
}
// get the next item
var option = allOptions.shift();
// process this item, and call "processNextOption" when done
doIntensiveWork(option, processNextOption);
// if "doIntensiveWork" is asynchronous (using AJAX for example)
// the code above might be OK.
// but if "doIntensiveWork" is synchronous,
// you should let the browser breath a bit, like this:
doIntensiveWork(option, function () {
setTimeout(processNextOption, 0);
});
}
processNextOption();
Notice: as said by Karl-André Gagnon, you should avoid doing many AJAX requests using this technique. Try combining them if you can, it will be better and faster.
If you can't pass the whole block to the server to be processed in bulk, you could use a jQuery queue. This is using your sample code as a base:
var $container = $('.as-network-list').first();
$container.find('input[type="checkbox"]:checked').each(function(){
var $input = $(this);
$container.queue('publish', function(next) {
var blog_id = $input.val(),
$parent = $input.parent();
console.log(blog_id+' started');
$parent.addClass('synd-in-progress'); //add visual feedback of 'in-progress'
as_process_syndication_to_blog(blog_id).done(function(response) {
console.log(response);
console.log('finished'+blog_id);
$parent.removeClass('synd-in-progress');
next();
});
});
});
$container.dequeue('publish');
function as_process_syndication_to_blog(blog_id){
var data = {
"post_id": $('#as-syndicate_data-attr').attr("data-post_id"), //these values are stored in hidden html elements
"nonce": $('#as-syndicate_data-attr').attr("data-nonce"),
"blog_id": blog_id
};
return as_syndicate_to_blog(data).done(function(){ console.log('end 2nd func'); });
}
function as_syndicate_to_blog(data){
return $.ajax({
type : "post",
dataType : "json",
url : ASpub.ajaxurl, //reference localized script to trigger wp_ajax PHP function
data : {action: "as_syndicate_post", post_id : data.post_id, nonce: data.nonce, blog_id: data.blog_id}
});
}
I don't have a test environment for this so you may need to tweak it for your use case.
I have written a Chrome extension that adds a char counter to some input elements. There is no UI for this, it just injects the char counting code if the user is on a specific page.
There is a limit to how many chars should appear in the inputs. I initially wrote it to just display the number of chars but then I decided it would be nice if the user could choose to see how many chars they have left instead. So I decided to create an options page.
At some point in my options page I do this:
localStorage["count"] = count; // count is the string "countUp" or "countDown"
It turns out I can't access the localStorage of options.html from the contentscript.js so I reluctantly created a background.html page which listens to requests from the contentscript and returns the localStorage values that the content script asks for.
In contentscript (simplified)
var countOption;
chrome.extension.sendRequest(
{method: "localStorage", key: "count"},
function(response){
countOption = response.data;
console.log(countOption); // returns "countUp"
}
);
console.log(countOption); // returns undefined
if(countOption === "countUp") {
doSomething();
} else {
doSomethingElse();
}
Background page
<script type="text/javascript">
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
if(request.method === "localStorage") {
sendResponse({data: localStorage[request.key]});
} else {
sendResponse({});
}
}
);
</script>
The problem is I can't assign a value to countOption so that it is accessible in the scope of the rest of my script. When I assign it in the chrome.extension.sendRequest's response this is the window object so I have tried declaring countOption globally but it is still undefined in the rest of my script.
Can anyone see where I'm going wrong? Thanks.
Would something like this work?
function executeCount(countOption)
{
console.log(countOption); // returns undefined
if(countOption === "countUp") {
doSomething();
} else {
doSomethingElse();
}
}
chrome.extension.sendRequest(
{method: "localStorage", key: "count"},
function(response){
executeCount(response.data);
}
);
hoping some one can shed some light on my problem. Basicly I only want to execute a block of code if a certain DOM element exists. If it does I then perform a few bits and bobs and then call a function. However it complains that the function is not defined, suggesting that the function is not in scope. Below is the code :
$(document).ready(function ()
{
if ((document.getElementById("view<portlet:namespace/>:editSplash")!= null)) {
console.log("notifications scripted started");
// hide loading box/ notify on body load
$('.ajaxErrorBox').hide();
$('.loadingNotifications').hide();
$('.notifyWindow').hide();
getFeed();
// set up refresh button for reloading feed
$('.refreshFeed').click(function() {
$('.notifyWindow').hide();
$('.notifyWindow').empty();
console.log("notifications clicked");
getFeed();
});
// begin ajax call using jquery ajax object
function getFeed ()
{
$('.notifyWindow').empty();
console.log("ajax call for feed starting");
$.ajax ({
type: "GET",
url: "http://cw-pdevprt-05.tm-gnet.com:10040/notificationsweb/feed?username=uid=<%# taglib uri="/WEB-INF/tld/engine.tld" prefix="wps" %><wps:user attribute="uid"/>",
dataType: "text/xml",
timeout: 10000,
success: parseXml
});
};
// show loading box on start of ajax call
$('.notifyWindow').ajaxStart(function() {
$('.refreshFeed').hide("fast");
$('.notifyWindow').hide();
$('.ajaxErrorBox').hide();
$('.loadingNotifications').show("fast");
});
// hide loading box after ajax call has stopped
$('.notifyWindow').ajaxStop(function() {
$('.loadingNotifications').hide("slow");
$('.refreshFeed').show("fast");
});
$('.notifyWindow').ajaxError(function() {
$('.loadingNotifications').hide("slow");
$('.ajaxErrorBox').show("fast");
$('.refreshFeed').show("fast");
});
// parse the feed/ xml file and append results to notifications div
function parseXml (xml) {
console.log("xml parsing begining");
if (jQuery.browser.msie)
{
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.loadXML(xml);
xml = xmlDoc;
}
$(xml).find("entry").each(function()
{
var $item = $(this);
var title = $item.find("title").text();
var linkN = $item.find("link").attr("href");
var output = "<a href='" + linkN + "' target='_self'>" + title + "</a><br />";
$(".notifyWindow").append($(output)).show();
});
}
}
else {
console.log("notifications not available");
return false;
}
});
If the DOM element exists I then try and call the getFeed function "getFeed();" however it comes back undefined. If anyone could shed some light on this it would be greatly appreciated.
Thanks in advance
It seems that you're calling getFeed before it is defined. Try moving the if statement to after the function definition. Note that this behaviour is actually implementation specific, so some browsers may work this way and some may not.
Oh - And seriously? view<portlet:namespace/>:editSplash for an id?
Problem solved - I moved my functions outside of the if statement. We live and learn lol :-)