Error with find() after correct result - javascript

I have some errors in my extension. I have this code that do a find() on an external page:
$.ajax({
url: 'http://www.subspedia.tv/traduzioni.php',
success: function(data) {
$(data).find('.itemListaSerie').each(function() {
console.log($(this).attr('title'));
});
}
});
The find function work correctly but after the result I have a lot of errors that say "File not found" on all images in the page that I'm doing the request.
The screen show my result:

You need to post process the relate links like immagini/serie/covers/33.png for each of the images, and convert them into something like
http://www.subspedia.tv/immagini/serie/covers/33.png
instead of using it as is
EDIT:
The images loaded are probably due to the $(data). If you need only the titles, then you should replace the src of all the tags before $(data)
success: function(data) {
var strippedData = data.replace(/src='(?:[^'\/]*\/)*([^']+)'/g, "");
$(strippedData).find('.itemListaSerie').each(function() {
console.log($(this).attr('title'));
});
Credit to #Gumbo for his answer on regex for matching src. Note, this will remove all src attributes in the page

After your success function, using $(data) you create an element that contain all the html from http://www.subspedia.tv/traduzioni.php so, the document is looking for all the script, css and the images included in that page.
try to replace all the img as words in data as string and then call $(data).find....
Hope this helps you! Anche se mi sarei spiegato meglio in Italiano ;)

Related

jquery .load() does not load external JS

I am loading external content into a div element using jquery.load() without a selector. If the content loaded has embedded JS, the JS works as expected. HOWEVER, if the content includes a script tag with src=path-to-js-code the js-code is not loaded.
Am I correct in this observation and if so is there a good solution other than embedding the JS in the loaded content?
EDIT :
A few clarifications and observations:
To load the content I am using
$("#DivId").load("path/to/content.php", CallbackFunction(response, status, xhr) {
error checking and post processing code
});
Changing the load code to:
$.get("path/to/content.php", CallbackFunction(response, status, xhr) {
error checking
$("#DivId").html(response);
post processing
});
Does not seem to change the behavior (more on the behavior below)
I have not tried parsing the response to retreive the script src and then using getScript().
Now more on the behavior...
Using Firefox, it seems that the external JS is loaded but only if it has been about 2 min from the last load. I do not see an attempt in Firebug unless the refresh is about 2m after the last load of the external JS. (weird). When I was making JS code changes and hitting refresh, it was not loading my new code and thus the original question.
So i will withdraw my question in light of this clarified behavior (2m caching?).
Thanks.
Both the .load() and .html() jQuery methods utilise the .innerHTML property. This won't execute scripts added with <script> tag. Use a regular AJAX call e.g. .get() then in the callback use .append() to add your HTML string and the scripts will run once it's parsed e.g.
$.get("path/to/content.php", function(response, status, xhr) {
// error checking
$("#DivId").append(response); // Any <script> tags in the response string will execute
// post processing
});
Thing is you need to make sure you're running trusted code if it's added by .append()
I was wondering you can get the script src in the response text of $.load method with regular expressions, then use $.getScript() method to load the script, maybe something like this:
$("#DivId").load("path/to/content.php", function(response, status, xhr) {
var regexp = new RegExp('script.*?src="(.*?)"'),
execresults = regexp.exec(response);
if(execresults.length > 1)
{
// the first result is the entire match including
// the 'script..src=', so abandon it
var matches = execresults.slice(1);
$.each(matches, function(){
$.getScript(this, function(){
// do something after load script
});
});
}
});
Hope this can help
This is the easy way to load an external JS to your jQuery
$.ajax({
type: "GET",
url: "path/to/content.php",
dataType: "script"
success:CallbackFunction(response, status, xhr)
});

get all images in an HTML string

