Display ajax in html page - html

I'm using flask as a backend, and one of my endpoints is objectList, which returns data in this format:
[{name1:value1, name2:value2}, {name1:value3, name2:value4}]
In order to display this data on my html page, I'm using the following code:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function){
$.ajax({
url: 'localhost:5000/objectList',
method:"GET",
success: function(result){
$("#div1").html(result);
};
});
};
</script>
</head>
<body>
<div id="div1"></div>
</body>
</html>
This doesn't display any data. What am I doing wrong and how can I fix this?
Edit: just a clarification, I want the data to load when the page loads, not on a button or a click

After our discussion, I find this code works properly
You have to close the parenthesis in the function ajax, and allow the access-control in the server side with this line
header("Access-Control-Allow-Origin: *");
// or replace the star with the server where you have the html
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.ajax({
url: 'localhost:5000/objectList',
method:"GET",
success: function(result){
// to verifiy the result
console.log(result);
var htmlOutput = '';
// the iteration of your result because you have many entries
$.each(result, function(i, item) {
htmlOutput += ''+
'<ul>'+
'<li>name1: '+item['name1']+'</li>'+
'<li>name2: '+item['name2']+'</li>'+
'</ul>';
});
$("#div1").html(htmlOutput);
}, error: function(jqXHR, textStatus, error) {
// to verifiy either there is an error or not
console.error(textStatus);
}
});
});
</script>
</head>
<body>
<div id="div1"></div>
</body>
</html>

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.getJSON("demo_ajax_json.js", function(result){
$.each(result, function(i, field){
$("div").append(field + " ");
});
});
});
});
</script>
</head>
<body>
<button>Get JSON data</button>
<div></div>
</body>
</html>

Related

Dynamic Src in HTML in a Script Tag

I have a script:
<script src="http://192.168.0.187:3004/socket.io/socket.io.js"></script>
The IP Address is subject to change which I have no control of, so I'm thinking of having the IP dynamic.
Like this:
<script src="http://" + location.host + "/socket.io/socket.io.js"></script>
But of course this doesn't work.
I did however came across this:
<script type="text/javascript" src="">
document.getElementsByTagName("script")[0].src += "http://" + location.host + "/socket.io/socket.io.js";
</script>
But still doesn't work. This is not my strongest point so, any clue?
EDIT:
Here is the sample of my html:
<!DOCTYPE html>
<html>
<head>
<title>SAMPLE</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script id="script" src=""></script>
<script type="text/javascript">
document.getElementById("script").src = "http://" + location.host + "/socket.io/socket.io.js";
</script>
<link rel="stylesheet" href="/styles.css">
</head>
<body bgcolor="#ffffff">
<table id="table" border=1>
<thead>
<th><center>Sample</center></th>
<th></th>
</thead>
<tbody id="online"></tbody>
</table>
<script>
var ipServer = location.host;
var socket = io.connect('ws://' + ipServer);
</script>
</body>
</html>
This is call dynamically loading javascript:
var script = document.createElement('script');
script.setAttribute( 'src', 'socket.io.js');
document.head.appendChild(script);
//script that use socket.io
But there's another problem that you don't know when the script is fully loaded. If you call a function is defined in external script before it's loaded, it's error!
var script = document.createElement('script');
script.onload = function () {
//script that use socket.io
};
script.setAttribute( 'src', 'socket.io.js');
document.head.appendChild(script);
And we can make a utility function:
function loadScript(scriptPath, callback) {
var script= document.createElement('script');
script.setAttribute('src', scriptPath);
script.onload = callback();
document.head.appendChild(s);
};
loadScript('socket.io.js', function() {
//script that use socket.io
});
OR you can use jQuery $.getScript():
$.getScript('socket.io.js', function(data, textStatus, jqxhr) {
//script that use socket.io
});
For more information: https://api.jquery.com/jquery.getscript/
PS: with your code, it will be like this:
<!DOCTYPE html>
<html>
<head>
<title>SAMPLE</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script id="script" src=""></script>
<!--<script type="text/javascript">-->
<!--document.getElementById("script").src = "https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.1.1/socket.io.js";-->
<!--</script>-->
<!--<link rel="stylesheet" href="/styles.css">-->
</head>
<body bgcolor="#ffffff">
<table id="table" border=1>
<thead>
<th><center>Sample</center></th>
<th></th>
</thead>
<tbody id="online"></tbody>
</table>
<script>
var script = document.createElement('script');
script.onload = function () {
var ipServer = location.host;
var socket = io.connect('ws://' + ipServer);
};
script.setAttribute( 'src', 'https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.1.1/socket.io.js');
document.head.appendChild(script);
</script>
</body>
</html>
You can use document write to load the script.
<script type='text/javascript'>
var script = '<script type="text/javascript" src="http://' + location.host + '/socket.io/socket.io.js"><\/script>';
document.write(script);
</script>
You have the right idea; the problem is that you can't combine an external script (using src) with an inline one.
You simply need two different scripts for this, making sure the inline one comes after the reference to an external script:
<script src=""></script>
<script type="text/javascript">
document.getElementsByTagName("script")[0].src = "http://" + location.host + "/socket.io/socket.io.js";
</script>

