Reference error on javascript using json data from dbpedia server - javascript

Hi all and thanks in advance for the help:
i got this error:
Uncaught SyntaxError: Unexpected identifier
for line 65 (the line with the "Var query"... here the third line)
and when i click on the Execute button this is the other error:
Uncaught ReferenceError: retrieveData is not defined
(retrieveData is the function i call with the click)
i have used an existing code modifyng it for my purpose.
the very strange things are:
1: the original code run without errors (and it seems to me quite the same)
2: if i paste the url and the query and &output=json on the browser, it works fine... so i think it's not an error about mispelling...
this is the code I wrote:
<script type="text/javascript">
function retrieveData() {
var query = "SELECT ?museum WHERE {?museum a <http://dbpedia.org/ontology/Museum>.?museum <http://dbpedia.org/ontology/address> ?address. FILTER contains(?address, "Firenze")}";
var url = 'http://it.dbpedia.org/sparql?default-graph-uri=&query=' + encodeURIComponent(query) + '&output=json';
$.ajax({
url: url,
dataType: "json",
success: function (data) {
$('#results').show();
$('#raw_output').text(JSON.stringify(data, null, 3));
handle_json(data);
},
error: function(e) {}
});
}
function handle_json(json) {
$('#output_div').text("");
$.each(
json['results']['bindings'], function(index, value) {
var html = "";
name = value['museum']['value'].replace("http://it.dbpedia.org/resource/", "");
name = decodeURIComponent(name.replace(/_/g, " "));
html += "<div><h3><b>" + name + ":</b> () </h3></div>";
$('#output_div').append(html);
}
);
}
</script>
and this is the original code:
<script type="text/javascript">
function retrieveData() {
var query = "PREFIX : <http://dbpedia.org/resource/> PREFIX dbp: <http://dbpedia.org/ontology/> PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX dbpprop: <http://dbpedia.org/property/> SELECT ?person ?b_date ?d_date ?abstract ?thumbnail WHERE { ?person rdf:type dbp:Person ; dbp:birthDate ?b_date ; dbp:deathDate ?d_date ; dbp:abstract ?abstract . OPTIONAL { ?person dbp:thumbnail ?thumbnail } FILTER ( ?b_date >= '1488-01-01'^^xsd:date && ?b_date < '1600-01-01'^^xsd:date && ?d_date < '1650-01-01'^^xsd:date ) FILTER ( langMatches(lang(?abstract), 'EN')) } ORDER BY ?person ?b_date";
var url = 'http://dbpedia.org/sparql?default-graph-uri=http%3A%2F%2Fdbpedia.org&query=' + encodeURIComponent(query) + '&output=json';
$.ajax({
url: url,
dataType: "json",
success: function (data) {
$('#results').show();
$('#raw_output').text(JSON.stringify(data, null, 3));
handle_json(data);
},
error: function(e) {}
});
}
function handle_json(json) {
$('#output_div').text("");
$.each(
json['results']['bindings'], function(index, value) {
var html = "";
name = value['person']['value'].replace("http://dbpedia.org/resource/", "");
name = decodeURIComponent(name.replace(/_/g, " "));
html += "<div><h3><b>" + name + ":</b> (" + value['b_date']['value'] + " - " + value['d_date']['value'] + ")</h3></div>";
if (value['thumbnail'] != null)
html += "<div class='inline thumb'><img style='width: 200px' src='" + value['thumbnail']['value'].replace("200px", "150px") + "'/></div>";
else
html += "<div class='inline thumb'><img src=''/></div>";
html += "<div class='inline abstract'>" + value['abstract']['value'] + "</div><div class='clear'></div><br>";
$('#output_div').append(html);
}
);
}
</script>
Thanks again
--UPDATE--
Obviously i 'm made a mess with quotation mark. Thanks dodl. Now it works.
A LITTLE NOTE if anyone tries to run this script:
It will come "XMLHttpRequest same domain policy error"...
Just add the '&callback=?' in the url, using the built-in support for JSONP in JQUERY.

You're not escaping your quotation marks properly, ie:
var query = "SELECT ?museum WHERE {?museum a <http://dbpedia.org/ontology/Museum>.?museum <http://dbpedia.org/ontology/address> ?address. FILTER contains(?address, "Firenze")}";
should be
var query = "SELECT ?museum WHERE {?museum a <http://dbpedia.org/ontology/Museum>.?museum <http://dbpedia.org/ontology/address> ?address. FILTER contains(?address, \"Firenze\")}";
(Or alternatively, in javascript you can use single and double quotes to differentiate quotes within strings from string definition quotes.)

Related

PHP generated option list only appearing on first Ajax dynamically generated container

