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);
}
});
});
Related
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.
I have a web page that's showing a "ressource" (aka just one entry from a mongodb collection), and on that web page I want to have a button "delete" that will send a "delete" request to the server to the correct route.
The router works (so when I use an external program to send a delete request, the entry is deleted), but I want to the same with a link.
Apparently, after doing some research, I would need to use an ajax function to do that, as in this post. The problem is that I can't make it work (probably because I just started using jquery), it seems nothing happens when I click on the button. But if I try a simple alert(), it works ('#delete').on('click',function(){ alert('clicked')}); .
So
Here's the basic html :
$('#delete').on('click', function() {
alert('click');
//here would be the code to send the DELETE request ?
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<title>Storystrap Template</title>
<meta name="generator" content="Bootply" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<!-- bower:css -->
<link rel="stylesheet" href="/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css" />
<!--endbower-->
<!-- bower:js -->
<script src="/lib/jquery/dist/jquery.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="/lib/bootstrap/dist/js/bootstrap.js"></script>
<script src="/js/printplugin.min.js"></script>
<!--inject:js-->
<script src="/js/app.js"></script>
<script src="/js/modernizr-custom-touch.js"></script>
</head>
<body>
<button class="delete" data-target="/" data-method="DELETE" data-disabled="true">Delete Ressource</button>
</body>
</html>
And here is the route code in node.js (this code works if I manually send a DELETE request), the id is supposed to be in the link of the page
ressourcesRouter.route('/ressources/t/:ressourcesId')
// permet d'afficher UNE ressource spécifique
.get(function(req,res){
var returnRessource = req.ressource.toJSON();
res.render('ressourceView', {
title: 'Ressources',
ressource: returnRessource
});
})
.delete(function(req,res){
req.ressource.remove(function(err){
if(err)
res.status(500).send(err);
else{
res.status(204).send('Removed');
console.log('ressource supprimée');
}
});
});
Could you help me out to figure the ajax code needed ? or is there another way ?
Don't hesitate to ask for more code if needed, I'll be as reactive as possible to answer you quickly.
Best regards.
Take a look at the jQuery ajax docs: http://api.jquery.com/jquery.ajax/
$.ajax({
url: '/ressources/t/123',
method: 'DELETE',
data: yourdata
})
.done(function( data ) {
console.log(data);
});
<script type="text/javascript">
$(document).ready(function(){
$('table#delTable td a.delete_link').click(function()
{
if (confirm("Are you sure you want to delete this row?"))
{
var id = $(this).parent().parent().attr('id');
var data = 'id=' + id ;
var parent = $(this).parent().parent();
$.ajax(
{
type: "POST",
url: '../scripts/delete_link.php',
data: 'link=' + $(this).attr('data_link') + '&topic_pk=' + $(this).attr('data_topic') + '&topic_introduction=' + $(this).attr('data_introduction'),
cache: false,
success: function()
{
parent.fadeOut('fast', function() {$(this).remove();});
}
});
}
});
});
</script> just look at this. it can solution your problem. Dont Forget your datatable's name
Today I have a question that may seem kinda simple the the rest of you. I'm just now learning how to use APIs/JSONs and I'm a little confused. I'm trying to simply grab the temperature from this openweathermap.org API response and displaying it in an html tag.
The javascript from what I know is grabbing the temperature and setting it as a var. I'm confused why I cannot use id="" to set text inside a tag. The code below is what I have so far. I thank you for your time.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script type="text/javascript">
var weather;
var temp;
$(document).ready(function() {
$.ajax({
url: "http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=44db6a862fba0b067b1930da0d769e98&units=metric",
dataType: 'jsonp',
success: function(weather){
var temp = weather.main.temp;
}
});
</script>
</head>
<body>
<p id="temp"></p>
</body>
</html>
#ArunPJohny have already identified the errors: 1) missing }) and 2) use $('#temp') to get the HTML element. Also you don't need to declare weather because it is declared as an argument.
$(document).ready(function() {
$.ajax({
url: "http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=44db6a862fba0b067b1930da0d769e98&units=metric",
dataType: 'jsonp',
success: function(weather) {
$('#temp').text(weather.main.temp);
}
});
});
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<p id="temp"></p>
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>
http://te.chni.ca/twitter.api/tweet.php
I tried all tutorials but unable to get the data from that please help me
try to get atleast one attribute so i can try the remaining ones
<!DOCTYPE html>
<html>
<head>
<title>Twitter</title>
</head>
<body>
<button id="initquery">Search</button>
<script src="http://code.jquery.com/jquery.js"></script>
<script>
$(function(){
$('#initquery').click(function(){
$.getJSON('http://te.chni.ca/twitter.api/tweet.php',function(data){
var item=[];
$.each(data,function(key,val){
items.push('<li id="'+key+'">'+val+'</li>');
});
$('<ul/>',{
'class':'interests-list',
html:items.join('')
}).appendTo('body');
});
});
});
</script>
</body>
</html>
You need to be using jsonp. Do you see the parenthesis around the response from that API? That is tell-tale sign that this is intended to be jsonp.
You should use ajax() method for this:
$ajax(
url: 'http://te.chni.ca/twitter.api/tweet.php',
dataType: 'jsonp',
success: function(data) {
// your success function
}
);