Display JSON response array in Phonegap

very quick question
i have webservice which returns JSON array
I want to display that JSON array in phonegap app
how can i do that
so far i was trying this
but its not working
$(document).ready(function () {
$.jsonp({
url: 'getevents.php',
callbackParameter: 'callback',
success: function (data, status) {
//$('#your-tweets').append('<li>The feed loads fine');
$.each(data, function (i, item) {
var tweet = item.title;
$('#your-tweets').append('<li>' + tweet);
});
},
error: function () {
$('#your-tweets').append('<li>There was an error loading the feed');
}
});
});
And here is my index.html file
<script src="js/jquery-2.1.1.min.js" type="text/javascript"></script>
<script src="js/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript" src="js/data.js"></script>
<title>Hello World</title>
</head>
<body>
<ul id="your-tweets"></ul>
</body>
But with this code i am getting error that $.jsonp is not a function
If there are some tutorials available online than do provide me the link as well
I have tried this function as well
But somehow i cannot figure out where to pass the return array from the webservice
function readJSONData() {
$.getJSON("getevents.php",function(data){
if(data) {
var json_data;
$('#read-data').hide();
$('.demo-table').show();
$.each(data, function(i,event){
json_data = '<tr>'+
'<td valign="top">'+
'<div class="feed_title">'+event.title+'</div>'+
'<div>'+event.description+'</div>'+
'</td>'+
'</tr>';
$(json_data).appendTo('#demo-table-content');
});
} else {
json_data += '<tr>'+
'<td valign="top">No Tutorials Found</td>'+
'</tr>';
$(json_data).appendTo('#demo-table-content');
}
});
}
I can see in the firebug that on ajax request it returns the event array but on the page i get undefined instead of the data
thank you and really appreciate it
Use this prototype. And not event is an array so you have to check element in array i.e. data.event[index]
also you don't have any parameter data.event.desc so referring to that element will result undefined.
<html>
<body>
Get JSON Data
<div id="showdata"></div>
</body>
</html>
$(document).ready(function(){
//attach a jQuery live event to the button
$('#getdata-button').live('click', function(){
$.getJSON('http://dev.app.horsebuzz.com/dbconnection/getevents.php', function(data) {
//alert(data); //uncomment this for debug
//alert (data.item1+" "+data.item2+" "+data.item3); //further debug
for(var i=0;i<data.event.length;i++){
$('#showdata').html("<p>item1="+data.event[i].title+" item2="+data.event[i].start_date+" item3="+data.event[i].location+"</p>");
}
});
});
});

Passing message from one window to another window

