I am writing a script that sends an ajax request. The Cloud seems to response with the JSON, but how can I display the data from the JSON on my webpage?
Here the link for the pretty printed JSON.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<button onclick="myFunctionPost()">Start</button>
<script>
function myFunctionPost() {
jQuery.ajax( {
url: 'https://iotmmss0018275632trial.hanatrial.ondemand.com/com.sap.iotservices.mms/v1/api/http/app.svc/T_IOT_77877E443B666B7FED2F?$format=json',
type: 'POST',
crossDomain: true,
dataType: 'jsonp',
success: function( response ) {
console.log(response);
},
error : function(error) {
console.log(error);
}
} );
}
</script>
</body>
</html>
To achieve this you can use JSON.stringify() space argument. You will also need to wrap the output with <pre> </pre> will preserve the line spacing.
function myFunctionPost() {
$.ajax( {
url: 'https://jsonplaceholder.typicode.com/posts',
type: 'GET',
success: function(response) {
$('#pp').html('<pre>' + JSON.stringify(response, undefined, 4) + '</pre>');
},
error: function(error) {
console.log(error);
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<button onclick="myFunctionPost()">Start</button>
<p id="pp"></p>
</body>
</html>
Source: Does jQuery have a JSON/javascript object to HTML pretty print function similar to PHP's var_dump?
By var responseObject = json.parse(response) to make a javascript object.
And then do as you would with JS object?
Hard to tell exact code without knowing what do you wanna display, in what HTML.
Related
I'm creating a PHP application where I have to send a JavaScript variable to the same page and then use it in PHP. However when I run my code the output shows and is correct but it goes away and dissappears.
$.ajax({
type: 'POST',
url: 'ajax.php',
data: { id: 1},
success: function(result) {
$('body').html(result);
console.log(result);
},
error: function() {
alert('Some error happened. Please try again!');
}
});
I accessed the posted variable via PHP post variable and the output is correct but I cant get it to stay on the screen. Is the innerHTML of my ajax.php being overwritten?
The console shows correct output also !
Are you doing something else with your html <body> element? If I were you, I'd make a new element in the body and put your results there.
$.ajax({
type: 'POST',
url: 'ajax.php',
data: { id: 1},
success: function(result) {
$('#results').html(result);
console.log(result);
},
error: function() {
alert('Some error found. Please try again!');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<head>
<title>Title</title>
</head>
<body>
<div id="results"></div>
</body>
</html>
You are calling body attributes, try changing this line:
$('body').html(result);
To;
$("#myResult").html(result);
You can now print your response by adding this to your HTML code:
<div id="myResult"></div>
If you want to select via a Class instead:
$(".myResult").html(result);
Here, the ID selector # is replaced by the Class selector . so your div will now become:
<div class="myResult"></div>
Now try this:
$.ajax({
type: 'POST',
url: 'ajax.php',
data: {id: 1},
success: function(result) {
// $('body').html(result);
// $(".myResult").html(result);
$("#myResult").html(result);
console.log(result);
},
error: function() {
alert('Some error found. Please try again!');
}
});
On the HTML side enter this:
<div class="myResult"></div>
Hey guys I am new with this json syntax and I have one problem.
I made function that gets data from remote server in json like this:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery-3.1.0.min.js"></script>
<script type="text/javascript">
function getStates(value) {
var data = {
q: value
}
$.ajax({
url: 'https://something.hr/api/search',
method: 'GET',
headers: {'Accept': 'application/json'},
data: data
}).done(function(data) {
//do something with data I returned to you
console.log("success")
console.log(data)
}).fail(function(data) {
//doSomethingWith the data I returned to you
console.log("fail")
console.log(data)
});
};
</script>
</head>
<body>
<input type="text" onkeyup="getStates(this.value)" >
<br>
<script>
</script>
</body>
</html>
My problem is that I know how to get object in console log, but i wish to get that object in html, like in some box, than click on it and open his data(name, id, adress etc.)
var httpManager = (function() {
var getData = function(value) {
$.ajax({
url: 'https://api.github.com/users/zixxtrth',
method: 'GET'
}).done(function(data) {
//do something with data I returned to you
jQuery('#avatar').attr('src', data.avatar_url);
jQuery('#name').html(data.name);
jQuery('#username').html(data.login);
}).fail(function(data) {
//doSomethingWith the data I returned to you
alert('No Data');
});
};
return {
getData: getData()
}
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<img src='' id='avatar' width='200' height='200' />
<h1 id='name'></h1>
<h2 id='username'></h2>
I'm looking to be able to implement the Emotion API from Project Oxford on my website. I've currently written the below HTML/JavaScript code which checks an image from a URL and displays the result of said image after having run the Emotion API:
<head>
<title>JSSample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<body>
<script type="text/javascript">
$(function() {
$.ajax({
url: "https://api.projectoxford.ai/emotion/v1.0/recognize",
beforeSend: function(xhrObj) {
// Request headers
xhrObj.setRequestHeader("Content-Type", "application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key", "my-key");
},
type: "POST",
// Request body
data: '{"url": "https://philosophybank.files.wordpress.com/2013/08/happy-people.jpg"}',
})
.done(function(data) {
JSON.stringify(data);
alert(JSON.stringify(data));
//console.log(data);
//alert(data.scores);
})
.fail(function(error) {
console.log(error.getAllResponseHeaders());
alert("fail");
});
});
</script>
This code works fine, however I'm looking to implement this on my website such that people upload images themselves locally from their machine with the use of a browse button as opposed to looking up an image using the link. Any help would be very much appreciated!
I mocked this up using application/octet-stream as the body type which allows you to post a binary object (i.e. the image itself), rather than a url to an image. The Emotion API documentation details how this is a supported content type.
I've continued with use of JQuery as per your original example.
You should be able to copy and paste this entire example into a HTML file, add your Emotion API key where it says my-key and it will work
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<input type="file" id="file" name="filename">
<button id="btn">Click here</button>
<script type="text/javascript">
$('#btn').click(function () {
var file = document.getElementById('file').files[0];
$.ajax({
url: "https://api.projectoxford.ai/emotion/v1.0/recognize",
beforeSend: function(xhrObj) {
// Request headers
xhrObj.setRequestHeader("Content-Type", "application/octet-stream");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key", "my-key");
},
type: "POST",
data: file,
processData: false
})
.done(function(data) {
JSON.stringify(data);
alert(JSON.stringify(data));
})
.fail(function(error) {
alert(error.getAllResponseHeaders());
});
});
</script>
</body>
</html>
I am trying to try the microsoft emotion api. I am running a simple python web server with CORS enabled. Below is my server python file with which I start the server:
python-server.py
#! /usr/bin/env python2
from SimpleHTTPServer import SimpleHTTPRequestHandler
import BaseHTTPServer
class CORSRequestHandler (SimpleHTTPRequestHandler):
def end_headers (self):
self.send_header('Access-Control-Allow-Origin', '*')
SimpleHTTPRequestHandler.end_headers(self)
if __name__ == '__main__':
BaseHTTPServer.test(CORSRequestHandler, BaseHTTPServer.HTTPServer)
I have an index.html file in which I am sending the http request:
index.html
<!DOCTYPE html>
<html>
<head>
<title>JSSample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(function() {
$.ajax({
url: "https://api.projectoxford.ai/emotion/v1.0/recognize",
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key",JSON.stringify({"my-key"}));
},
type: "POST",
// Request body
data: JSON.stringify({"url": "http://tinyurl.com/2g9mqh"}),
})
.done(function(data) {
alert("success");
})
.fail(function() {
alert("error");
});
});
</script>
</body>
</html>
After about 30 seconds I get the connection refused response. The http request code was taken from the emotion api's page I linked earlier. I wonder whether I need a real server or is there a mistake in the code? Thanks.
The JSON needs to be sent out as a string. So change your body specification to:
data: "{\"url\": \"http://...\"}"
Please use the code below(replace your-key), just save it as a .html and open it in the browser it shut work(without any server). If it works then try it in your python server.
<!DOCTYPE html>
<html>
<head>
<title>JSSample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(function() {
$.ajax({
url: "https://api.projectoxford.ai/emotion/v1.0/recognize",
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","your-key");
},
type: "POST",
// Request body
data: {"url": "https://oxfordportal.blob.core.windows.net/emotion/recognition1.jpg"},
})
.done(function(data) {
alert("success");
})
.fail(function() {
alert("error");
});
});
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Face API</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(function() {
$.ajax({
url: "https://api.projectoxford.ai/emotion/v1.0/recognize",
beforeSend: function(xhrObj) {
// Request headers
xhrObj.setRequestHeader("Content-Type", "application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key",
"");
},
type: "POST",
// Request body
data: JSON.stringify({
"url": "http://i1.mirror.co.uk/incoming/article6395000.ece/ALTERNATES/s1200/MAIN-David-Beckham-next-James-Bond.jpg"
}),
})
.done(function(data) {
console.log(data);
})
.fail(function(e) {
console.log(e);
});
});
</script>
</body>
</html>
I try AJAX and JSON.
I have got this very simple scripts. Could you help me to get it work?
html file
<div class="esemeny">
<h2>Event</h2>
<p></p>
<button>click</button>
</div>
json file, I call it eventresult.json
{name: whatever,
}
and the javascript file
$(function(){
$('button').on('click', function(){
$.ajax('/javascript/eventresult.json', {
dataType: 'json',
success: function(result){
var esemeny = $('.esemeny');
esemeny.find('p').html(result.name);
}
});
});
});
Thank you
You didn't tell what did want to do exactly, anyway I think, this what you want to do:
JSON:
{
name: "whatever"
}
JS:
$(function(){
$('button').on('click', function(){
$.ajax('/javascript/eventresult.json', {
dataType: 'json',
type: 'GET' // you want to get content
success: function(result){
var esemeny = $('.esemeny');
esemeny.find('p').html(result.name);
}
});
});
});
Hope that helps a bit
I guess your JSON should look like
{
name: "whatever"
}
Mind the double quotes and the unnecessary comma.
Well,you actually didn't descripte the question clearly.You can have a debug that can be seen from your firebug console,like this:
$.ajax('/javascript/eventresult.json', {
dataType: 'json',
success: function(result){
var esemeny = $('.esemeny');
esemeny.find('p').html(result.name);
}
}).fail(function(jqXHR, textStatus, errorThrown){console.log(textStatus+':'+ errorThrown)})
Here are some suggestions that should make it work:
Make sure you include the necessary script files in your html file:
<head>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js'></script>
</head>
<div class="esemeny">
<h2>Event</h2>
<p></p>
<button>click</button>
</div>
<script src="javascript.js"></script>
Make sure you use valid json in the json file
{
"name": "whatever"
}
Use .click() function in your javascript:
$(function() {
$('button').click(function() {
$.ajax('/trials/eventresult.json', {
dataType: 'json',
success: function(result) {
var esemeny = $('.esemeny');
esemeny.find('p').html(result.name);
}
});
});
});