I have an java application running, with a REST #POST endpoint, which takes an SQL query, and returns the result in a csv format.
The endpoint works, I can get the correct results via Curl and Postman.
Now, I am trying to call this endpoint via javascript, and to update a HTML value with the response. But have no experience with js.
This is the code I am using:
<!DOCTYPE html>
<html>
<body>
<h1>Making A POST</h1>
<p id="demo">Change this text.</p>
<button type="button" onclick="loadDoc()">Change Content</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function loadDoc() {
$.post("http://localhost:4567/query/sql/csv",
"SELECT * FROM testTable",
function(data,status){
document.getElementById("demo").innerHTML = $result;
});
}
</script>
</body>
</html>
It is successfully making the POST request, can see from the application console. But it is not changing the HTML element with the response:
<p id="demo">Change this text.</p>
As I see, you're using a var that is undefined: $result
I think you wanted to use data instead.
Like this: document.getElementById("demo").innerHTML = data;
Code works.
The issue was Chrome and Internet Explorer blocking the script.
Related
So I'm trying to make a problem for a ctf, and for a problem, I need to send data from a python script to the javascript. Can anyone tell me how?
Thanks!
My html code is:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1 class="text">text</h1>
<script>
$.get("http://[website]/cgi-bin/challenge.py",
function(data) {
$(".text").html(data);
});
</script>
</body>
</html>
I replaced the website name with [website]
The python code is like this:
#!/usr/bin/python
import json
print "Content-type: text/html\n\n"
text = "It works!"
json.dumps(text)
Edit:
I expected the python file to return "It works!", however after going into the network tab to see the result, it returned nothing. The text in the h1 also disappeared.
This is an image from the network tab:
https://i.stack.imgur.com/8JSMO.png
You missing print() and content-type application/json because json.dumps() will not print output or set header to JSON.
#!/usr/bin/python
import json
text = json.dumps("It works!")
print "Content-Type: application/json\n"
print(text)
I had a node js application where I have my app.js and one html which gets displayed for the route /index.Now In my index file I had a button and text box and when I click button Iam trying to call a function.Where in that function I will have a variable with some text "Hello" which should be displayed in text box.I couldnt achieve this can some one help.
<html>
<body>
<div class="jumbotron" style="padding:40px;">
<h1>Hello!!!</h1>
<div>
<button type="submit" onclick="getData();">Call</button>
<input type="text">
</div>
</div>
</div>
</body>
</html>
app.js
app.get('/index',function(req,res){
res.sendFile(path.join(__dirname+'/index.html'));
});
function getData(){
console.log("Hello");
var text="Hello";
};
Right now Im getting reference error that getData is not defined.Can someone help over here.
I think you may have misunderstood what NodeJS is. Node isn't like other JavaScript or jQuery that runs in the browser.
Node is code that runs on the server. What you've correctly done in your app.js is have the server send the index.html file to the browser. But after that point all that the browser knows about and has access to is the index.html file, it is a separate file and context and so has no access to the server anymore.
The only way to have your page call a function on the server would be to create some sort of API where your page sends a separate http request to the server, which then responds with the function's output.
index.html runs in browser so you can't call getData() function that is defined on server side in app.js
Move getData() function body to index.html as Nenad Vracar suggests or use some kind of API for client-server communication.
code moved to index.html
<html>
<body>
<script>
function getData() {
var text="Hello";
document.querySelector('#input_id').value = text;
}
</script>
<div class="jumbotron" style="padding:40px;">
<h1>Hello!!!</h1>
<div>
<button type="submit" onclick="getData();">Call</button>
<input type="text" id="input_id">
</div>
</div>
</div>
</body>
</html>
I have made an Ajax call to Bing to get its daily image, however i get an error in the console:
this is the full code its on a localhost using wamp
index.php
<head>
<script src="jquery.min.js"></script>
</head>
<body>
<div id="output"></div>
</body>
<script type="text/javascript">
$.ajax({
url : "http://bing.com/HPImageArchive.aspx?format=js&idx=0&n=1",
dataType:"jsonp",
});
function mycallback(data)
{
$('#output').html(data.images[0].url);
}
</script>
I think you should study the documention for jquery ajax call.
<head>
<script src="jquery.min.js"></script>
</head>
<body>
<div id="output"></div>
</body>
<script type="text/javascript">
(function() {
var bingImagesUrl = "http://bing.com/HPImageArchive.aspx";
$.getJSON( bingImagesUrl, {
idx:0,
n:1,
format: "js"
}).done(function( data ) {
$('#output').html(data.images[0].url);
});
})();
</script>
#Below_the_Radar: your answer does not really help as OP is likely getting the same error even if he makes the Ajax call correctly.
According to Is there a way to get Bing's photo of the day?, it seems that Bing.com only supports XML, JSON, and RSS. I guess OP want to make the call with dataType: "jsonp" probably because he would like to bypass the browsers same-origin policy.
This can be solved client-side in browser by using a Chrome extension, but I guess that is not OP's use case. I bet OP is trying to get a picture from Bing's archive and thus use it in his own website. If that is the case, it has no solution as we need to have "Access-Control-Allow-Origin": "*" in the response's headers returned by Bing, which we do not have control.
I suggest considering an alternative. Try this: https://source.unsplash.com/
I am having difficulty with a specific JQuery $.post call to a PHP-based processor. I created a test page with the code below located here: http://goo.gl/Bg7H2u
Note this is located on a subdomain, but we are not doing cross-domain posting. Everything should be included on the subdomain.
There do not seem to be any JS errors as reported in the error console.
The processor /get-data.html is the general purpose PHP processor, and, if you load the processor page with the right value, it returns a dataset from the MySQL database in JSON format. We have this working on the main domain without issue, and other $.post calls seem to work OK from this subdomain (not to this /get-data.html processor, but other processors that process form content).
See the actual processor output here: http://goo.gl/yOzrm2
I must be missing something obvious, but I am coming up empty. Thoughts?
Here is the code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=320px, initial-scale=1">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
var prices;
$(document).ready(function(){
$.post( "/get-data.html", { table: 'prices' },
function( data ) {
prices = data;
alert(prices);
}, 'json');
});
</script>
</head>
<body>
<div style="overflow-x: hidden;" id="divMain">
</div>
</body>
</html>
Thanks for any advice you can provide.
If you do View Source on the processor output, you'll see that your script is returning:
<p>{"Basic Plan":["349"],"Basic":["349"],"Premium Plan":["549"],"Premium":["549"],"Standard Plan":["429"],"Standard":["429"],"Bonus Plan":["175"],"Additional Central AC System":["99"],"Additional central heating system":["99"],"Central Vacuum":["99"],"Whole home humidifier":["49"],"Pool (in-ground)":["179"],"Spa (in-ground)":["179"],"Septic System":["99"],"Sump Pump":["99"],"Well pump":["99"],"Whole home water softener":["99"],"Lawn sprinkler system (in-ground)":["99"],"Wine refrigerator":["49"],"Ice maker (free standing)":["49"],"Home phone (unlimited)":["49"],"TV Protection (Flat screen up to 60 inches)":["99"],"PC Protection (laptop or desktop)":["49"]}</p>
There's <p> at the beginning and </p> at the end. This is not valid JSON. You need to fix the server script so that it doesn't print anything other than the JSON (whitespace is OK, that's it).
1.confirm that /get-data.html is the correct relational url for your file location.
If you navigate directly to the /get-data.html, does it produce the results that you are after.
try running the same code without , 'json' and see if it works.
hope this helps
Here is my code:
<!DOCTYPE html>
<html lang="en" >
<head>
<script type="text/javascript">
function showResponse(response){
var responseString = JSON.stringify(response, '', 2);
document.getElementById('response').innerHTML += responseString;
}
function onClientLoad(){
gapi.client.load('youtube','v3', onYouTubeApiLoad);
}
function onYouTubeApiLoad(){
gapi.client.setApiKey('MyActualKey');
search();
}
function search(){
var request = gapi.client.youtube.search.list({
part: 'snippet'
});
request.execute(onSearchResponse);
}
function onSearchResponse(response){
showResponse(response);
}
</script>
<title></title>
<script src="https://apis.google.com/js/client.js?onload=onClientLoad"></script>
</head>
<body>
<div id="response"></div>
</body>
</html>
This code is from Codecademy, and I thought I can use it on an html page and it would work.
I got an API key from google and I set my Youtube data api v3 setting to enabled in my google developers console, but this code gives me a blank page.
What am I doing wrong?
There are a few missing pieces, code snippets which codecademy likely took for granted but which are essential when placing it in your own server outside of their app. First of all, you need a line that actually loads the gapi library from google. You can put this in your code, just before the closing :
<script src="https://apis.google.com/js/client.js?onload=onClientLoad"></script>
In short, this will get the library from Google's servers, and when it's loaded the library will automatically call your onClientLoad method, kicking off your app.
Next, you say you have an API key; make sure you put that key into your code by replacing this:
gapi.client.setApiKey('MyKey');
with this:
gapi.client.setApiKey('{WHATEVER_YOUR_ACTUAL_KEY IS');
Finally, as the commenters mentioned, your body is empty, so when your code executes the showResponse method there's no place to put what comes back. Add this:
<div id="response"></div>