I am having an issue where my php generated select/option list is not applying to all of my dynamically generated blocks/containers. It only adds the PHP select to the last container/block instance, despite being called for each container. When troubleshooting with alerts it seems to run through all of the iterations prior to adding the containers/blocks and generating the select, hence why it always appears on the last only-
n = -1
function addDiv() {
n++;
So, a brief overview - on page initialize the code will get how many entries are in the database within a certain criteria and apply that number to 'length', which then runs the function addDiv() that many times. Usually, when adding a block one at a time via button it will populate the created block with a Select/list of Options via php in the addDiv() function, however when automating this with a loop ( the initialize() function ) the above issue occurs.
$( document ).ready(function() {
initialize();
});
function initialize() {
$.ajax({
url: 'get-entries.php',
type: 'POST',
dataType: 'text',
cache: false,
success: function(data) {
result = data;
var arrayJson = JSON.parse(data);
console.log(arrayJson);
length = arrayJson.length;
console.log(length);
for(var i = 0; i < length; i++) {
addDiv();
};
},
error: function(jqXHR) {
alert("Error while fetching data");
console.log("Error while fetching data: " + jqXHR.status + " " + jqXHR.statusText + " " + jqXHR.responseText); //improved error logging
}
});
};
here is the addDiv related code with some redactions to make it easier to read.
var n = -1;
function addDiv() {
n++;
$.post(
"json-option-generator.php",
{}
).done(
function(data)
{
$('#selectedcoin' + n).html(data);
});
$("<div class='coinmarketcap fill' id='container"
+ n +
"'><form id='"
+ n +
"' name='"
+ n +
"' class='formClass' method='post' action=''><select onchange='mySelect(this)' type='text' class='coinname' id='selectedcoin"
+ n +
"' name='selectedcoin"
+ n +
//.etc.....
"' autocomplete='off' value=''><select></select>").appendTo(".main-container");
}
and finally here is the contents of the PHP file for generating the option list based off of json data -
<?php
$json = file_get_contents("../ticker/full.json");
$decode = json_decode($json, true);
sort($decode);
echo '<select name="coinname">';
foreach($decode as $a){
echo "<option value='{$a['id']}'>{$a['name']}</option>";
}
echo '</select>';
?>
I know this is messy and may require a bit of an in depth read through, so I appreciate anyone taking the time to look.
Is there anything glaringly obvious that can help nudge me in the right direction? I have tried breaking the 'addDiv()' calls within initialize() by wrapping 'addDiv()' with a setTimeout function, but no joy.
it should work with this (I named the arguments differently for comprehension, but index and index_t can all be named n):
var n = -1;
function sendToGenerator(index){
var index_t = index;
$.post(
"json-option-generator.php",
{}
).done(
function(data)
{
$('#selectedcoin' + index_t).html(data);
}
);
}
function addDiv() {
n++;
sendToGenerator(n);
$("<div class='coinmarketcap fill' id='container"
+ n +
"'><form id='"
+ n +
"' name='"
+ n +
"' class='formClass' method='post' action=''><select onchange='mySelect(this)' type='text' class='coinname' id='selectedcoin"
+ n +
"' name='selectedcoin"
+ n +
//.etc.....
"' autocomplete='off' value=''><select></select>").appendTo(".main-container");
}

I keep getting this error SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data

This one is making me sick.because i cant find where i am going wrong.I will
appreciate any help or hint from you. below is my javascript code.so far the server side is fine but display the actual comment on the client side is the problem. please help me.
$(document).ready(function () {
// process the form
$('form.comments_form').each(function () {
var form_to_submit = $(this);
form_to_submit.submit(function (event) {
event.preventDefault();
var posta_id = form_to_submit.find("input[type=hidden].UNIQUE_ID").val();
var tetxarea1 = form_to_submit.find("textarea.target").val();
$.ajax({
type: 'POST', // define the type of HTTP verb we want to use (POST for our form)
url: 'http://localhost/Forepost/php/real_time_comment.php', // the url where we want to POST
data: {
posta_id: posta_id,
tetxarea1: tetxarea1
}, // our data object
dataType: 'json', // what type of data do we expect back from the server
success: (function (response) {
display_the_comment(jQuery.parseJSON(response));
console.log(response);
}),
error: function () {
alert("oops something went wrong");
// oops something went wrong
}
});
//FUNCTION TO DISPLAY COMMENT FROM DATABASE
function display_the_comment(response) {
var comment_string = " ";
comment_string += "<li class='indiv_cmnts'>";
comment_string += "<span class='user_fname2'>'" + response.f_name + "'</span>";
comment_string += "<div class='my_msg'>'" + esponse.my_comment + "'</div>";
comment_string += "<img class='user_proff' src='" + response.profile_img + "'/>";
comment_string += "<span class='time_cmnts'>'" + response.my_comment_date + "'</span>";
//comment_string += "<span class='fa_reply'><i class='fa fa-reply' aria-hidden='true'></i> reply</span>";
comment_string += "</li>";
$("ul.comenting2").prepend(comment_string);
}
//FUNCTION TO DISPLAY COMMENT FROM DATABASE
});
});
});
i am trying to display the list to unordered lis with the class "comenting2"
change your code from
$("ul.comenting2").prepend(comment_string);
to
$("ul.comenting2").prepend($(comment_string));
Your response value already is an object since jquery parses it automatically (you put json as datatype). You are trying to json-parse an object, of course that has illegal characters.
Yes. To make it easier to understand the problem. I believe it would be great if you also supplied the sample of your JSON response. It is usually caused by bad JSON format.
Okay. Got your sample JSON response.
Try to change your code into:
$.ajax({
type: 'POST', // define the type of HTTP verb we want to use (POST for our form)
url: 'http://localhost/Forepost/php/real_time_comment.php', // the url where we want to POST
data: {
posta_id: posta_id,
tetxarea1: tetxarea1
}, // our data object
dataType: 'json', // what type of data do we expect back from the server
success: (function (response) {
display_the_comment(eval('('+response+')'));
console.log(response);
}),
error: function () {
alert("oops something went wrong");
// oops something went wrong
}
});
//FUNCTION TO DISPLAY COMMENT FROM DATABASE
function display_the_comment(response) {
var comment_string = " ";
comment_string += "<li class='indiv_cmnts'>";
comment_string += "<span class='user_fname2'>‘" + response.f_name + "’</span>";
comment_string += "<div class='my_msg'>‘" + esponse.my_comment + "’</div>";
comment_string += "<img class='user_proff' src='" + response.profile_img + "'/>";
comment_string += "<span class='time_cmnts'>‘" + response.my_comment_date + "’</span>";
//comment_string += "<span class='fa_reply'><i class='fa fa-reply' aria-hidden='true'></i> reply</span>";
comment_string += "</li>";
$("ul.comenting2").prepend(comment_string);
}
Please noted the changes at ajax success and function display_the_comment(response)

Uncaught ReferenceError: $ is not defined - Rails [duplicate]

This question already has answers here:
Uncaught ReferenceError: $ is not defined rails
(7 answers)
Closed 6 years ago.
I keep getting this console error when trying to load data from an API
Uncaught ReferenceError: $ is not defined
I have tried placing a JQuery script within the app and it does not work.
I just want the data to append to the #resultContainer when the page is loaded
app/views/locations/show.html.erb
<div id="resultContainer"></div>
app/assets/javascripts/application.js
var _PremiumApiBaseURL = 'http://api.worldweatheronline.com/premium/v1/';
var _PremiumApiKey = 'APIKEY';
//Get Marine Weather Data
function JSONP_MarineWeather(input) {
var url = _PremiumApiBaseURL + "marine.ashx?q=" + input.query +
"&format=" + input.format +
"&fx=" + input.fx +
"&key=" + _PremiumApiKey +
"&tide=yes&";
jsonP(url, input.callback);
}
// Helper
function jsonP(url, callback) {
$.ajax({
type: 'GET',
url: url,
async: false,
contentType: "application/json",
jsonpCallback: callback,
dataType: 'jsonp',
success: function (json) {
console.dir('success');
},
error: function (e) {
console.log(e.message);
}
});
}
var resultContainer = $('#resultContainer');
var output = '';
$(document).ready(function () {
GetMarineWeather();
});
function GetMarineWeather(e) {
var marineWeatherInput = {
query: '26.13,-80.10',
format: 'JSON',
fx: '',
callback: 'MarineWeatherCallback'
};
JSONP_MarineWeather(marineWeatherInput);
e.preventDefault();
}
function MarineWeatherCallback(marineWeather) {
var allDataToday = marineWeather.data.weather[0]
output = "<br/> Date: " + allDataToday.date;
output += "<br/> Min Temp (f): " + allDataToday.mintempF;
output += " - Max Temp (f): " + allDataToday.maxtempF;
output += "<br/>";
//6AM
output += "<br/> Time: 6AM";
output += " - Surf: " + allDataToday.hourly[2].swellHeight_ft + "ft";
output += " - Swell: " + allDataToday.hourly[2].swellDir16Point + " " + allDataToday.hourly[2].swellPeriod_secs + "sec";
resultContainer.empty();
resultContainer.html(output);
}
Help
Make sure you've properly included jQuery library before calling jQuery functions Or Check any conflicting JavaScript libraries which shares jQuery $ alias.
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
IF any other JavaScript libraries' $ variable has some conflicts with jQuery, You can use jQuery.noConflict() method to avoid the same.
Eg.
var jq = jQuery.noConflict();
jq( "div p" ).hide(); //Instead of $( "div p" ).hide();
If you can access jQuery by typing jQuery, you can alias it yourself with $ = jQuery;

Ajax call jsonp from PHP

Hi guys so i made a code that parses a CSV file into a JSON ARRAY with PHP. So when you go to this URL you get the PHP output:
http://www.jonar.com/portal/mynewpage.php
Now i used this code to append my JSON ARRAY to HTML but now things have changed since i am using PHP i am not sure how to use it and what to do differently.
Also my ajax call is always empty which is weird..
$.ajax({
type: 'GET',
url: 'http://www.jonar.com/portal/mynewpage.php',
dataType: 'jsonp',
success: function(response) {
alert(response);
}
});
I used this to append my JSON ARRAY but now if i can get the response do i use the same code or will it have to be altered?
$.each(results.data.slice(1), // skip first row of CSV headings
function(find, data) {
var title = data.title;
var link = data.link;
var date = data.date;
var type = data.type;
var where = data.where;
var priority = data.priority;
if (priority == '1') {
$('ul.nflist').prepend($('<li>', {
html: '' + title + ' ' + ' ' + '<span class="category">' + type + '</span>'
}));
} else if (where == 'pp', 'both') {
$('ul.nflist').append($('<li>', {
html: '' + title + ' ' + ' ' + '<span class="category">' + type + '</span>'
}));
}
});
the reason i used PHP is to avoid cross domain issue
Thanks for the help guys!

Array and while loop: make unique clickable

I have an array (via ajax) that looks like this:
data[i].id: gives the id of user i
data[i].name: gives the name of user i
I want to output the array like this:
X Leonardo Da Vinci
X Albert Einstein
X William Shakespeare
...
The X is an image (x.gif) that must be clickable. On click, it must go to functiontwo(), passing the parameter data[i].id. Functiontwo will open a jquery dialog with the question "Delete id data[i].id"?
I know this can't be too hard to do, but I can't seem to figure it out...
This is what I have so far:
function functionone() {
$.ajax({
type : 'POST',
url : 'post.php',
dataType : 'json',
success : function(data){
var message = "";
var i = 0;
while (i < (data.length - 1))
{
var myvar = data[i].id;
message = message + "<div class=" + data[i].id + "><img src=x.gif></div>" + data[i].name + "<br />";
$('#somediv').html(message).fadeIn('fast');
$("." + data[i].id + "").click(function () {
functiontwo(myvar);
});
i++;
}
}
});
}
function functiontwo(id) {
...}
I know why this isn't working. Var i gets populated again and again in the while loop. When the while loop stops, i is just a number (in this case the array length), and the jquery becomes (for example):
$("." + data[4].id + "").click(function () {
functiontwo(myvar);
});
, making only the last X clickable.
How can I fix this?
Thanks a lot!!!
EDIT:
This is my 2nd function:
function functiontwo(id) {
$("#dialogdelete").dialog("open");
$('#submitbutton').click(function () {
$('#submitbutton').hide();
$('.loading').show();
$.ajax({
type : 'POST',
url : 'delete.php',
dataType : 'json',
data: {
id : id
},
success : function(data){
var mess = data;
$('.loading').hide();
$('#message').html(mess).fadeIn('fast');
}
});
//cancel the submit button default behaviours
return false;
});
}
In delete.php there's nothing special, I used $_POST['id'].
As I pointed out in my comment. The problem is the .click part. Either use bind, or use a class for all the elements, and a click-event like this $('.classnamehere').live('click',function () { // stuff });
function functionone() {
$.ajax({
type : 'POST',
url : 'post.php',
dataType : 'json',
success : function(data){
var message = "";
var i = 0;
while (i < (data.length - 1))
{
var myvar = data[i].id;
message = message + "<div class=\"clickable\" id=" + data[i].id + "><img src=x.gif></div>" + data[i].name + "<br />";
$('#somediv').html(message).fadeIn('fast');
i++;
}
}
});
}
$('.clickable').live('click',function () {
alert($(this).attr('id') + ' this is your ID');
});
The usual trick is create a separate function to create the event handler. The separate function will receive i as a parameter and the generated event will be able to keep this variable for itself
make_event_handler(name){
return function(){
functiontwo(name);
};
}
...
$("." + data[i].id + "").click( make_event_handler(myvar) );

Categories

Resources