AJAX Check if a div of an external file is empty - ajax

I have the following code that retrieves every 60 sec the content of a specific div (#livetick) and refresh another div (#liveticker) with that content.
<script>
$(document).ready(function() {
$("#liveticker").load('http://www.domain.com/livetickerr/ #livetick');
var refreshId = setInterval(function() {
$("#liveticker").load('http://www.domain.com/livetickerr/ #livetick');
}, 60000);
$.ajaxSetup({ cache: false });
});
</script>
Also, the html code of div that is refreshed every 60 sec is:
<div class="liveticker" id="liveticker">
<b>Loading...</b>
</div>
My question is how can i hide the div "liveticker" if the return content of "livetick" div is empty?
I have already search about my question but i cant find a way to do it.
Thank you in advance!

Try adding a callback to run after you load the external source:
$(document).ready(function() {
$("#liveticker").load('http://www.domain.com/livetickerr/ #livetick', function(response) {
if ( response === "" )
{
$('#liveticker').html("");
}
});
Of course, response === "" isn't a great conditional. Something more like,
$("#ticker_content", response).html() === ""
might serve you better. I don't know how the #livetick div is structured.

Related

angular - invoke() on exising element undefined

I've a div (id: dest) in which content is loaded via ajax using query.
I need to compile with angular the content of that div.
Here is the content loaded via ajax:
{{myvar}}
I tried to do:
var app = angular.module("myapp", []);
app.controller("myctrl", function($scope){
$scope.myvar = "hello world!";
});
$("#dest").attr("data-ng-app", "myapp");
$("#dest").attr("data-ng-controller", "myctrl");
console.log(angular.element($("#dest")).size()); //always returns '1'
angular.element($("#dest")).injector().invoke(function($compile) {
var scope = angular.element($("#dest")).scope();
$compile($("#dest"))(scope);
});
I'm sure that $("#dest") exists in dom when that code is executed but
angular.element($("#dest")).injector() is always undefined.
I also tried to wait 15 seconds:
setTimeout(function(){
angular.element($("#dest")).injector().invoke(function($compile) {
var scope = angular.element($("#dest")).scope();
$compile($("#dest"))(scope);
});
}, 15000);
But the problem remains.
PS.
I cannot interact directly with ajax request or response and the div (with id dest), exists at page loading.
Have you tried wrapping that code with $(document).ready() or angular's equivalent:
angular.element(document).ready(function () {
angular.element($("#dest")).injector().invoke(function($compile) {
var scope = angular.element($("#dest")).scope();
$compile($("#dest"))(scope);
});
});
Working jsfiddle.
Have you tried this :
angular.element($("#dest")).injector().invoke(['$compile', function($compile) {
var scope = angular.element($("#dest")).scope();
$compile($("#dest"))(scope);
}]);

Load JavaScript when partial is called via ColorBox?

It seems when loading a Razor partial view via ColorBox (not using an iframe), the JavaScript libraries do not initialize properly or it is an artifacte of the partial. If I include the libraries in the parent page, the JavaScript function runs inside the partial jsut fine. I don't see any errors coming from the browser when the library is in the partial, but it is not working. If I move the library (in this case fileuploader.js) outside of the partial and keep the function in the partial it works fine.
Example:
<script src="#Url.ContentArea("~/Scripts/plugins/ajaxUpload/fileuploader.js")" type="text/javascript"></script>
<div id="file-uploader">
<noscript>
<p>
Please enable JavaScript to use file uploader.</p>
</noscript>
</div>
<script>
$(function () {
var fileCount = 0;
var uploader = new qq.FileUploader({
element: document.getElementById('file-uploader'),
action: '/Admin/Avatar/AvatarUpload',
debug: true,
params: {
'userId': '#ViewBag.UserId'
},
onSubmit: function (id, fileName) {
fileCount++;
},
onComplete: function (id, fileName, responseJson) {
if (responseJson.success) {
if (createAvatar(responseJson.file, responseJson.imageId)) {
fileCount--;
} else {
fileCount--;
}
} else {
$("span.qq-upload-file:contains(" + fileName + ")").text(responseJson.errorMessage);
fileCount--;
}
if (fileCount == 0) {
.....
}
},
onCancel: function (id, fileName) {
fileCount--;
if (fileCount == 0) {
....
}
}
});
});
<script>
You may want to check whether there are duplicate references to the JavaScript libraries you are using (one in the parent and one in the partial).
This is a common issue and it will not raise any errors whatsoever, but will stop your JavaScript code from executing.
I think this is a time line problem.Before the "Partial View" load(or appending the div) JavaScript try to bind it and fail.So it cannot find a element which is in your Partial View document.I had a problem with like this with "ColorBox".I have found a solution for this problem.For example : When you call GET or POST method ,after the query put a control point like this .For example for binding "colorbox" :
function getMyPartial(partialname) {
var resultDiv = document.getElementById("content");
$.ajax({
type: "GET",
url: partialname,
async: false,
success: function (data) {
resultDiv.innerHTML = "";
resultDiv.innerHTML = data.toString();
}
});
var indd = 0; //This is Control Point
if (partialname == "YourPartialName") {
var yourelementinpartial= document.getElementById("example");
while (!yourelementinpartial) {
indd++;
}
$(".group4").colorbox({ rel: 'group4' }); //binding point
}
}
At the control point, if any of the element in your PartialView document has found it will bind.

jplayer+Ajax inserted content

I am using jPlayer to play audio files.
If I use the player on content, which is privided, when the page gets loaded, it works without any problems.
I also need it for HTML which is inserted by AJAX. Here it does not work. It seems, that the ready event is not triggered.
I wrote a function, which can be executed by click(). In that way, I can click it manually, when the HTML which contains the player is fully loaded. Here I have the same problem: The ready event is not triggered.
This is my function which works on non ajax inserted players fine:
$('.jp-jplayer').each(function () {
var src = $(this).attr('data-src');
var id = $(this).attr('id');
var post_id = $(this).attr('data-id');
alert('beg');
$('#' + id).jPlayer({
ready: function () {
$(this).jPlayer('setMedia', {
mp3: "/prelisten/_lofidl/change_of_heart_full_lofi.mp3",
});
alert('#' + id);
},
swfPath: "/wp-content/themes/Dark_3Chemical_DE_mit_Pagenavi/Dark_3Chemical_DE/audioplayer/js",
//////ERRRROOOOOR
solution: "flash, html",
supplied: "mp3",
wmode: "window",
cssSelectorAncestor: "#jp_container_" + post_id,
play: function () { // To avoid both jPlayers playing together.
$(this).jPlayer("pauseOthers");
},
repeat: function (event) { // Override the default jPlayer repeat event handler
if(event.jPlayer.options.loop) {
$(this).unbind(".jPlayerRepeat").unbind(".jPlayerNext");
$(this).bind($.jPlayer.event.ended + ".jPlayer.jPlayerRepeat", function () {
$(this).jPlayer("play");
debug($(this));
});
} else {
$(this).unbind(".jPlayerRepeat").unbind(".jPlayerNext");
$(this).bind($.jPlayer.event.ended + ".jPlayer.jPlayerNext", function () {
//$("#jquery_jplayer_4858").jPlayer("play", 0);
});
}
},
});
$("#jplayer_inspector").jPlayerInspector({
jPlayer: $('#' + id)
});
});
Currently I am setting the src manually to exclude any possible errors here.
How can I get this function running on AJAX inserted content?
EDIT:
This is the code, which fetches the html including the players:
$.get('/query_posts.php', {
paged: _page,
cats: cols
}, function(data) {
$('#search-results').append(data).fadeIn(300);
//create_player_scripts();
//set_players();
$('#search-results').find('input[name="cartLink"]').each(function() {
$(this).val($(this).closest('.post1').find('.post_headl a').attr('href'));
});
});
To make an AJAX page reload work I had to first destroy all jplayer instances. So I wrote a little function that grabs all instances of a jplayer on the site (by looking for jp-audio classes) and calls jplayer('destroy'); and jplayer('clearMedia'). This function gets called in the $.ajax({ beforeSend: destroyJplayerInstances(); })
UPDATE:
Here is a statement from the developer of jPlayer, Mark Panaghiston:
https://groups.google.com/forum/#!topic/jplayer/Q_aRhiyYvQo
Hope that helps!

AJAX recognizing if the result call is an error or a success

multiple request to fill different containers?
ajax/javascript example:
$(document).ready(function()
{
$(#submit).click(function()
{
$var = $("#result");
$.post("ajax.php", {request : $var}, function()
{
$("#container1").fadeOut(400, function(){ $("#container1").html(result); });
$("#container1").fadeIn();
});
});
});
ajax.php example:
<?php
if($_POST['request']==1) // or several complicated conditions
{ ?><div>This is a success</div>
//if success I would like to load another piece of html inside an id="container2".
<?php }
if($_POST['request']==0)
{ ?><div>This is a disaster</div> <?php }
?>
That's the question if the response is 1 (or This is a success) I would like to load another piece of html code inside a container (container2) with a different id from the original container id used for the request within the post method(in this case "container1").
Is there a way to do it?
Thanks for your thoughts and answers!
$(document).ready(function()
{
$(#submit).click(function()
{
$var = $("#result");
$.post("ajax.php", {request : $var}, function(a,b)
{
if(b=="error"){
Do Somthing...
} else{
$("#container1").fadeOut(400, function(){ $("#container1").html(result); });
$("#container1").fadeIn();
}
});
});
});

Why doesn't javascript execute in .php file loaded with Ext.Ajax.Request?

I want to load .php files via ajax which execute ExtJS script as they load, which in turn modifies the existing ExtJS objects already present in the DOM.
However, I can't even get Javascript to execute from a page that is being loaded via Ext.Ajax.request. And no errors are showing up in the Firebug Net panel. The PHP code gets executed, but not the Javascript. When I call the page being loaded by itself in the browser, it executes the Javascript fine.
How can I get Javascript to execute in pages loaded with Ext.Ajax.request?
Ext.onReady(function(){
var menuItemStart = new Ext.Panel({
id: 'panelStart',
title: 'Start',
html: 'This is the start menu item.',
cls:'menuItem'
});
var menuItemApplication = new Ext.Panel({
id: 'panelApplication',
title: 'Application',
html: 'this is the application page',
cls:'menuItem'
});
var regionMenu = new Ext.Panel({
region:'west',
split:true,
width: 210,
layout:'accordion',
layoutConfig:{
animate:true
},
items: [ menuItemStart, menuItemApplication ]
});
var regionContent = new Ext.Panel({
id: 'contentArea',
region: 'center',
padding:'10',
autoScroll: true,
html: 'this is the content'
});
new Ext.Viewport({
layout: 'border',
items: [ regionMenu, regionContent ]
});
menuItemStart.header.on('click', function() {
Ext.Ajax.request({
url: 'content/view_start.php',
success: function(objServerResponse) {
regionContent.update(objServerResponse.responseText);
}
});
});
menuItemApplication.header.on('click', function() {
Ext.Ajax.request({
url: 'content/view_application.php',
success: function(objServerResponse) {
regionContent.update(objServerResponse.responseText);
}
});
});
});
the file that is being loaded via Ajax:
<script type="text/javascript">
window.onload=function() {
alert('from application view'); //is not executed
}
//Ext.onReady(function(){
// alert('from application view extjs'); //is not executed
//}
</script>
<?php
echo 'this is the application view at ' . date('Y-m-d h:i:s');
?>
When you get the ajax response the onload event on the window has been already fired so the function won't be executed because the onload event won't be fired again. Try only with the alert:
<script type="text/javascript">
alert('from application view');
</script>
<?php
echo 'this is the application view at ' . date('Y-m-d h:i:s');
?>
UPDATE
Browsers don't execute injected scripts in that way so you can try with something like:
var scripts, scriptsFinder=/<script[^>]*>([\s\S]+)<\/script>/gi;
while(scripts=scriptsFinder.exec(responseText))
{
eval(scripts[1]);
}
Have you tried passing true for the second param to Panel.load (which happens to be the loadScripts option)?
regionContent.update(objServerResponse.responseText, true);
Normally, when you call update with ext you just do
update(string,true) and it will execute scripts contained within the string. However, ext core seems to lack this functionality, but there is no documentation for the update method (I had to search the actual code to confirm this.)
If you are using some regular EXT (like ext-all) you can simply add
regionContent.update(objServerResponse.responseText,true);
like this and it should eval the scripts. No dice for me, though - ext-all is too slow but I need eval functionality. I may have to hack EXT.

Resources