I'm trying to get my head around how I can make json request to a json file stored on my server from jsfiddle.
html:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="images">
</div>
</body>
</html>
jquery:
$.getJSON("http://www.shopsheep.com/groupon/json/test.json?jsoncallback=?", function(data) {
$.each(data.items, function(i, item) {
$("<img/>").attr("src", item.media.m).appendTo("#images");
if (i == 0) {
return false;
}
});
});
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?format=json&jsoncallback=?", function(data) {
$.each(data.items, function(i, item) {
$("<img/>").attr("src", item.media.m).appendTo("#images");
if (i == 0) return false;
});
});
I downloaded the flicker json file and uploaded it to my server as test.json. If I paste it in the browser it returns just as the flicker file.
However when I try to display the image only the original flicker example is working? Any idea why this is the case?
http://jsfiddle.net/stofke/DJQ5g
Ok I have found out how to do this. The getJSON function adds a random
named callback functionname to jsoncallback=? something like this
jQuery160188050875203142_1309437718540&_=1309437718551
In order to wrap your json file with this callbackfunction you need of course to know the name of this function, so if you convert your jsonfile into a php file than you can get the callbackfunctionname like this:
<?php echo $_GET["jsoncallback"];?>(
ADD JSON CONTENT HERE
)
This php file will get the name of the callbackfunction via a GET variable and wraps the json content with it. This way it works fine.
Your JSON file missed function name. It should start with function name.
If you see here http://api.flickr.com/services/feeds/photos_public.gne?format=json, it starts with jsonFlickrFeed.
Your JSON should be like this:
callback({
"title": "Uploads from everyone",
"link": "http://www.flickr.com/photos/",
"description": "",
"modified": "2011-06-29T21:43:16Z",
"generator": "http://www.flickr.com/",
"items": [
{....
Maybe you need to understand more about JSONP. http://en.wikipedia.org/wiki/JSONP
Related
I am using the following to save the html of a certain website in a string
function loadajax(dname) {
$.ajaxSetup({async: false});
$.get('https://www.example/?param=param1', function(response) {
var logfile = response;
//alert(logfile);
});
}
The problem is that in the html code there are some codes like {{sample}} which seems that there a not loaded yet when the Ajax call is getting the code. When I perform the operations manually I can clearly see HTML code instead of the " {{ }}'s ".
I have already tried {async: false}...
I'm developing a website and I want to add structured data to detailed pages.
The problem is that I need to request the data before knowing what to add to the JSON-LD script.
I am using Parse as a backend. I also tried to look around for tutorials on how to achieve that but it seems not possible to add JSON-LD dynamically.
I really hope someone can help me with that! :)
EDIT:
The response with the data I need to put in the JSON-LD comes after the DOM is ready. What is it the pattern in this situations?
I have a list of items and when clicking on one of them I have to open a detail page which I have to load first, but after content is loaded I want to provide structured data through JSON-LD.
I'm at the beginning and I'm finding hard times solving this.
EDIT 2:
This is my actual implementation:
In the HTML:
<body>
// my html page code
...
<script type="text/javascript">
loadDetailPageContent();
</script>
</body>
In the JS:
function loadDetailPageContent() {
// Calling the method here is too early because I don't have info
//writeData();
createDetailPage();
}
function createDetailPage() {
var recipe = Parse.Object.extend("Recipe");
var query = new Parse.Query(recipe);
query.equalTo("objectId", myId);
query.first({
success: function(result) {
// Calling the method here would be perfect
writeData();
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
}
function writeData() {
var script = document.createElement('script');
script.type = 'application/ld+json';
script.text = JSON.stringify({
"#context": "http://schema.org",
"#type": "Recipe",
"name": "My recipe name"
});
document.querySelector('head').appendChild(el);
}
As you can see the method writeData() is called in two places. If I call it immediately at the beginning, there is no problem and with the use of the Google Structured Data testing tool, I am able to track the structured data I need. The problem with that is that at that point I don't have the information to create the structured data because I need to wait for the response from Parse.
When I am calling the method in the success callback, then the testing tool is not able to retrieve the data anymore :(
http://jsfiddle.net/c725wcn9/2/embedded
You will need to inspect the DOM to check this works. Jquery is needed.
$(document).ready(function(){
var el = document.createElement('script');
el.type = 'application/ld+json';
el.text = JSON.stringify({ "#context": "http://schema.org", "#type": "Recipe", "name": "My recipe name" });
document.querySelector('head').appendChild(el);
});
Your code included the variable name script but appended the variable el to the <head> instead. Also removed are the new line characters from the JSON string which was checked with JSON-LD playground .
i think Mousey perfectly answered this, i am going to share similar
scenario where we load flight details on page but for price we call an API
when page load, so we have to load schema dynamically when we get price.
We created a nested function which we call on page load and pass flight
details then on page load when we call "priceGraber" API (to get flight
price), Once priceGraber return successful response then we inject schema
on page.
Schema Creator Function:
// create product schema
createProductSchema = function(from, to, currency) {
return injectSchema = function(price) {
let el = document.createElement('script');
el.type = 'application/ld+json';
el.text = JSON.stringify({
"#context": "https://schema.org/",
"#type": "Product",
"name": `Flight from ${from} to ${to}`,
"description": `Cheap flights from ${from} to ${to}`,
"offers": {
"#type": "Offer",
"url": `http://flightsearches.net?fso=${from}&fsd=${to}`,
"priceCurrency": `${currency}`,
"availability": "https://schema.org/InStock",
"price": `${price}`,
}
});
console.log('inject now ');
document.querySelector('head').appendChild(el);
};
};
On Page Load Pass Information for schema which is available on page load
below script is inside blade file, {{ $flight_from }}, {{ $flight_to }} are blade directive (server side variables)
<script>
$(function(){
if(typeof createProductSchema == "function") {
console.log('create product schema...');
window.injectProductSchema = createProductSchema({{ $flight_from }}, {{ $flight_to }});
} else {
console.error("product schema creator doesn't exists !");
}
});
</script>
Dynamically Injecting Schema
we call below function inside ajax response where we get "price" form API and then this function call nested function which then append schema into head
window.injectProductSchema(price);
I've a JavaScript file script.js like this:
var myArray = {"INSERT":"ARRAY"};
Further I've a array.json file like this:
{
"Item1": "Text1",
"Item2": "Text2"
}
I would like gulp to replace the array in the script.js with the content in the array.json file. How can I do that?
I've been looking at gulp-replace and have this example:
gulp.task('my-task', [], function () {
return gulp.src(['script.js'])
.pipe(replace('{"INSERT":"ARRAY"}', '{"MY":"OTHER_ARRAY"}'))
.pipe(gulp.dest("dist.js"));
});
where I successfully replace the text, but instead of replacing with a static array, I need to read the array.json file instead and use this instead. I'm not sure how I can do that or if there are any better solutions to this? I've been looking at gulp-inject, but I'm not sure if this can be used in my case?
Just read the file contents?
gulp.task('my-task', [], function () {
var replacement = fs.readFileSync('path/to/file');
return gulp.src(['script.js'])
.pipe(replace('{"INSERT":"ARRAY"}', replacement))
.pipe(gulp.dest("dist.js"));
});
I have an HTML page from which i want to read a remote webpage which is at http://xtremeinspection.com/new2you4kids/app/android/get_product_size.php?productID=113
The webpage returns a value depending on the Query string parameter passed that is the productID
My question is since its cross domain reading data which is the best method to use Jquery/Ajaz/Json or mix of all these ?
I have searched it on Google but i cant find example of reading and displaying the data in a DIV .
I am using this code but it doesnt display anything
<script type="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.getJSON('http://xtremeinspection.com/new2you4kids/app/android/get_product_size.php?productID=113', function(data){
$.each(data, function(i, tweet){
$('#tweets').append('<li>' + tweet.text + '</li>');
alert(tweet.text);
});
});
});
</script>
<ul id="tweets"></ul>
A basic example like this should help you get started:
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
{
tags: "gulmarg",
tagmode: "any",
format: "json"
},
function(data) {
$.each(data.items, function(i,item){
$("<img/>").attr("src", item.media.m).appendTo("#images");
if ( i == 5 ) return false;
});
});
DEMO
I've been looking around, but I'm not quite sure what to search for...
I want to have a webpage send a Get request to a python script when you first open the page, maybe with the option to refresh it with a button. Is there a way to send a request ("script.py?var=test") and display the results within the page?
What I tried to use earlier: (didn't work..)
Am I doing something stupid? I don't know anything about JavaScript
<p>Highscores:</p>
<p id='scores'>text</p>
<input type='button' onclick='changeText()' value='Change Text'/>
<script type="text/javascript">
function changeText(){
var request = new XMLHttpRequest();
request.open("GET", "../../cgi-bin/highScore.py?scoreMethod=load&game=ulama", true)
request.onreadystatechange = function(){
var done = 4, ok = 200;
if (request.readyState == done && requeset.status == ok){
document.getElementById('scores').innerHTML = request.responseText;
}
};
request.send();
}
</script>
Also, should I have the python script return a full page with the header and all? or just the relevant section?
Use a Jquery call in this case to clean up your code a little bit.
Also in this case you should use a post because of the nature of your 'beast' :)
function changeText(){
$.ajax({
method : "POST",
URL : "../../cgi-bin/highScore.py",
data : {
"scoreMethod" : "load",
"game" : "ulama"
},
success : function(data) {
$("#scores").html(data);
}
});
}
I'd also look into JSON and jquery being returned as its probaly going to be easier in the long term (Though ive never played with python.
why not using jquery for doing this?
$('#scores').load('../../cgi-bin/highScore.py?scoreMethod=load&game=ulama', function(responseText, textStatus) {
alert(textStatus);//check here whether textStatus equals 'success' or something else (maybe an error)
});