Micro data from json - javascript

I was wondering how to get through the testing tool of Google when it comes to rich snippets or micro data and using json data.
The thing is that I don't have the option to use PHP and only javascript. So when I want to grab review data from let's say Trusted Shops for a shop I never get passed the testing tool because the data is always empty when Google crawls the page.
So what I mean is this:
There's a direct link to the json file with the review data
http://api.trustedshops.com/rest/public/v2/shops/X17BD396442BCEE0808C79156D0E95F97/quality/reviews.json
What I tried is this
<script type="text/javascript">
window.onload = function(){
var url = 'http://api.trustedshops.com/rest/public/v2/shops/X17BD396442BCEE0808C79156D0E95F97/quality/reviews.json';
$.getJSON(url, function(data){
var stuff = data.response.data;
var review = stuff.shop.qualityIndicators
$('#value').html(review.reviewIndicator.overallMark);
$('#votes').html(review.reviewIndicator.activeReviewCount);
});
}
</script>
HTML output
<span xmlns:v="http://rdf.data-vocabulary.org/#" typeof="v:Review-aggregate">
<span rel="v:rating">
<span property="v:value" id="value">4.83</span> /
<span property="v:best" id="best">5.00</span>
</span> of
<span property="v:votes" id="votes">58</span> reviews.
</span>
Now with the Testing tool from Google I always get 3 errors saying "can't leave blank...".
Is such thing even possible??

So I have no clue how to use this tool, but none of their examples have javascript in them. I don't think this tool will execute any javascript in the left hand box before it tries to validate the data. There are examples with <script type="application/ld+json"> tags, but they are just JSON data, and not executable code (note the type).
To verify this I simply entered this snippet:
<script type="text/javascript">
console.log('it this on?');
</script>
When I click validate, nothing shows up in my browser console.
Whatever you are trying to make this tool do, I think is outside the scope of how it's intended to be used. It appears that this tools can validate the result of your code, but it cannot also run your code.

Related

AutoComplete Google Javascript

Hi I am having trouble getting the autocomplete to display like here. My code works on submit and displays the map properly, but does not show results of autocomplete. I am wondering what could be the issue.
Here is my HTML
<div id="floating-panel">
//this is the text field that does not display the autocomplete
<input id="address" placeholder="Enter Starting Location" type="text"/>
<input id="submit" type="button" value="Directions">
</div>
<div id="right-panel"></div>
<div id="map"></div>
Here is my Javascript:
var autocomplete = new google.maps.places.Autocomplete(document.getElementById('address'));
Here is my call to autocomplete, the API is enabled, I see calls being made on the data, but no results back:
https://maps.googleapis.com/maps/api/js?key=xxx&libraries=places&callback=initMap: {type: external, attributes: {async: true}}
Google maps API has new security changes in its new version, use version 3.0, this works for me:
<script src="https://maps.googleapis.com/maps/api/js?v=3.0&key=YOUR_KEY&libraries=places" async></script>
I'm getting the same thing with very similar code. For me that code was working for months and just today I got a report from a user that the drop down list of locations wasn't showing anymore.
var input = $("input[name='location']");
var formattedAddress = input.next("input[name='formattedLocation']");
var searchBox = new google.maps.places.SearchBox(input[0]);
searchBox.addListener('places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
formattedAddress.val('');
return;
}
formattedAddress.val(places[0].formatted_address);
});
I was thinking that maybe we went over our daily quota, but it doesn't seem so from the Google API console. I don't see any errors in the browser console. If I look in developer tools network tab I can see requests going to https://maps.googleapis.com/maps/api/place/js/AutocompletionService.GetQueryPredictions, but the responses seem rather cryptic (ex:/**/xdc._490z0c && xdc._490z0c( [4] ) ) so I can't tell if good data is coming back or not.
I'm wondering if something changed recently on the Google side that I haven't heard about.
My temp solution: I went with the experiential version, https://maps.googleapis.com/maps/api/js?v=3.32 and noticed at the bottom of my HTML there is a tag <div class="pac-container pac-logo hdpi">once you start typing it updates, style this and got fixed. I sent a issue request I am hoping they are going to fix this for the stable version.
https://developers.google.com/maps/documentation/javascript/versions
Specify that you want to use the release version rather than the experimental if you are on the standard plan.

