Appending Syntax Error to HTML Element - javascript

I'm using YQL and jQuery.ajax to retrieve an inline JavaScript variable from another website. This variable contains a complete XML document that base64 encoded.
While the AJAX request is working, I can't figure out how to take the res.query.results and append it to a dynamically made <script> element.
Here's the jQuery:
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql/dj/fsp?format=json",
type: "GET",
success: function(res) {
var sc = $('script');
$(sc).append(document.createTextNode('var '+$(res.query.results)));
$('head').append(sc);
}
});
Here's what the console log is telling me:
Any ideas or suggestions would be greatly appreciated. Thanks, everyone!

Three things:
To create a script element, you do $('<script>'), not $('script'). The latter searches for all script elements.
No need for createTextNode, jQuery will handle that for you.
You're over-doing it with the calls to $():
var sc = $('<script>');
sc.append(document.createTextNode('var '+res.query.results));
// ^ #1 (see below) ^ #2
You don't want to do $(sc) again, it's pointless, it's already a jQuery instance.
You don't want to parse res.query.results into a jQuery instance, you want to grab the string into a JavaScript variable (apparently).
Live example:
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<meta charset="utf-8">
<title>Example</title>
</head>
<body>
<script>
(function() {
"use strict";
display("Doing query...");
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql/dj/fsp?format=json",
type: "GET",
success: function(res) {
display("Got result, creating <code>script</code>...");
var sc = $('<script>');
sc.append('var '+res.query.results);
$('head').append(sc);
display("length of <code>txt</code> global variable: " + window.txt.length);
}
});
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
})();
</script>
</body>
</html>

Related

How can I include the content of PHP files in output generated by JavaScript?

