Difficulties using JSONP in jQuery - javascript

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>");
});
});

Related

Parsing BBCode on AJAX success

I am in a spot here trying to parse BBCode upon a AJAX success : item.message object. I am using jQuery 1.11. I have tried passing the var result in place of item.message, and only shows the [object] errors. I have tried wrapping item.message with XBBCODE and same thing.
Im not sure what to do, the script is great otherwise. We must parse bbcode to HTML or a method that can be managed PHP-side, but I don't think this is possible over JSON data.
Currently this is my jQuery code:
$(document).ready(function () {
$.ajax({
url: "/ajax/shoutbox.php",
method: "GET",
dataType: 'JSON',
success: function (data) {
var html_to_append = '';
$.each(data, function (i, item) {
// Object array repeated - not working
var result = XBBCODE.process({
text: 'item.message',
removeMisalignedTags: false,
addInLineBreaks: false
});
/*
currentPost = jQuery(this);
postHTML = bbcodeToHTML(currentPost.html());
currentPost.html(postHTML);
*/
html_to_append +=
'<div class="shoutbox-container"><span class="shoutDate">' +
jQuery.timeago(item.date) +
' <span style="color:#b3b3b3">ago</span></span><span class="shoutUser"><img src="' +
item.avatar +
'" class="shout-avatar" /></span><span class="shoutText">' +
item.message +
'</span></div><br>';
});
$("#shoutbox").html(html_to_append);
$(".shoutbox-container").filter(function () {
return $(this).children().length == 3;
}).filter(':odd').addClass('shoutbox_alt');
$(".shoutbox-container").each(function () {
$(this).parent().nextAll().slice(0, this.rowSpan - 1).addClass('shoutbox_alt');
});
}
});
});
As you see, I'm trying to make use of the following javascript:
https://github.com/patorjk/Extendible-BBCode-Parser
I've followed the instructions exactly, before moving into the JS above with no success either way. I get this:
[object][Object]
For each iteration of the message object coming back (its a custom AJAX shoutbox).
Commented, you can see another method I have tried to no success. Any help is appreciated!
Update: Working
Thank you, Quiet Nguyen for the suggestion for replacing item.message with result.html and updating text: object

Why am I getting a '$' is not defined when running an AJAX query?

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.

Extracting data from a GET response/JSON object

Haven't touched Javascript for a bit while and cannot find a proper way to extract data from a JSON object.
So I am basically sending a simple GET request to the Giphy API and attempting to get URL's from the response but for some reason I get all kinds of errors.
This is what I tried:
$(function() {
$('#searchButton').click(function() {
console.log("test");
$("#result").append("test<br />");
var xhr = $.get("http://api.giphy.com/v1/gifs/search?q=cats&api_key=dc6zaTOxFJmzC&limit=1");
xhr.done(function(data) {
console.log(this.fixed_height);
$("#result").append("success got data<br />" + data + "<br />");
console.log("success got data", data);
$.each(data.results, function() {
$.each(this.images, function() {
console.log(this.fixed_height);
$("#result").append(this.fixed_height + "<br />");
});
})
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="searchButton">search!</button>
<div id="result"></div>
You have a couple of problems. First, there is not a results member in the data object. The only thing I see that you can iterate on, in the data object is yet another data member. Second, inside the images, there is no fixed_height, just height. This works:
var xhr = $.get("http://api.giphy.com/v1/gifs/search?q=cats&api_key=dc6zaTOxFJmzC&limit=1");
xhr.done(function (data) {
$.each(data.data, function () {
$.each(this.images, function () {
console.log(this.height);
});
})
});
http://jsfiddle.net/n9ffva83/
Remember $(function () {});is not needed in JSFiddle, so you must provided (just the way you do in the code you gave us above).
EDIT:
To just get the url of the fixed height try this:
var xhr = $.get("http://api.giphy.com/v1/gifs/search?q=cats&api_key=dc6zaTOxFJmzC&limit=1");
xhr.done(function (data) {
$.each(data.data, function () {
console.log(this.images.fixed_height.url);
})
});
It seems this url is only one, that belong to the images.
http://jsfiddle.net/n9ffva83/1/

Read media\\:thumbnail RSS feed with Jquery

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

why would .load not work in IE8

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 > *");

Categories