I'm trying to pass the message from comn.html window to comm.html window, but it doesn't pass
please tell me whether the code is correct or not. If not, kindly provide the exact code for that.
I want the code for passing message between windows not between iframes.
Code of comn.html:
<html>
<head>
<script>
window.onload = function()
{
var btn = document.getElementById('send');
btn.addEventListener('click', function sendMessage(e)
{
var string="Hi Adaptavant";
var new_win=window.open('comm.html');
new_win.postMessage(string,"*");
});
}
</script>
</head>
<body>
<button id="send" >Send Message</button>
</body>
</html>
Code of comm.html:
<html>
<head>
<title>postMessage</title>
<script type=text/javascript>
window.onload = function()
{
var msg = document.getElementById('message');
window.addEventListener("message",function receiveMessage(e) {
msg.innerHTML="msg received= " +e.data;
document.write("the message is " +msg);
}
</script>
</head>
<body>
<div id="message"></div>
</body>
</html>
If I run this program, my message isn't posting in another window.
What's the problem?
replace your script with this:
window.onload = function()
{
var msg = document.getElementById('message');
window.addEventListener('message', function(e) {
var message = e.data;
msg.innerHTML="msg received= " +e.data;
});
}
Let me know if it worked!

Ajax call - Which button pressed?

<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.1.js">
</script>
<script>
$(document).ready(function(){
$("#btn1").click(function(){
txtname=$("#btn1").val();
$.ajax({url:"doSome.php",data:{name:txtname},success: function(ajaxresult){
$("#ajaxrequest").html(ajaxresult);
}});
});
});
</script>
</head>
<body>
<button id="btn1" value="myButton">Click to send1</button>
<button id="btn2" value="myButton2">Click to send2</button>
<div id="ajaxrequest"></div>
</body>
</html>
How can I recognize which button pressed in line: $("#btn1").click(function(){
without having to write again the same code for btn2?
You can use a selector on all buttons and then get back the ID when clicked
$('button').click(function()
{
alert( $(this).attr('id') ); // Button ID clicked
});
You can use
$( '#btn1' ).click(function(){
submitForm( 'btnOne' );
});
$( '#btn2' ).click(function(){
submitForm( 'btnTwo' );
});
And then pass your parameter in a single function:
function submitForm( type ){
var dataString = $('#form_confirm_delete').serialize();
dataString += "&type=" + type;
$.ajax({
type: "POST",
url: "doSome.php",
data: dataString,
dataType: 'json',
cache: false,
success: (function(response)
{
alert('Yes');
})
});
}
Actually, simply use multiple selectors:
$('#btn1, #btn2').click(function(e) {
var btn1Clicked = $(this).is('#btn1');
var btn2Clicked = $(this).is('#btn2');
});

Separate localstorages

I have 1 site under foo.com/test1/test1.html and another at foo.com/test2/test2.html
test1.html looks like this:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
document.ready = function(){
var name = localStorage.getItem("name");
if(name){
console.log("name is defined");
}else{
console.log("name is not defined");
localStorage.setItem("name", "test1");
}
$('#name').text(name);
}
</script>
</head>
<body>
<p id="name"></p>
</body>
</html>
And test2.html is like this:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
document.ready = function(){
var name = localStorage.getItem("name");
if(name){
console.log("name is defined");
}else{
console.log("name is not defined");
localStorage.setItem("name", "test2");
}
$('#name').text(name);
}
</script>
</head>
<body>
<p id="name"></p>
</body>
</html>
My question is that is it possible to achieve that that if I go to test1, the value of name is "test1" and if I go to test2 the name will be test2. Basically I suspect that I need to name them differently but I rather not do that. Is there any good work around for this?
Thank you in advance.
local storage is defined per domain. You should keep objects in localstorage to maintain page context.
Here is solution to do it.
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
document.ready = function(){
var thispage = JSON.parse(localStorage.getItem("page1"));
if(thispage.name){
console.log("name is defined");
}else{
console.log("name is not defined");
var obj={name : "test1"}
localStorage.setItem("page1", JSON.stringify(obj));
}
}
</script>
</head>
<body>
<p id="name"></p>
</body>
</html>
similar to all pages.