I have a JS script that scrapes a bit of data and outputs the result to the screen. That works fine. What I now need to do is wrap that output in some pre and post content php files for formatting purposes, and I can't seem to get it to work.
Here's where the script stands now:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<meta content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;" name="viewport">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<link rel="stylesheet" type="text/css" href="css/main.css">
</head>
<body>
<img id="loading-gif">
<script>
$('#loading-gif').hide();
$(document).ready(function () {
$('#loading-gif').show();
$.ajax({
url: "https://aajumpseat.com/dev/include/pre.content.php'); ?>",
type: 'GET',
dataType:"json",
success: function(data) {
pre = JSON.parse(data);
document.write(pre);
}
});
$.ajax({url: "https://aajumpseat.com/dev/scrape/getSegments.php"}).done(function (data) {
$('#loading-gif').hide();
output = JSON.parse(data);
document.write(output);
});
$.ajax({
url: "https://aajumpseat.com/dev/include/post.content.php'); ?>",
type: 'GET',
dataType:"json",
success: function(data) {
post = JSON.parse(data);
document.write(post);
}
});
});
</script>
</body>
</html>
The second ajax call works perfectly and outputs the result to the screen, which is what I want. What I would like to do is place the contents of pre.content.php before the result and the contents of post.content.php after the result so that the result is properly formatted.
There is some php being executed in 'pre.content.php is addition to the formatting html, while 'post.content.php contains only the closing body and html tags.
If need be, I can hardcode the required html into the above script, but if someone has an elegant, or not so elegant, solution on how to include these two files I'd appreciate it.
Thanks.
There's a function specifically for this called $.load(). It's always better to have a <div> with id and then use .innerHTML instead of using document.write().
$(function () {
$("#stuff").load("/path/to/api/call");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="stuff"></div>
If you have got multiple calls, that's fine too. Just have multiple containers.
$(function () {
$("#stuff").load("/path/to/api/call");
$("#pre").load("/path/to/api/code");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="stuff"></div>
<pre id="code"></pre>
One thing to note is that, $.load() fires an AJAX GET request.
place the contents of pre.content.php before the result and the contents of post.content.php
Don't use document.write. It gives you no control over where in the document you write anything. Instead, define the elements where you want to write your output:
<div id="pre-output"></div>
<div id="main-output"></div>
<div id="post-output"></div>
Then write your output to those specific locations:
pre = JSON.parse(data);
$('#pre-output').html(pre);
(Or maybe .text(pre)? It's strange to me that you're outputting raw JSON...)
******* SOLUTION *******
My main php has multiple tasks, so for this particular task the PHP is:
$output = " <div id='loading-gif'><img src='images/loading3.gif';></div>
<div id='main-output'></div>
<script>
$('#loading-gif').hide();
$(document).ready(function () {
$('#loading-gif').show();
$.ajax({url: 'https://aajumpseat.com/dev/scrape/getSegments.php'}).done(function (data) {
$('#loading-gif').hide();
output = JSON.parse(data);
//document.write(output);
$('#main-output').html(output);
});
});
</script>
<div class='bottom-border'></div>
";
and further down the page I have:
include('include/pre.content.php');
echo $output;
include('include/post.content.php');
And it is perfect.

Ajax - setInterval not triggerd

The code below is not triggered as per the interval set in the setInterval. When the page is loaded the first time the result set is returned, but the Ajax script does not run after first time page load.
<html>
<head>
<script language="javascript" type="text/javascript" src="jquery.js"></script>
</head>
<body>
<!-------------------------------------------------------------------------
1) Create some html content that can be accessed by jquery
-------------------------------------------------------------------------->
<h2> Client example </h2>
<h3>Output: </h3>
<div id="output"></div>
<script id="source" language="javascript" type="text/javascript">
$(function getEvent()
{
//-----------------------------------------------------------------------
// 2) Send a http request with AJAX http://api.jquery.com/jQuery.ajax/
//-----------------------------------------------------------------------
$.ajax({
url: 'get_events.php', data: "", dataType: 'json', success: function(rows)
{
for (var i in rows)
{
var row = rows[i];
var id = row[0];
var vname = row[1];
var time = row[2];
$('#output').append("<b>id: </b>"+id+"<b> name: </b>"+vname+"<b> time: </b>"+time)
.append("<hr />");
}
}
});
});
$(document).ready(function () {
var run = setInterval(getEvent, 1000);
});
</script>
</body>
</html>
I have looked at all the similar posts in this forum, but I still can't get my function to be triggered by setInterval. Please see my code below. Any help is appreciated.
Looks like your function is not in the global scope. Setinterval doesn't know about it.
Use var getEvent = function() { ... } to declare the function rather than $ wrapper.
By doing this
$(function functionName(){/*function body*/})
you are passing a function to another function called $. This doesn't create a function called functionName anywhere. So, when you are starting your interval, you are trying to call a function which does not exist.
Remove $() from around your function declaration. This will define a function rather than pass it as a parameter.

Calling json data from an api

I am trying to retrieve data from an api and use it to populate the div with the ID "output". I get an error that the $ is undefined. Can anyone help determine what I am missing?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="Content-Script-Type" content="text/javascript">
<meta name="Content-Style-Type" content="text/css">
</head>
<body style="margin: 0px; padding: 0px;">
<div id="fullscreen">
<div id="output">
</div>
</div>
</body>
<script>
$.ajax({
type: 'GET',
url: "https://apiurl.com",
dataType: "json",
crossDomain: true,
success: function( response ) {
console.log( response ); // server response
var id = response[0];
var vname = response[1];
$('#output').html("<b>id: </b>"+id+"<b> name: </b>"+vname);
}
});
</script>
</html>
As Sirko already explained in the comments, you are trying to use the javascript library JQuery, but the library is not available because you didn't include it.
You can include it by either downloading JQuery here and including it via
<script src="src_to_local_jquery.js"/>
or by including it externally (described in CDN section of above link)
Also note, that script tags should be put either in the head or the body section. To make sure your custom script is executed after the page is ready, you can use JQuery's document ready method.
The $ sign is not part of the JavaScript language, it is a short hand for a third party library jQuery ($ === jQuery).
You need to add it as a dependency in your html file with a script tag with a src attribute containing the URI for the source file before you can use it.
<html>
<head></head>
<body>
...
...
<script src="//code.jquery.com/jquery-3.1.1.js"></script>
<script>
$(function () {
// Your code here
});
</script>
</body>
</html>
Include jQuery either as a CDN or download add reference locally. Then make sure the DOM is ready before you make the call. You can read more about that here
<script src="local_jquery.js"/>
// OR
<script src="https://code.jquery.com/jquery-3.1.1.js"></script>
$(function() {
$.ajax({
type: 'GET',
url: "https://apiurl.com",
dataType: "json",
crossDomain: true,
success: function( response ) {
console.log( response ); // server response
var id = response[0];
var vname = response[1];
$('#output').html("<b>id: </b>"+id+"<b> name: </b>"+vname);
}
});
});

How do I look up the HTML5 'data' attribute when parsing an xml file using Javascript?

This is the code I have. I am trying to pull out the "data" attribute and drop it into the div at the end with id "question". I'm pretty new to JS and know there must be something really basic that I'm doing wrong, what is it?!
<!DOCTYPE HTML>
<html>
<head>
<script language="javascript" type="text/javascript">
function display() {
var base = document.getElementById("output");
var CompleteSuggestion = base.getElementsByTagName("CompleteSuggestion")[1];
var suggest = CompleteSuggestion.getElementsByTagName("suggest")[0];
var question = suggest.getAttribute("data")[0].firstChild.data;
document.getAttribute("data").innerHTML = question;
}
</script>
</head>
<body onload="display()">
<xml id="output" style="display: none;">
<CompleteSuggestion>
<suggest data="hello">
</CompleteSuggestion>
</xml>
<div class="question" id="question"></div>
</body>
</html>
Here's a better way to get the attributes from an xml file
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
//use ajax to grab the xml file
//I had an xml file named your.xml in the same directory as this script
$.ajax({
type: "GET",
url: "your.xml",
dataType: "xml",
success: function (xml) {
//when the file has loaded via the ajax request loop over each suggestion element
$(xml).find('suggestion').each(function() {
//get the value of the first attribute (data), from this suggestion row
console.log( this.attributes[0].value );
});
}
});
</script>

Trying to remove duplicate info received from an xml file displayed on my html page

I am trying to delete the duplicate atrists that are displayed when I retrieve the info from this xml file using JQuery. How can I accomplish this?
Here is the js file:
$(function(){
$(window).load(function(){
$.ajax({
url: 'http://imaginationeverywhere.info/djronlove/new_2.xml',
dataType: 'xml',
success: function(xml){
$(xml).find("key:contains('Artist') + string").each(function(){
var string1 = $(this).text();
$('<p></p>').addClass('string1').html(string1).appendTo('#container');
});
}
});
});
$('<div></div>').attr('id', 'container').appendTo('body');
});
Here is the html file:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>DJ Ron Love Music Catalog</title>
<script type='text/javascript' src='http://imaginationeverywhere.info/jslib//dev/jquery-1.5.1.js'>
</script>
<script type='text/javascript' src="http://imaginationeverywhere.info/djronlove/itunes.js">
</script>
</head>
<body>
<!--<h3>Songs that currently in DJ Ron Love's Music Catalog</h3>-->
<h3>Artist that DJ Ron Love currently has in roatation</h3>
</body>
</html>
one way you may want to try is by creating a master artist array, and then querying that before adding new artists. You can do this easily using jquerys "inArray" function.
var masterArray = new Array();
$.ajax({
url: 'http://imaginationeverywhere.info/djronlove/new_2.xml',
dataType: 'xml',
success: function(xml){
$(xml).find("key:contains('Artist') + string").each(function(){
var string1 = $(this).text();
if( jQuery.inArray(string1, masterArray) == -1 ){
$('<p></p>').addClass('string1').html(string1).appendTo('#container');
masterArray.push(string1);
}
});
}
});
Note: there may be more efficent ways to do this, but if you're just looking for something simple, that may work.

Categories