I'm always having trouble with that,
i'm loading a file with AJAX :
$.ajax({
url: fullHref,
success : function(result) {
console.log(fullHref+" was loaded via AJAX");
saveImages(result);
}
});
and trying to iterate through all images in result :
function saveImages(file){
console.log("savesImages enterd");
$(file).find('img').each(function(){
console.log("The file has this image : "+$(this).attr('src'));
});
}
}
I've also tried :
$('img',file)
$('img',$(file))
$('img',$(file).html())
Yet it doesn't enter the loop.
Any suggestions?
I'm using Chrome, and i don't wanna use regex.
Tryfilter() instead of find:
$(file).filter('img').each(function() { /* ... */ });
find() looks down the DOM tree which is not what you want if the img elements in the string are all at the root level.
Just make a new node and set the innerHTML of it.
$('<span></span>').html(file).find('img').each(...

Why .html() method does not load data in the element?

$.get("progress.txt", null, function(data_aj){
if(data_aj.substr(0,14) == "<!-- MSG:: -->"){
$("#list").html("<li>"+data_aj+"</li>");
window.clearTimeout(timeOutId);
}else{
$("#list").html(data_aj);
}
});
I really have tried everything but can't figure out whats wrong. If I use alert(data_aj); it gives the desired output and just works fine but HTML(data_aj) just doesnt loads into a <ul> element #list using .html(). Can anyone tell me why?
Have you tried putting your code in a document ready, as your alert will fire fine but if your dom is not loaded then you cannot append to it. Also use .append() for lists not html
$(document).ready(function() {
$.get("progress.txt", null, function(data_aj){
if(data_aj.substr(0,14) == "<!-- MSG:: -->"){
$("#list").append("<li>"+data_aj+"</li>");
window.clearTimeout(timeOutId);
}else{
$("#list").append(data_aj);
}
});
});
Listen up...
$.get() is a shorthand for $.ajax().
So when you do this
$.get(uri, function(data){
//Your functionality
});
You're really doing this
$.ajax({
url: uri,
type: "GET",
success: function(data) {
//Your functionality
}
});
By default this returns the page as HTML. Or rather, by default, it first checks the MIME-type on the page, and if none is found, it returns HTML. As you are requesting a .txt file it will interpret it as a simple textfile. If you want to tell it what you would like to return (HTML), you can either do it in the MIME-type on the server page, or you could use $.getJSON().
An easy way to solve this is thus doing:
$.get(uri, function(data) {
//Your functionality
},
"html");
Which is the same as doing:
$.ajax({
url: uri,
type: "GET",
dataType: "HTML",
success: function(data) {
//Your functionality
}
});
Also it is not a good idea to use html() because you are replacing the existing html inside of your ul element every time you want to add an additional new node.
Try making use of:
$('#list').append('<li>' + data_aj + '</li>');
Basically you can just append the <li> to the <ul> itself.
Lastly make sure your dom has already been loaded by placing all your JQuery code into the
$(document).ready(function() {
//Your code...
});
Otherwise if your HTML is not fully loaded yet, your list might not exist yet so there is no way for JQuery to put some values into unexisting HTML.

Get contents from <link> (not <a>) tag

Hi I'm trying to get contents of the link tag. So with:
<link rel="stylesheet" href="some.css">
I want the contents of the file some.css in a string.
Tried:
document.getElementsByTagName('link')[0].firstChild.nodeValue; // fails
document.getElementsByTagName('link')[0].hasChildNodes(); // false
Any ideas? I don't want to use the styleSheet method (which only works in FF anyway) because it will strip out stuff like -moz-border-radius and such.
Thanks.
I think Daniel A. White is correct. Your best bet is to get the href of the stylesheet, then load the content via Ajax and parse it.
What are you trying to do exactly?
You can't get the contents of a file with only javascript. You'll need an ajax request to the server which opens the file and returns its contents.
To do this, you need to access the file via an ajax request.
So, with jQuery, something like this
$.ajax({
url: "some.css",
success: function(){
//do something
}
});
More details here: http://api.jquery.com/jQuery.ajax/
Note: this only works if the file making the request is on the same server as the file requested.
CSS rules offer a special API, but nothing like innerHTML.
This is as close as it gets:
var result = '';
var st = document.styleSheets[0].cssRules;
for (var i = 0; i < st.length; i++) {
result += st[i].cssText;
}
console.log(result);
However, this will not respect whitespace, comments, erroneous rules, ...
And as usual, this is subject to Same Origin Policy.

Embedding Javascript in html document

I'm trying to implement the following code in a html document:
$(function () {
$.ajax({
type: "GET",
url: "/projects/img/Bathurst/PhotoGallery.xml", // location of your gallery's xml file
dataType: "xml",
success: function(xml) {
$(xml).find('img').each(function() {
var location = '/projects/img/Bathurst/'; // relative path to the directory that holds your images
var url = $(this).attr('src');
var alt = $(this).attr('alt');
$('<li></li>').html('<img class="thumb" src="'+location+''+url+'" alt="'+alt+'" title="'+alt+'" />').appendTo('#gallery-ul');
});
$('<script type="text/javascript"></script>').html('Shadowbox.clearCache(); Shadowbox.setup();').appendTo('#photo-gallery');
}
});
});
The code works perfectly when I use it in an external .js file, but I cant get it working when i implement it, it just renders with error in the code.
II'm I missing something and dos anyone have a suggestion to this? The reason why I need to implement it, in case some one wonderes, is that I'm building a custom webapp and the line "/projects/img/Bathurst/PhotoGallery.xml" and "/projects/img/Bathurst/" is dynamic variables.
All answers are very much appreciated! :)
The problematic line ($('<script type="text/javascript">...) is a convluted and unnecessarily complicated way to run two lines of Javascript.
You should replace it with simple method calls. (Shadowbox.clearCache(); Shadowbox.setup();)
You can't have a </script> inside a script.
Change
$('<script type="text/javascript"></script>')
to
$('<script type="text/javascript"><\/script>')

Categories