I want to display data from MySQL with vis.js.
I get data with JSON, but I am having this error:
Error: Node must have an id
throw new Error("Node must have an id");
-------^
function tampil()
{
$.ajax({
type:"GET",
cache :false,
dataType: "json",
url:"fetch.php",
success: function(data){
console.log(data);
var vertex = new vis.DataSet([
{id:data[0], label:data[1]}
]);
var hubung = new vis.DataSet([
{from:data[2], to:data[3]}
]);
var myDiv = document.getElementById("media");
var data = {
nodes : vertex,
edges : hubung
}
var options = {};
var network = new vis.Network(myDiv,data,options);
}
});
}
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="js/vis.js"></script>
<script type="text/javascript" src="js/jquery-2.1.3.min.js"></script>
<link rel="stylesheet" type="text/css" href="css/vis.css" />
</head>
<body>
<button type="button" onclick="tampil()">proses</button>
<div id="media" style="width:500px;height:500px;"></div>
</body>
</html>
and my server sid like this
solved, in JavaScript I've added the following code:
function tampil()
{
$.ajax({
type:"GET",
cache :false,
dataType: "json",
url:"nodes.php",
success: function(data){
console.log(data);
var vertex = new vis.DataSet();
var hubung = new vis.DataSet();
var myDiv = document.getElementById("media");
var data = {
nodes : vertex,
edges : hubung
}
var options = {};
var network = new vis.Network(myDiv,data,options);
$.getJSON('edges.php', function(edges) {
hubung.add(edges);
});
$.getJSON('nodes.php', function(nodes) {
vertex.add(nodes);
});
}
});
}
Related
I am having trouble with my JSON payload. The success function does not fire.
Thanks in advance for any help that can be provided.
JLS
I get the value in the console so I know the query works okay but it is not in a key/value pair it just echos "VALUE" and does not triggers success.
//JS file ***UPDATED***
$(document).ready(function(){
// code to get all records from table via select box
$("#school").change(function() {
var id = $(this).find(":selected").val();
var dataString = 'school='+ id;
$.ajax({
url: 'cif_submit.php',
dataType: "json",
data: dataString,
cache: false,
success: function(data) {
if(data) {
alert(data);
}
}
});
})
});
//Here is the php ***UPDATED***
if($_REQUEST['school']) {
$stmt = $conn->prepare("SELECT streetname FROM schoolinfo WHERE fullschoolname = :schoolname");
$stmt->execute (array(':schoolname' =>$_REQUEST['school']));
while($mydata = $stmt->fetch()) {
echo json_encode($mydata);
} }
}
The JSON RESPONSE is:
{"streetname":"Colbeck Road, PO Bag 7200","0":"Colbeck Road, PO Bag 7200"}
I think changing the schooldata to data will fix the issue.
Don't forget that change() event gets called when you unfocus the input.
https://api.jquery.com/change/
Tried with this code and worked perfectly.
JS
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
</head>
<body>
<input id="school" type="text">
<script>
$(document).ready(function(){
// code to get all records from table via select box
$("#school").change(function() {
var id = $(this).find(":selected").val();
var dataString = 'school='+ id;
$.ajax({
url: 'a.php',
dataType: "json",
data: dataString,
cache: false,
success: function(schooldata) {
if(schooldata) {
alert('success');
//$("#streetname").text(schooldata.streetname); TRIED THIS NO JOY
//$("#streetname").hide(); TRIED THIS NO JOY
}
}
});
})
});
</script>
</body>
</html>
PHP
if($_REQUEST['school']) {
$datas = array();
$datas[] = array('streetname' => 'test');
foreach ($datas as $data) {
$data = $data['streetname'];
//$streetname = trim(json_encode($data), '"');
//echo json_encode($data);
echo json_encode($data, true);
}
}
I use this script to get the markers for Google Maps with JSON.
It is not working because I need to receive the boundary in the Json script like this:
$swLat=$_GET["swLat"];
$swLon=$_GET["swLon"];
$neLat=$_GET["neLat"];
$neLon=$_GET["neLon"];
That is where I need your help.
Google maps script
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script type="text/javascript" src="http://skiweather.eu/gmap3/js/jquery.ui.map.js"></script>
<script language="javascript" type="text/javascript">
var map = null;
map = new google.maps.Map(document.getElementById("map"));
var markers = new Array();
var bounds = map.getBounds();
var zoomLevel = map.getZoom();
$(function() {
demo.add(function() {
$('#map').gmap().bind('init', function() {
$.getJSON( 'http://skiweather.eu/gmap3/markers/index.php', {zoom: zoomLevel,
swLat: bounds.getSouthWest().lat(), swLon: bounds.getSouthWest().lng(),
neLat: bounds.getNorthEast().lat(), neLon: bounds.getNorthEast().lng()}, function(data) {
$.each( data.markers, function(i, marker) {
$('#map').gmap('addMarker', {
'position': new google.maps.LatLng(marker.latitude, marker.longitude),
'bounds': true
}).click(function() {
$('#map').gmap('openInfoWindow', { 'content': marker.content }, this);
});
});
});
});
}).load();
});
</script>
</head>
<body>
<div id="map"></div>
The jQuery/gmap-part of your code will not be executed at all.
Fixed code:
<script type="text/javascript">
$(function() {
$('#map').gmap().bind('init', function() {
var markers = new Array();
var bounds = $(this).gmap('get','map').getBounds();
var zoomLevel = $(this).gmap('get','map').getZoom();
$.getJSON( 'http://skiweather.eu/gmap3/markers/index.php', {zoom: zoomLevel,
swLat: bounds.getSouthWest().lat(), swLon: bounds.getSouthWest().lng(),
neLat: bounds.getNorthEast().lat(), neLon: bounds.getNorthEast().lng()}, function(data) {
$.each( data.markers, function(i, marker) {
$('#map').gmap('addMarker', {
'position': new google.maps.LatLng(marker.latitude, marker.longitude),
'bounds': true
}).click(function() {
$('#map').gmap('openInfoWindow', { 'content': marker.content }, this);
});
});
});
});
});
</script>
However, it's sending the data now, but it's still not working, because the server will not give any response(are you sure that there is a webservice that returns JSON-data?)
I am trying to show loading image until php excutes, the query works on the second page but the results aren't showing on the first page, I know I am missing something here, can someone help me out? I am new to jquery or ajax thing.
home.php
<html>
<head>
<!--Javascript-->
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
$('#loading_spinner').show();
var post_data = "items=" + items;
$.ajax({
url: 'list.php',
type: 'POST',
data: post_data,
dataType: 'html',
success: function(data) {
$('.my_update_panel').html(data);
},
error: function() {
alert("Something went wrong!");
}
});
$('#loading_spinner').hide();
</script>
<style>
#loading_spinner { display:none; }
</style>
</head>
<body>
<img id="loading_spinner" src="image/ajax-loader.gif">
<div class="my_update_panel">
<!--I am not sure what to put here, so the results can show here-->
</div>
list.php I tested the query and it prints the rows.
<?php
include_once("models/config.php");
// if this page was not called by AJAX, die
if (!$_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') die('Invalid request');
// get variable sent from client-side page
$my_variable = isset($_POST['items']) ? strip_tags($_POST['items']) :null;
//run some queries, printing some kind of result
$mydb = new mysqli("localhost", "root", "", "db");
$username = $_SESSION["userCakeUser"];
$stmt = $mydb->prepare("SELECT * FROM products where username = ?");
$stmt->bind_param('s', $username->username);
$stmt->execute();
// echo results
$max = $stmt->get_result();
while ($row = $max->fetch_assoc()) {
echo $row['title'];
echo $row['price'];
echo $row['condition'];
}
?>
The HTML. Put the img inside of the .my_update_panel div
<div class="my_update_panel">
<img id="loading_spinner" src="image/ajax-loader.gif">
</div>
The JS
var url = 'list.php';
var post_data = "items=" + items;
$('.my_update_panel').load(url, post_data, function() {
$(this +' #loading_spinner').fadeOut('slow');
});
You can find a good selection of loading images that are readily available for download here.
There is a issue with
var post_data = "items=" + items;
Make it
$(document).ready(function(){
$('#loading_spinner').show();
$.ajax({
url: 'list.php',
type: 'POST',
data: {"items":items},
dataType: 'html',
success: function(data) {
$('.my_update_panel').html(data);
$('#loading_spinner').hide();
},
error: function() {
alert("Something went wrong!");
}
});
});
let me know if works for you.
Try To add complete event in the ajax , I hope it will work. Refer
http://api.jquery.com/jQuery.ajax/
<html>
<head>
<!--Javascript-->
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
$('#loading_spinner').show();
var post_data = "items=" + items;
$.ajax({
url: 'list.php',
type: 'POST',
data: post_data,
dataType: 'html',
success: function(data) {
$('.my_update_panel').html(data);
},
error: function() {
alert("Something went wrong!");
},
complete:function(){
$('#loading_spinner').fadeOut(500);
});
//$('#loading_spinner').hide();
</script>
<style>
#loading_spinner { display:none; }
</style>
</head>
<body>
<img id="loading_spinner" src="image/ajax-loader.gif">
<div class="my_update_panel">
<!--I am not sure what to put here, so the results can show here-->
</div>
It is better to chain the ajax callback functions. adding callbacks as options will be removed from jquery in the future.
http://api.jquery.com/jQuery.ajax/
Deprecation Notice: The jqXHR.success(), jqXHR.error(), and
jqXHR.complete() callbacks are deprecated as of jQuery 1.8. To prepare
your code for their eventual removal, use jqXHR.done(), jqXHR.fail(),
and jqXHR.always() instead.
var post_data = items;
$('#loading_spinner').show();
$.ajax({
url: 'list.php',
type: 'POST',
dataType: 'html',
data: {"items":post_data},
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("error");
})
.always(function() {
$('#loading_spinner').hide();
});
I hide the loading_spinner in the always() callback, that way the spinner also disappears when the ajax call throws an error. if this is not working you have to search in your server side code to solve the problem. First of, are you sure the response is html? you might have to set the dataType to text in the ajax call.
so I've got these two sets of JavaScript functions that continuously pole my server and, if the database has been updated, the functions do something. Both sets of functions have nothing to do with each other; they're only relationship is that they happen at the same time. Yet for some reason one function is conflicting with the other. Here's what my code looks like:
<!DOCTYPE html>
<html>
<head>
<title>Stage</title>
<link href="stage.css" rel="stylesheet" type="text/css">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
<script type="text/javascript">
///////////////////// FUNCTION SET 1
function loadThumbnail(){
$.ajax({
url: 'process_stage_show.php',
data: 'value=<?php echo $_GET["session"]; ?>',
dataType: 'json',
success: function(data){
var idCurrent = data[0];
var idVideo = data[1];
var idSession = data[2];
var state = data[4];
if (state == 1) {
$('#tv').html('<img src="http://i.ytimg.com/vi/'+ idVideo +'/hqdefault.jpg" width ="800" height="533"/>');
setTimeout(function(){timedCount2(idCurrent);},1000);
}
else {
setTimeout(function(){timedCount2(idCurrent);},1000);
}
}
});
}
function timedCount2(idCurrent){
$.ajax({
url: 'process_stage_show.php',
data: 'value=<?php echo $_GET["session"]; ?>',
dataType: 'json',
success: function(data) {
var idNew = data[0];
var idVideo = data[1];
var idSession = data[2];
var state = data[4];
if (!(idCurrent == idNew)) {
window.location.reload();
}
else{
setTimeout(function(){timedCount2(idCurrent);},1000);
}
}
});
}
///////////////////// FUNCTION SET 2
function loadStage(){
$.ajax({
url: 'process_stage_play.php',
data: 'value=<?php echo $_GET["session"]; ?>',
dataType: 'json',
success: function(data){
var idVideo = data[0];
var idCurrent = data[1];
var idSession = data[2];
var state = data[4];
if (state == 2) {
//alert("State equal to 2. Do nothing.");
setTimeout(function(){timedCount(idCurrent);},1000);
}
else if (state == 1) {
//alert("State equal to 1. Open window.");
popupwindow = window.open ("http://www.youtube.com/watch_popup?v="+ idVideo);
setTimeout(function(){timedCount(idCurrent);},1000);
}
else if (state == 0) {
//alert("State equal to 0. Close window.");
popupwindow.close();
setTimeout(function(){timedCount(idCurrent);},1000);
}
}
});
}
function timedCount(idCurrent){
$.ajax({
url: 'process_stage_play.php'
data: 'value=<?php echo $_GET["session"]; ?>',
dataType: 'json',
success: function(data) {
var idVideo = data[0];
var idNew = data[1];
var idSession = data[2];
var state = data[4];
if (idCurrent == idNew) {
setTimeout(function(){timedCount(idCurrent);},1000);
}
else{
//alert("ID has changed. Re-load stage.");
loadStage();
}
}
});
}
</script>
</head>
<body onload="loadStage(); loadThumbnail();">
<div id="tv"></div>
</body>
</html>
I'm don't want to go into too much detail about what these sets of functions do (unless requested) as I don't want this post to be REALLY long. But the problem is both these sets of functions work fine by themselves but for some reason if you run them at the same time, the second function set keeps saying popupwindow is not defined when state is equal to 0.
Which makes no sense! Why would the first function set cause that to happen? :(
Well one of the things that the first function sometimes does is reload the window. As soon as that happens, the global variable "popupwindow" will vanish.
It might work to have code in the popped-up window check its "opener" window periodically to see whether it should close itself.
Do I understand correctly that these functions both open a popup window?
If so, some browsers do only open one popup per webpage and if another popup is opened, the old one will be refreshed with the new url.
Thus, one of these functions could lose "its" popup window which would explain your problem.
I am trying to minimize my code by putting it into an array but nothing happens. I can't figure out what I am doing wrong. Here's the code
<html>
<head>
<title>test</title>
<!-- JavaScript -->
<script src="js/jquery-1.5.2.js" type="text/javascript"></script>
<script type="text/javascript">
var phpfile = new Object();
phpfile["testselect"] = "zoomchange.php";
var elementID = new Object();
elementID["testselect"] = "#testdiv";
$(document).ready(function(){
$("select").change(function() {
$.post(
phpfile[$(this).id()],
$(this).serialize(),
function(data) {
$(elementID[$(this).id()]).html(data)
}
);
});
});
</script>
</head>
<body>
<select id="testselect">
<option value="1">1</option>
<option value="2">2</option>
</select>
<div id="testdiv"></div>
</body>
</html>
here is the zoomchange.php:
<?PHP echo $_REQUEST['testselect'] ; ?>
Your initializers shouldn't look like this:
var phpfile = new Array();
phpfile["testselect"] = "zoomchange.php";
var elementID = new Array();
elementID["testselect"] = "#testdiv";
A JavaScript Array is indexed by numbers, not strings. You want simple object literals:
var phpfile = { testselect: 'zoomchange.php' };
var elementED = { testselect: '#testdiv' };
Then, your POST callback is confused:
function(data) {
$(elementID[$(this).id()]).html(data)
}
this isn't what you think it is when that function is called. You want something more like this:
$("select").change(function() {
var that = this;
$.post(
phpfile[that.id],
$(this).serialize(),
function(data) {
$(elementID[that.id]).html(data);
}
);
});
This
function(data)
{
$(elementID[$(this).id()]).html(data);
}
instead of this
function(data)
{
$(elementID[$(this).id()]).html(data)
}
Is this the error ?
You should do new Object() instead of new Array().
Edit: There are other mistakes, your js code should be this:
<script type="text/javascript">
var phpfile = {};
phpfile["testselect"] = "zoomchange.php";
var elementID = {};
elementID["testselect"] = "#testdiv";
$(document).ready(function(){
$("select").change(function() {
var $select = $(this);
$.post(
phpfile[$select.attr("id")],
$select.serialize(),
function(data) {
$(elementID[$select.attr("id")]).html(data)
}
);
});
});
</script>