Embed same web widget multiple times with different data attribute values

I want to create a web widget that can be embedded multiple times on the same page but with different data attribute values so I can display different data according to the data attribute value.
For example, I want to embed mywidget.js file multiple times as follows:
<body>
<div>
<script src="script/mywidget.js" data-sport="soccer" id="widget-soccer">
</script>
</div>
<div>
<script src="script/mywidget.js" data-sport="tennis" id="widget-tennis">
</script>
</div>
</body>
My question is, inside the code in mywidget.js, how do I determine the correct script tag reference and read it's data attribute so I can use that value to fetch the corresponding data from a web service. I am using only jquery and javascript.
I want the widget to be embeddable on other users sites as well so all they do is embed using only the script tag and passing in the desired data attribute value without adding anything extra anywhere they need on their website.
This is not really a very good approach, as it is very inflexible. But given that <script> tags, when not deferred, halt parsing of the document while they execute, the current script tag will be the last in the DOM; so you can get the current sport inside your script by using this:
var sport = $('script').last().data('sport');
However, it would be much better to define a function in your external JavaScript file, and then invoke it when you need to instantiate your widget (EDIT: like in Lee Taylor's answer).
Why don't you do something like:
<head>
<script src="script/mywidget.js"></script>
</head>
<body>
<div><script>createMyWidget({sport : "soccer"} );</div>
<div><script>createMyWidget({sport : "tennis"} );</div>
</body>
I don't think you can. I know it's not that nice, but I would try:
<div><script>sport = "soccer";</script><script src="script/mywidget.js" id="widget-soccer"></script></div>
<div><script>sport = "tennis";</script><script src="script/mywidget.js" id="widget-tennis"></script></div>
and use sport in mywidget.js
Another approach could be that myscript.js is actually a dynamic "page", let's say with php, then you could use src="script/mywidget.js?sport=swimming", and in the php you would print:
sport = "<?php echo addcslashes($_GET['sport'], '"'); ?>";
But even better would be:
<script src="script/mywidget.js"></script>
<div><script>showWidget("soccer");</script></div>
<div><script>showWidget("basketball");</script></div>
I think you can use jQuery to find all script tags with src="script/mywidget.js" or something
$('script[src="script/mywidget.js"]')
And then you'll have an array of scripts tags that you can loop through and access the data property using jQuery's .data() method.

Interpret variable in Javascript file Laravel

I need to include a js file in my views.
But in this js file i need to interpret somes PHP variable.
Actually i do this :
#section('javascript')
<script>
alert("{{{test}}}");
</script>
#stop
But i REALLY need to do this :
#section('javascript')
{!! Html::script('js/test.js') !!}
#stop
test.js :
alert("{{{test}}}");
I need to declare a lot o variable. So my JS file will be very huge. And i don't want to show this directly in the source code.
How can i do ?
Thank you !
You can only pass the variable to the javascript like so:
#section('javascript')
<script>
var test = {{{$test}}};
</script>
#stop
then in your javascript file included at the bottom you can use it:
alert(test);
Let me just mention that this is not a great way of handling the passing variables from php to javascript.
When I need to do something like this, I usually create a meta tag on the page which would contain the alert information.
<meta name="someAlertValue" content="{{{ $test }}}" />
Then you can very easily grab that via jQuery.
var alert_text = $('meta[name=someAlertValue]').attr('content');
I find this approach to be much cleaner and maintainable than trying to drop php variables directly into your javascript.
I had the same problem, and wanted to have a stand alone js which will have bunch of variables taken from config() or even from database, multi-language, and will be configurable, or even will work with query parameters.
Maybe it's a hard way, but i've created a route:
Route::get('/js-modules/test.js',function(){ return view('js-modules.test');})->name('my_js);
So in the view resources/views/js-modules/test.blade.php you can put your js code together with your PHP stuff.
Or you can route it to a controller and have even more background work. it looks a bit slow (in the browser) on the first run , but second request it'll be cashed and retrieved as the regular js file
And now you can link it to any of your pages with
<script src="{{route('my_js')}}"></script>

"onComplete attribute must be javascript function name" what am i typing wrong?

I'm trying to run a piece of JavaScript code on completion of a song in the <cfmediaplayer> tag but whenever i put "playNext()" into the onComplete attribute it provides me with an error telling me it must be a proper name, but that is the proper name? Anybody know where i might be going wrong?
<script type="text/javascript">
function playNext(){
<cfoutput>
var #ToScript(URL.current, "trackNo")#;
</cfoutput>
trackNo++;
$("#" + trackNo).click();
}
</script>
<div style="margin: 0 auto; width: 500px;">
<cfoutput query="getmusic" maxrows="1">
<cfmediaplayer name="musicPlayer" source="/artists/music/#music_location#" autoplay="yes" height="500" width="500" title="#artist_name# - #music_name#" onComplete="playNext"></cfmediaplayer>
</cfoutput>
</div>
This is my code, however i just noticed (using the Web Developer toolbar) that it is saying playNext is undefined, yet clearly i DO have it defined there as displayed. I'm wondering what I may have done wrong, as far as i'm aware my JavaScript looks OK but i'm a novice when it comes to JS so i've probably made a simple mistake.
use onComplete="playNext" not "playNext()"
Try calling "playNext()" in the onComplete attribute as playNext with no quotations or brackets. If that does not work use playNext(). Let me know if that helps.
I could be wrong but I think it has to do with a CFIDE mapping.
The CFIDE/Scripts folder is needed for a lot of the client side controls ColdFusion creates.
Some CFForm elements like the date picker, multiple file upload, cfajaxproxy, cfmediaplayer, etc require these scripts to be mapped or copied to the site.
Here is a SO question that may help.
Workaround for CFIDE Not Web Accessible for AJAX and Flash Built-Ins
Here is a general google search on the subject.
Try a simple script to mute the player you get any 'Coldfusion is undefined' errors. something like
<script language ="javascript">
ColdFusion.Mediaplayer.setMute('musicPlayer', true);
</script>

HTML/Javascript search function with AJAX

I've created a webpage where I want users to be able to search for a word/term stored in a CSV file, and if that term is found the full line for that line entry will be returned and displayed to the user (ideally in table format, otherwise a textarea will do).
But I need to do this using AJAX, and I also cant use PHP (unfortunately, otherwise I wouldn't be asking this question).
So far I have a table for the form/input/button, and I've also got the code to read the file, but I'm a bit stuck with bringing both together. I know this should be an easy thing to do, but I've spend a lot of time going through tutorials and online questions but havent been able to find anything similar.
If anyone knows of any tutorials that covers this, or can help out with the code below it would be appreciated.
<table>
<tr><td>Enter Search Term:
<input type="text" name="searchword" />
<input type="button" name="searchbutton" value="Search" onclick="contentDisp();">
</td></tr>
<tr><td><textarea id="contentArea" rows="40" cols="60"></textarea></td></tr>
</table> //currently using text area but ideally this would be displayed in a table
<script type="text/javascript">
function contentDisp()
{
$.ajax({
url : "file.csv",
success : function (data) {
$("#contentArea").html(data); // I THINK SOMETHING NEEDS TO GO IN HERE, WHICH WILL GRAB THE SEARCH TERM ABOVE AND THEN ONLY DISPLAY FILE CONTENTS USING THAT TERM, POSSIBLY 'CONTAIN' */
}
});
}
</script>
It is possible to do this strictly via JavaScript by using some strpos and indexOf functions (indexOf is the starting point, while the other will look for the string delimiter(s) ).
it is also possible to do the task with php if you feel comfortable with it, if you're restricted by domain-origin restriction, take a look at JSONP, which stands for JSON with Padding - which basically means that you'll need to wrap the result in a JavaScript function.
good luck.
User Regular Expressions to find your string and to parse the found line in the CSV data.
http://www.w3schools.com/jsref/jsref_obj_regexp.asp
HTML
<input type="text" id="text" />
<input type="submit" id="btnsubmit" />
Script
$(function(){
$('#btnsubmit').on('click', function(){
var csv = $.ajax('text.csv');
csv.done(function(data){
var str = data.split(',');
var value = $('#text').val();
$.each(str, function(index, item){
if(item.match(value)){
console.log(item) //Output
};
})
})
})
});
CSV
Presidency ,President ,Wikipedia Entry,Took office ,Left office ,Party ,Portrait,Thumbnail,Home State
Why would you use strpos and indexOf when javascript already has built-in functions for matching strings?
http://jsfiddle.net/AWZg8/

Categories

Resources