I'm writing a chrome extension and I'm trying to get the RSS feed "media:thumbnail" but the function el.find('media\:thumbnail').attr('url') outputs 'undefined'.
Here's my code :
$.get("http://www.reddit.com/.rss", function (data) {
$(data).find("item").each(function () { // or "item" or whatever suits your feed
var el = $(this);
$("tbody").append("<tr><th>" + el.find('media\\:thumbnail').attr('url') + "</th><td>" + el.find("title").text() + "</td></tr>");
});
});
There is something in JS that is called "same origin policy". It means that you cannot query stuff, that is not from the same domain, using the same protocol and uses the same subdomain.
You need to research "cors" to make calls to another domain possible, but in this case, this won't help you. Cors needs you to include stuff in the http response header.
Another way out is to configure your web server as a reverse proxy and mask the requests from reddit as a local call.
Here is the scripts that will help
First, you need a server script that will pick crosdomain content
<?php // crossdomain php script
header('Content-type: application/xml');
header('Access-Control-Allow-Origin: *');
ini_set('error_reporting', E_WARNING );
$str_xml = '';
if ($_POST['source'] === 'reddit') {
$str_xml = file_get_contents('http://www.reddit.com/.rss');
}
die($str_xml);
?>
Then make Ajax requests and parse response xml
$.ajax({
type: "POST",
url: "crossdomain.php",
dataType: "xml",
data:{source:"reddit"},
success: function(xml){
var xmlText = new XMLSerializer().serializeToString(xml);
$(xmlText).find("media\\:thumbnail").each(function(){
$("tbody").append("<tr><th>" + $(this).attr('url') + "</th><td>" + $(this).parent().find("title").text() + "</td></tr>");
});
}
});
I found a workaround. I use the element "description" of the RSS feed. It contains the link to the image.
Xml :
<description>
<table> <tr><td> <img src="http://b.thumbs.redditmedia.com/50jHjrHnJTSIX_Q86UUXe1Kc-rAxYyhEd90GeUDJHao.jpg" alt="Cat walks into a bar." title="Cat walks into a bar." /> </td><td> submitted by _dear_ms_leading_ to funny <br/> [link] [69 commentaires] </td></tr></table>
</description>
Jquery :
$('' + el.find('description').text()).find("img").attr("src")
I cannot believe that people do not understand this question and give an answer about something else.
The questioner does not mention CORS or any possible error that could point to it.
The question is simply asking about JQuery selectors on XML nodes rather than HTML, the fact that he is using AJAX to get an RSS feed is irelivant, so one can assume that CORS is not an issue in this case.
I had been struggling with the exact same thing, apparently double backslash is supposed to escape, but doesn't seem to work in this case.
What I did instead is use the JQuery attribute selector with the attribute url, all thumbnails have url attributes in my case.
So your code would be:
$.get("http://www.reddit.com/.rss", function (data) {
$(data).find("item").each(function () { // or "item" or whatever suits your feed
var el = $(this);
$("tbody").append("<tr><th>" + el.find('[url]').attr('url') + "</th><td>" + el.find("title").text() + "</td></tr>");
});
});
Update
It might be better to use map
$.get("http://www.reddit.com/.rss", function (data) {
var tbody = $('tbody');
tbody.append(
$(data).find("item").map(function () { // or "item" or whatever suits your feed
var el = $(this);
return $("<tr><th>" + el.find('[url]').attr('url') + "</th><td>" + el.find("title").text() + "</td></tr>");
}).get()
);
});
I have tested it mind
Related
Possibly a dumb question, but I have a page where I'm trying to load list data into a customer table to display as a front-end. I'm retrieving this list from a SharePoint list using an AJAX call in a Javascript function, however when I'm using this function my console returns a SCRIPT5009: '$' is not defined error. Previously, I've used an AJAX call successfully using very similar code, but to return a single item from the list using the list ID to search for a specific item, and I've run the query successfully directly from the URL that returns the data I'm after - I'm just not sure what's happening with this one.
function getIncidents(){
$.ajax({
url: "SharepointURL/_api/web/lists/getbytitle('Incident List')/items?$select=Title,Id,Priority,IncidentStart,IncidentStatus,IncidentTitle,UpdateResolution",
type: "GET",
headers: {"accept": "application/json;odata=verbose"},
success: function (data) {
var dResponse = data.d.results;
var results = document.getElementById('Results');
results.innerHTML += "<tr><td>Incident<br>Reference</td><td style='width:20px'></td><td>Priority</td><td style='width:20px;'></td><td>Start Time</td><td style='width:20px'></td><td style='width:170px'>Issue</td><td style='width:20px'></td><td style='width:170px'>Latest Update</td><td style='width:20px'></td></tr>";
for(var obj in dResponse){
results.innerHTML += "<tr style='font-size:10pt'><td>"+dResponse[obj].Title + "</td><td></td><td>" + dResponse[obj].Priority + "</td><td></td><td>" + dResponse[obj].IncidentStart + "</td><td></td><td>" + dResponse[obj].IncidentTitle + "</td><td></td><td>" + dResponse[obj].UpdateResolution + "</td></tr>";
}
}
});
}
Previous example where I have this call working:
function getIncident() {
var listName="Incident List";
var incidentID = $("#incidentReference").val();
if(incidentID!=""){
$.ajax({
url: "SharepointURL/_api/web/lists/getbytitle('Incident List')/items?$filter=Title eq '" + incidentID + "'&$select=Title,Id,SystemOrService,Priority,IncidentStatus,IncidentTitle,UpdateResolution,IncidentStart,ImpactedArea,IncidentEnd",
type: "GET",
headers: {"accept": "application/json;odata=verbose"},
success: function (data) {
if(data.d.results.length>0){
var item=data.d.results[0];
$("#systemImpacted").val(item.SystemOrService);
$("#incidentPriority").val(item.Priority);
$("#incidentState").val(item.IncidentStatus);
$("#incidentTitle").val(item.IncidentTitle);
$("#incidentUpdate").val(item.UpdateResolution);
$("#startTime").val(item.IncidentStart);
$("#impactedAreas").val(item.ImpactedArea.results);
$("#endTime").val(item.IncidentEnd);
updateImpact();
getStartTime();
getEndTime();
actionsFormat();
}
},
error: function (data) {
alert("Incident Reference incorrect or not found");
}
});
}
}
The issue is that jQuery ($) is not yet loaded to the page. If you used it before, this means that loading is already setup, so you don't need to add more references to the jQuery.
In most of the cases, when you working with jQuery, you will subscribe on DOM event ready event and do your code there.
So, all you need is to find the
$(document).ready( ...
statement and insert your code there.
If you want to separate your code from already existed, you may write your own $(document).ready subscription.
If you will not find this $(document).ready function, you can search in html for the reference to the jQuery, and insert your script after it. But, than you need to be sure, that reference doesn't include async or defer attribute.
As mentioned in comments, if you decide to add your own subscription, you also need to place it after jQuery reference, because it will not work, if $ isn't available.
I'm trying to save google's API search results in a Mysql database in localhost.
My problem
I'm using a for loop to show every possible result from book research, such as "Harry Potter".
I do this with AJAX and then I cycle the results.
The main problem is that if I want to save one of the results, what is saved is just the last one because every variable is overwritten during every cycle.
Here is the code, saveBook.php is just a .php file where I do an insert into query.
$.ajax({
url:"https://www.googleapis.com/books/v1/volumes?q=" + search,
dataType: "json",
type: 'GET',
success: function(data){
for(i=0; i < data.items.length; i++)
{
title = $( '<p> ' + data.items[i].volumeInfo.title + '</p>');
author = $('<p> ' + data.items[i].volumeInfo.authors + '</p>');
img = $('<img><a href=' + data.items[i].volumeInfo.infoLink +
'><br></br><button>Read More</button></a>' );
url= data.items[i].volumeInfo.imageLinks.thumbnail;
save = $('<br><button onclick="save()">Save</button></br>
</br>');
img.attr('src',url);
title.appendTo("#result");
author.appendTo("#result");
img.appendTo("#result");
save.appendTo("#result");
}
},
});
}
}
function save(){
$.ajax({
type:'POST',
data: {
url: url,
title: title,
author: author,
},
url: "saveBook.php",
success: function(data){
alert("Success!");
location.replace("home.php");
}
})}
Another problem is:
how should I use this JSON
data: {
url: url,
title: title,
author: author,
},
to actually return a string with title and author, because url is correctly saved.
I've had some time to think over your project. While I'm not sure of all of your project requirements, a fundamental pursuit should be to minimize the calls to the api. For this reason, let your users search via a standard (non-ajax) search input/form and load the api results into the html with php, then use your ajax call to allow multiple save calls from a single load of search results (if that makes sense for your project). Basically, I suppose I am discouraging the auto-reload after saving a single item; otherwise you can avoid ajax again.
Also, as far as I know authors is an array, so you'll need to join/implode the values into a single string.
foreach (json_decode($apijson, true) as $item) {
echo '<div class="book">';
// your other elements in the row
echo "<button onclick=\"save('" ,
htmlspecialchars($item['id'], ENT_QUOTES, 'UTF-8') , "','" ,
htmlspecialchars($item['volumeInfo']['title'], ENT_QUOTES, 'UTF-8') , "','" ,
htmlspecialchars(implode(', ', $item['volumeInfo']['authors']), ENT_QUOTES, 'UTF-8') , "','" ,
htmlspecialchars($item['volumeInfo']['imageLinks']['thumbnail'], ENT_QUOTES, 'UTF-8') , "');\">Save</button>";
echo '</div>';
}
Then these parameters can be directly fed to your ajax function.
Be sure to validate and use sensible data sanitizing techniques and use a prepared statement when you INSERT.
You can return a success message from your ajax, and then hide() the saved row/book.
You can return a vague (not exact) error message if the insert did not make an "affected row".
Problem solved thanks to #mickmackusa. I have declared the variable "save" as a global array and, then, I have passed every string with a proper escape. Now it's working fine! Thank you very much.
save[i] = $('<button onclick="save((\'' + data.items[i].volumeInfo.authors + '\'),(\'' + data.items[i].volumeInfo.title + '\'),(\'' + data.items[i].volumeInfo.infoLink + '\'))">Save</button><br><br>')
I've been reading up on JSONP and trying to get a working implementation. The code below represents my understanding of what this is supposed to look like using jQuery. For some reason I can't get this working, and I don't know why. I've seen many example scripts online, but for some reason, none of them work for me. Can anyone help? Am I doing this correctly?
Here's the JSONP script:
<script type="text/javascript">
$(document).ready(function() {
var url = "http://www.example.com/blog/?json=get_recent_posts";
$.getJSON(url + "?callback=?", function(data) {
$("#output_div").append("<p>" + data.posts[2].title + "</p>");
}
});
});
</script>
... and I wrote a div like this:
<div id="output_div"> </div>
Thanks!
Since callback is the second parameter you need to use & to append it to the url like url + "&callback=?" or
$(document).ready(function () {
var url = "http://www.example.com/blog/?json=get_recent_posts&callback=?";
$.getJSON(url, function (data) {
$("#output_div").append("<p>" + data.posts[2].title + "</p>");
});
});
I have this code,
$(".delete").live("click", function () {
alert("!");
var self = $(this);
var loadUrl = $(this).attr('href');
var interestParents = self.parents('div:eq(4)').attr("id");
$.ajax({
type: "POST",
url: loadUrl,
data: "isAjax=1"
}).done(function (msg) {
self.parent().parent().parent().parent().parent().fadeOut('fast', function () {
$(this).remove();
});
//console.log($("#"+interestParents).load(site_url+"my_profile/interests " + "#" + interestParents).fadeIn('fast'));
//$("#UL_" + msg + "items").load(site_url + "my_profile/interests " + "#UL_" + msg + "items").fadeIn('fast');
$("#large_buttons").load(site_url + "my_profile #large_buttons > *").show();
});
return false;
});
and I cannot for life of me work out why the .load does not load the data into the large_buttons div, it definatly exists on the page, and it works in every other browser but IE8.
Check to make sure that the page you are "load"ing (my_profile) is valid HTML (no misplaced end tags, unclosed tags, etc). I had an issue like this with IE8 because the markup I was trying to load was invalid. Most browsers managed to interpret the bad markup, but IE8 failed.
An HTML validator may help you.
have you tried this way:
$("#large_buttons").show().load(site_url + "my_profile #large_buttons > *");
although i am unable to see where is the site_url variable, if this is a type then you should use this
$("#large_buttons").show().load(loadUrl + "my_profile #large_buttons > *");
I could use another pair of eyes. This script does what I want in Chrome (renders a gallery of images from a google picasa web album), but doesn't render anything in IE8, can anyone see anything obvious?
$(function () {
var json_Photo_URI = "https://picasaweb.google.com/data/feed/base/user/111727095210955830593/albumid/5420114965919213729?alt=json&fields=entry(title, media:group)&thumbsize=75"
$.ajax({
type: 'GET',
url: json_Photo_URI,
success: function (data) {
var photo_URL = "";
var photo_Thumb_Url = "";
$.each(data.feed.entry, function (i, item) {
$.each(item.media$group.media$content, function (i, item) { photo_URL = item.url; });
$.each(item.media$group.media$thumbnail, function (i, item) { photo_Thumb_URL = item.url; });
var photo_Description = item.media$group.media$description.$t;
$('#gallery').append("<a href='" + photo_URL + "' title='" + photo_Description + "'><img src='" + photo_Thumb_URL + "'></a>");
});
$('#gallery a').lightBox({ txtImage: 'Photo', txtOf: '/' });
}, dataType: 'json'
});
});
Replace:
dataType : 'json'
with
dataType : 'jsonp'
See: http://jsfiddle.net/b36v5/2/
It's about cross domain AJAX requests. The site you are trying to access correctly sets the access-control-allow-origin: * response header in order to allow AJAX requests for browsers that support CORS. And IE supports CORS, partially. In fact in IE in order to support CORS you have to use a different object called XDomainRequest as explained in the following blog post in order to achieve cross domain requests. Except that jQuery.ajax doesn't support it out of the box. And if you look more carefully in the bug ticket you will see that it is closed because there are plugins that allow to achieve that.