When I do console.log(req.responsetext) i get [11:38:04.967] ReferenceError: req is not defined. But i define req as a new xml request on window load so I am kind of stumped. Is there a way that I should be passing a reference?
the console output is as follows
[12:29:06.839] GET getterms.php?query=DFA [HTTP/1.1 200 OK 99ms]
[12:29:06.888] SyntaxError: JSON.parse: unexpected character # search.php:21
[12:33:24.316] console.log(req.responsetext)
[12:33:24.318] ReferenceError: req is not defined
Any and all help would be most gratefully appreciated. Thank you to anyone who takes the time to read and/or answer even if you cannot help!
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8'>
<title>Auto Complete</title>
</head>
<body>
<script>
window.onload = function () {
var req = new XMLHttpRequest(); //the HTTP request which will invoke the query
var input = document.getElementById('search'); //where to grab the search from
var output = document.getElementById('results'); //where to display the sugestions
input.oninput = getSuggestions;
function getSuggestions() {
req.onreadystatechange = function () {
output.innerHTML = ""; //CLEAR the previous results!! only once the server can process new ones though
if (this.readyState == 4 && input.value != "") {
var response = JSON.parse(req.responseText);
for (var i = 0; i < response.length; i++)
addSuggestion(response[i].terms);
}
}
req.open('GET', 'getterms.php?query=' + input.value, true); //GET request to getterms.php?=
req.send(null);
}
addSuggestion = function (suggestion) {
var div = document.createElement('div');
var p = document.createElement('p');
div.classList.add('suggestion'); //suggestion[x]...
p.textContent = suggestion;
div.appendChild(p);
output.appendChild(div);
div.onclick = function() {
input.value = p.innerHTML; //set the search box
getSuggestions(); //GET new suggesions
}
}
}
</script>
<input type='text' id='search' name='search' autofocus='autofocus'>
<div id='results'></div>
</body>
</html>
edit this is my php page that echos the json.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'On');
if (!isset($_GET['query']) || empty($_GET['query']))
header('HTTP/1.0 400 Bad Request', true, 400);
else {
$db = new PDO(
my database
);
$search_query = $db->prepare("
SELECT * FROM `words` WHERE `word` LIKE :keywords LIMIT 5
");
$params = array(
':keywords' => $_GET['query'] . '%',
);
$search_query->execute($params);
$results = $search_query->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($results);
}
?>
Scope problem! Remove var in front of req to make it global and it should work
Related
I have the following PHP (Codeigniter Frameword) code:
$webpages = $this->webpageModel->select('webpageID,webpageTitle')->where('webpagecategoryID', $webpagecategoryID)->findAll();
header('Content-Type: application/json');
echo json_encode(array("response" => $webpages))
In the console, this is what is displayed:
{"response":[{"webpageID":"3","webpageTitle":"\u03a7\u03b1\u03b9\u03c1\u03b5\u03c4\u03b9\u03c3\u03bc\u03cc\u03c2 \u03b1\u03c0\u03cc \u03c4\u03bf\u03bd \u03c0\u03c1\u03cc\u03b5\u03b4\u03c1\u03bf"}]}
This is my JavaScript:
$(document).ready(function() {
let category = $('#webpagecategoryID');
let webpage = $('#webpageID');
category.on('change', function(e) {
webpage.empty();
var req = new XMLHttpRequest();
req.open("GET", "<?php echo base_url(); ?>/backEnd/Ticker/webpages_from_selected_category/" + category.val(), false);
req.send();
let res = JSON.parse(req.response);
let response = res.response;
let len = Object.keys(response).length;
for (let i = 0; i < len; i++) {
let titleLength = 150;
var trimmedTitle = response[i]['webpageTitle'].substring(0, titleLength);
webpage.append("<option value=" + response[i]['webpageID'] + ">" + trimmedTitle + "</option>");
}
});
});
In the Javascript, when I try to parse the object, I get an error: Uncaught SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 2 column 1 of the JSON data
What I am doing wrong?
My problem has not been related with the JSON at all. I use CodeIgniter 4, which in the development environment post in the console the following tag:
<script type="text/javascript" id="debugbar_loader" data-time="1611742634" src="http://ea3.test/index.php?debugbar"></script><script type="text/javascript" id="debugbar_dynamic_script"></script><style type="text/css" id="debugbar_dynamic_style"></style>
after my JSON. And after I switch the environment to production, this script tag is not displayed in the console, and my code works just fine.
I am trying to make a website that shows the weather forecast. It already shows the weather forecast. If I want to enter a city that doesn't exist I want a message to appear. I already tried something with 404 but it doesn't show up in the console log. I hope someone can help me. Thank you in advance!
function getData() {
let apikey = 'private';
var city = document.querySelector('#city').value;
let requestURL = 'https://api.openweathermap.org/data/2.5/forecast?q='+city+'&appid='+apikey+'&units=metric';
let request = new XMLHttpRequest();
request.open('GET', requestURL, true);
request.responseType = 'json';
request.send();
request.onload = function () {
let data = request.response;
addData(data);
var body = document.querySelector('body');
var div = document.createElement('div');
for (var i = 0; i < data.list.length; i += 8) {
// console.log(data.list[i].dt_txt);
div.appendChild( createEL('p',
'<b>Date en time: ' + data.list[i].dt_txt+'<br></b>'+
'City: ' + city+'<br>'+
'Country: ' + data.city.country + '<br>'+
'Temperature: ' +data.list[i].main.temp+'<br>'+
'Weather: ' +data.list[i].weather[0].main));
}
if (XMLHttpRequest == '404'){
console.log("Doesn't exist")
}
var body = document.querySelector('body');
body.appendChild(div);
function createEL(tag, content){
var el = document.createElement(tag);
el.innerHTML = content;
return el;
}
}
}
var button = document.querySelector('#show');
button.addEventListener("click", function (ev) {
ev.preventDefault();
getData();
},false);
function addData(jsonData) {
var city = document.querySelector('#city').value;
var input = document.querySelector('#city');
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Weather</title>
</head>
<body>
<h1>Weather</h1>
City: <input type="text" id="city" name="city" placeholder="city">
<button id="show" name="show">Show</button>
<script src="js/weather.js"></script>
</body>
</html>
XMLHttpRequest will never be equal to 404. It is the constructor function you used to created the object that made the HTTP request!
You need to examine request.status.
You need to check request.status if you are sending status code from API.
let request = new XMLHttpRequest()
console.log(request.status);
To display does not exist you can check the response data length like
if(data.list.length==0)
{
console.log("Does not exists.");
}
I have an extremely simple little JavaScript/Perl CGI example that I've used to get started with a larger project. When I run it as client.html and server.pl, it works flawlessly. However, when I change the client.html to client.tmpl, and call it from the same server.pl script using Template Toolkit, it can't seem to find jQuery functions.
I have even created a master.tmpl file, and used [% INCLUDE client.html %] inside it, and it fails. The browser console verifies that the path to jquery.js is correct, but it's like it fails to load it when it's inside a template.
The following is the HTML file that I'm essentially trying to turn into a .tmpl file (formatting messed up, first time here, sorry):
client.html
<!DOCTYPE html>
<html>
<head>
<title>AJAX Example</title>
<meta charset="UTF-8" />
<script src="http://domainname/ajax_example/jquery.js"></script>
<script type="text/javascript">
function myTimer() {
var typingTimer;
var doneTypingInterval = 2000;
$("#user_text").keyup( function() {
clearTimeout(typingTimer);
if ( $('#user_text' ).val()) {
typingTimer = setTimeout(updateText, doneTypingInterval);
}
});
function updateText() {
var current_text = document.getElementById('user_text').value;
var http = new XMLHttpRequest();
http.onreadystatechange = function() {
if ( http.readyState == 4 && http.status == 200 ) {
var response = http.responseText;
document.getElementById('server_response').value = response;
}
};
http.open("GET", "http://domainname/ajax_example/cgi-bin/server.pl?user_text=" + current_text , true );
http.send();
}
}
</script>
</head>
<body>
<div>Input Text: <input type="text" id="user_text" name="user_text" onkeyup="myTimer()"/></div><br/>
<div>Server Resp.: <textarea id="server_response" name="server_response"> </textarea></div>
<br/>
</body>
</html>
The server.pl that works:
server.pl
$cgi = CGI->new;
$id = $cgi->param('user_text');
$result = uc($id);
print $cgi->header();
print $result;
The server.pl that doesn't work:
server.pl
$cgi = CGI->new;
$id = $cgi->param('user_text');
**returned from result calculation sub** $result = uc($id);
my $config = {
EVAL_PERL => 1,
POST_CHOMP => 1,
INTERPOLATE => 1,
INCLUDE_PATH => '/usr/lib/cgi-bin/ajax_example/:/var/www/html/ajax_example/',
};
print $cgi->header( -charset=>'utf-8' );
my $tt = Template->new($config);
$tt->process('client.tmpl', \$result);
}
Keep in mind, I am trying my best to summarize the code, but the Perl and JavaScript work just fine, unless it's being used through TT. The error is:
#user_text.keyup is not a function:
("#user_text").keyup(function(){
Same error I would get if I put in a bad path to jquery.js. The path is good though, without a doubt.
Thank you for any recommendations anyone can provide.
The immediate problem is that you have enabled the INTERPOLATE option, which interpolates Perl variables anywhere in the template. That makes the module attempt to replace $( by its value, and destroys the JavaScript syntax
It's a sloppy way of using templates anyway: you should pass all the values you need in the $vars hash, and extract them from there using [% variable %] template directives. The same applies to the EVAL_PERL option, as any complex data manipulation should ordinarily be in the code that calls process. Everything you need to do inside the template is available as a Template directive
Talking of the $vars hash, you should be getting Not a HASH reference errors, because you are passing to process a reference to the string variable $result instead of a hash containing that value. It's unclear how you want that value to be handled, but the only mention of id in your HTML is the id attribute of the <input> element at the bottom of the HTML, so I've put a directive in their to show you how it all works
Take a look at this code
CGI program
use strict;
use warnings 'all';
use CGI;
use Template;
my $cgi = CGI->new;
my $id = $cgi->param('user_text') // 'abc123';
my $result = uc $id;
print $cgi->header( -charset => 'utf-8' );
my $tt = Template->new( {
# INCLUDE_PATH => '/usr/lib/cgi-bin/ajax_example/:/var/www/html/ajax_example/',
POST_CHOMP => 1,
} );
$tt->process('client.html', { result => $result } );
I have modified your HTML file like this. I couldn't tell what you wanted to do with the value that the CGI code pulls from the user_text parameter, so I put it into a value attribute for the first input field
Template file
<!DOCTYPE html>
<html>
<head>
<title>AJAX Example</title>
<meta charset="UTF-8" />
<script src="http://domainname/ajax_example/jquery.js" />
<script type="text/javascript">
function myTimer() {
var typingTimer;
var doneTypingInterval = 2000;
$("#user_text").keyup( function() {
clearTimeout(typingTimer);
if ( $('#user_text' ).val() ) {
typingTimer = setTimeout(updateText, doneTypingInterval);
}
} );
function updateText() {
var current_text = document.getElementById('user_text').value;
var http = new XMLHttpRequest();
http.onreadystatechange = function() {
if ( http.readyState == 4 && http.status == 200 ) {
var response = http.responseText;
document.getElementById('server_response').value = response;
}
};
http.open("GET",
"http://domainname/ajax_example/cgi-bin/server.pl?user_text=" + current_text,
true );
http.send();
}
}
</script>
</head>
<body>
<div>Input Text:
<input type="text" id="user_text" name="user_text" value="[% result %]" onkeyup="myTimer()"/>
</div>
<br/>
<div>Server Resp.:
<textarea id="server_response" name="server_response"/>
</div>
<br/>
</body>
</html>
And here's the resulting output from the CGI code. As you can see, the $("#user_text").keyup call remains intact, and the value from the CGI code—the result element passed in the $vars hash—has been substituted into the value attribute of the text input element
I hope this helps you to progress and get your application working
output
Content-Type: text/html; charset=utf-8
<!DOCTYPE html>
<html>
<head>
<title>AJAX Example</title>
<meta charset="UTF-8" />
<script src="http://domainname/ajax_example/jquery.js" />
<script type="text/javascript">
function myTimer() {
var typingTimer;
var doneTypingInterval = 2000;
$("#user_text").keyup( function() {
clearTimeout(typingTimer);
if ( $('#user_text' ).val() ) {
typingTimer = setTimeout(updateText, doneTypingInterval);
}
} );
function updateText() {
var current_text = document.getElementById('user_text').value;
var http = new XMLHttpRequest();
http.onreadystatechange = function() {
if ( http.readyState == 4 && http.status == 200 ) {
var response = http.responseText;
document.getElementById('server_response').value = response;
}
};
http.open("GET",
"http://domainname/ajax_example/cgi-bin/server.pl?user_text=" + current_text,
true );
http.send();
}
}
</script>
</head>
<body>
<div>Input Text:
<input type="text" id="user_text" name="user_text" value="ABC123" onkeyup="myTimer()"/>
</div>
<br/>
<div>Server Resp.:
<textarea id="server_response" name="server_response"/>
</div>
<br/>
</body>
</html>
So I am trying to make a simple autocomplete form but keep getting a error when I try to test the program.
When I try to test the program my console spits out [11:25:26.267] SyntaxError: JSON.parse: unexpected character # /search.php:22 which is this line. I am pretty sure my syntax is fine but I could be mistaken. Any and all help would be most gratefully appreciated. Thank you to anyone who takes the time to read and/or answer even if you cannot help!
for (var i = 0; i < response.length; i++)
My Full code is as follows.
Edit: Now with page that echos the json. When I do console.log(req.responsetext) i get [11:38:04.967] ReferenceError: req is not defined. But i define req as a new xml request on window load so I am kind of stumped.
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8'>
<title>Auto Complete</title>
</head>
<body>
<script>
window.onload = function () {
var req = new XMLHttpRequest(); //the HTTP request which will invoke the query
var input = document.getElementById('search'); //where to grab the search from
var output = document.getElementById('results'); //where to display the sugestions
input.oninput = getSuggestions;
function getSuggestions() {
req.onreadystatechange = function () {
output.innerHTML = ""; //CLEAR the previous results!! only once the server can process new ones though
if (this.readyState == 4 && input.value != "") {
var response = JSON.parse('(' + req.responseText + ')');
for (var i = 0; i < response.length; i++)
addSuggestion(response[i].terms);
}
}
req.open('GET', 'getterms.php?query=' + input.value, true); //GET request to getterms.php?=
req.send(null);
}
addSuggestion = function (suggestion) {
var div = document.createElement('div');
var p = document.createElement('p');
div.classList.add('suggestion'); //suggestion[x]...
p.textContent = suggestion;
div.appendChild(p);
output.appendChild(div);
div.onclick = function() {
input.value = p.innerHTML; //set the search box
getSuggestions(); //GET new suggesions
}
}
}
</script>
<input type='text' id='search' name='search' autofocus='autofocus'>
<div id='results'></div>
</body>
</html>
edit this is my php page that echos the json.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'On');
if (!isset($_GET['query']) || empty($_GET['query']))
header('HTTP/1.0 400 Bad Request', true, 400);
else {
$db = new PDO(
my database
);
$search_query = $db->prepare("
SELECT * FROM `words` WHERE `word` LIKE :keywords LIMIT 5
");
$params = array(
':keywords' => $_GET['query'] . '%',
);
$search_query->execute($params);
$results = $search_query->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($results);
}
?>
Get rid of the ( and ) in the JSON.parse!
JSON.parse('(' + req.responseText + ')')
should be
JSON.parse( req.responseText );
hopefully the responseText is valid JSON
I currently have some script on my page that parses title/artist information from my online radio station. I am displaying it as plain text in html by using
<span id="song_title"></span>
How can I take this dynamic information that is going into the span id and use it for a "post to twitter" link so listeners can share the current song title on Twitter?
I did some research and found a few variations on posting to twitter, but I had no luck with posting this dynamic text.
Here's the script code:
<!-- Begin Now Playing Script -->
<script>
(function () {
// we need a JSON parser, if it does not exist, load it
if (typeof JSON == "undefined") {
var s = document.createElement("script");
// json2.js retrieved from https://github.com/douglascrockford/JSON-js
s.src = "json2.js";
document.getElementsByTagName("head").appendChild(s);
}
})();
var song_ends = 0;
function update_song () {
if ((new Date).getTime() < song_ends) {
// use cached result as the song has not ended yet
return;
}
var req = new XMLHttpRequest();
// IE compatbility:
var textContent = 'textContent' in document ? 'textContent' : 'innerText';
req.onreadystatechange = function () {
if (req.readyState == 4) {
var song = JSON.parse(req.responseText);
if (song.title) {
var img = document.getElementById("song_image");
if(song.image.src){
img.alt = song.image.alt;
img.src = song.image.src;
img.width = 100;
img.height = 100;
}else{
img.src="images/default_art.png";
img.width = 100;
img.height = 100;
}
document.getElementById("song_title")[textContent] = song.title ;
document.getElementById("song_artist")[textContent] = song.artist;
document.getElementById("song_next")[textContent] = song.next ;
// store the end date in javascript date format
song_ends = (new Date).getTime() + song.wait_ms;
}
}
};
req.open('get', 'php/PlayingNow.php', true);
req.send(null);
}
// poll for changes every 20 seconds
setInterval(update_song, 20000);
// and update the song information
update_song();
</script>
<!-- End Now Playing Script -->
I want to be able to post it to Twitter like this: Currently listening to (song_title) by (song_artist)
Here is the code for the PHP file referenced in the script above:
<?php // filename: PlayingNow.php
$json = null;
$cache = 'song.json';
// if there is no usuable cache
if (!$json) {
// retrieve the contents of the URL
$ch = curl_init('http://bigcountry.streamon.fm/card');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$res = curl_exec($ch);
curl_close($ch);
$json = json_decode($res);
// if the title exists, assume the result to be valid
if ($json && $json->title) {
// cache it
$fp = fopen('song.json', 'w');
fwrite($fp, $res);
fclose($fp);
} else {
$json = null;
}
}
if ($json) {
$info = array();
// contains the time in milliseconds
$info['wait_ms'] = $json->interval->ends_at - 1000 * microtime(true);
$info['title'] = $json->title ;
$info['artist'] = $json->artist;
$info['album'] = $json->album ;
$info['next'] = $json->next_song;
$info['image'] = $json->album_art;
// display a JSON response for the HTML page
echo json_encode($info);
}
?>
The "right" way to do this is to use Twitter's Web Intents, which is designed specifically for this scenario. Take a look at the "Tweet or Reply to a Tweet" section. In practice you'll just include the Web Intents script (http://platform.twitter.com/widgets.js) on your page, create a link, and set its href, e.g.:
var link = document.createElement('a');
link.innerHTML = "Link Text";
link.href = 'http://twitter.com/intent/tweet?text=Currently listening to "' + songTitle + '" by ' + songArtist;
var parentElement = document.getElementById('SOME_ELEMENTS_ID');
parentElement.appendChild(link);
You can add the url parameter if you also want the tweet to include your site's URL.