I am testing whether i could read a item in a .json file into javascript JSON object and display the contents. I need to store the BIDs in the variable R1 array and display it
Code is as follows
<head>
<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<script type="application/javascript">
function loadJSON()
{
var data_file = "data1.json";
var http_request = new XMLHttpRequest();
try{
// Opera 8.0+, Firefox, Chrome, Safari
http_request = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
http_request.onreadystatechange = function(){
if (http_request.readyState == 4 )
{
// Javascript function JSON.parse to parse JSON data
var jsonObj = JSON.parse(http_request.responseText);
var R1 = new Array();
for(var i= 0 ; i< jsonObj.length; i++){
R1.push(jsonObj[i].BID);
document.write(R1);
}
}
}
http_request.open("GET", data_file, true);
http_request.send();
}
</script>
</body>
</html>
AND my data1.json is as follows
[ { "BID" : "4569749", }, { "BID" : "466759", }, { "BID" : "4561149", }, ]
Yes we can load Json objects, As I did in one of my JSP project. here is the code so that you can easily understand.It is calling a servlet which prepare JSON file from the DB.
$('document').ready(function(){
$.ajax({
type: 'POST',
url: 'getCities',
success: function(data) {
var response = JSON.parse(data);
var products = response['city'];
var product_html = '';
$(products).each(function(index, value){
product_html += ""+value['name']+"";
});
product_html += "";
$("#citylist").html(product_html);
}
});
});
here 'getCities' is a servlet which prepare JSON file from Data fetched from Database. It is actually populating the dropdownlist related to particular counties.
One more thing I believe the json file is incorrect. Please check the format with some json validator.
Related
I am trying working off of https://wiki.apache.org/solr/SolJSON tutorial. I have put my url for solr in the code, copied from solr admin query result to make sure the query should return something.
I try typing in "title:Asian" into text box (that field/search term combo returned results in the admin console query) but when the button is hit, textbox just clears and nothing in output spot.
I used the dev tools from [F12] key of browser to check console and see there was no errors given there, such as for syntax, so not due to that.
Perhaps I am understanding how the url for query works or should be here? If I leave out local host part as shown I just get error for not specifying local full path.
Does anyone see anything wrong here, or have any ideas/tips of what more to do to try and solve the issue?
[ If I must do/add anything else to make good/better post here, please do explain so I can fix :) ]
<html>
<head>
<title>Solr Ajax Example</title>
<meta charset="UTF-8">
<script language="Javascript">
// derived from http://www.degraeve.com/reference/simple-ajax-example.php
function xmlhttpPost(strURL)
{
var xmlHttpReq = false;
var self = this;
if (window.XMLHttpRequest) { // Mozilla/Safari
self.xmlHttpReq = new XMLHttpRequest();
}
else if (window.ActiveXObject) { // IE
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open('POST', strURL, true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
self.xmlHttpReq.onreadystatechange = function() {
if (self.xmlHttpReq.readyState == 4) {
updatepage(self.xmlHttpReq.responseText);
}
};
var params = getstandardargs().concat(getquerystring());
var strData = params.join('&');
self.xmlHttpReq.send(strData);
//document.getElementById("raw").innerHTML = strData;
return false;
}
function getstandardargs() {
var params = [
'wt=json'
, 'indent=on'
, 'hl=true'
];
return params;
}
function getquerystring() {
var form = document.forms['f1'];
var query = form.query.value;
qstr = 'q=' + escape(query);
return qstr;
}
// this function does all the work of parsing the solr response and updating the page.
function updatepage(str)
{
document.getElementById("raw").innerHTML = str;
var rsp = eval("("+str+")"); // use eval to parse Solr's JSON response
var html = "<br>numFound=" + rsp.response.numFound;
var first = rsp.response.docs[0];
html += "<br>product name=" + first.name;
var hl = rsp.highlighting[first.id];
if (hl.name != null) { html += "<br>name highlighted: " + hl.name[0]; }
if (hl.features != null) { html += "<br>features highligted: " + hl.features[0]; }
document.getElementById("result").innerHTML = html;
}
</script>
</head>
<body>
<form name="f1" onsubmit='xmlhttpPost("http://localhost:8983/solr/myCore/select?")'>
<p>query: <input name="query" type="text">
<input value="Go" type="submit"></p>
<div id="result"></div>
<p/><pre>Raw JSON String/output: <div id="raw"></div></pre>
</form>
</body>
</html>
i have trying to get json data via ajax in javascript . but i could not get the updated data from json while clicking the update button. Json data url also working correctly.
Mentioned below code:
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<script type="application/javascript">
function loadJSON() {
var data_file = "http://www.tutorialspoint.com/json/data.json";
var http_request = new XMLHttpRequest();
try {
// Opera 8.0+, Firefox, Chrome, Safari
http_request = new XMLHttpRequest();
} catch (e) {
// Internet Explorer Browsers
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
http_request.onreadystatechange = function () {
if (http_request.readyState == 4) {
var jsonObj = JSON.parse(http_request.responseText);
alert(jsonObj.name);
document.getElementById("Name").innerHTML = jsonObj.name;
document.getElementById("Country").innerHTML = jsonObj.country;
}
}
http_request.open("POST", data_file, true);
http_request.send();
}
</script>
<title>tutorialspoint.com JSON</title>
</head>
<body> <h1>Cricketer Details</h1>
<div id="Name">Sachin</div>
<div id="Country">India</div>
<button type="button" onclick="loadJSON()">Update Details </button>
</body>
</html>
in my above code, i have the url of json data. but while click on the update button, i could get the json data via ajax.
i could not find it out which is wrong in my code?
thanks in advance.
If you have the liberty to include the jQuery library, you can do it using $.ajax.
Use a regular web method that returns a json, and call it, like so:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: serverpath + "/Service.asmx/GetJSON",
data: {},
dataType: "json",
success: function (data, textStatus) {
if (data.hasOwnProperty('d')) {
data = data.d;
}
var jsonObj = data; // or $.parseJSON(data); if required
},
error: function (msg) {
console.log(msg);
}
});
I am creating a weather widget using javascript . In this widget the user can select the town they wish to see and the widget will display outlook , min and max temperature without refreshing using ajax . I have stored the city information in a database and had written PHP script to retrieve the data and pass it to js as JSON object
<?php
/**************************
* code to connect to your database here
*/
$con = mysqli_connect("localhost", "user", "pass");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL:".mysqli_connect_error();
}
mysqli_select_db("weather", $con);
$town = $_GET['town'];
/***************************
*
* Query the DB for weather information for the given town.
*
* A PHP array object containing the weather data.
* Return a JSON encoded version of the array to the browser.
*
*/
$sql = "SELECT * from weather where town = $town";
$result = mysqli_query($sql);
while($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
$arr = array(
"town" => $row[town],
"outlook" => $row[outlook],
"min_temp" => $row[min_temp],
"max_temp" => $row[max_temp]
);
}
echo json_encode($arr);
mysqli_close();
?>
And in js i want to show the weather only for selected town . How to parse the JSON object to get only the information of the town selected by the user . Like
if(jsondata == "sydney")
return "sydney information";
I did this using DOJO as
var data;
dojo.xhrGet({
// The URL to request
url: "PHP/weather.php?town=" + ntown,
sync: true,
handleAs: 'json',
// The method that handles the request's successful result
// Handle the response any way you'd like!
load: function(result) {
data = result;
}
});
return data;
}
However , i dont want to use dojo . how do i do that . Any suggestions ?
Suppose you have a select tag with id "town".
<select id="town" onchange="handler(this)"></select>
Now, for the Javascript part. You need to use XMLHttpRequest to make an ajax call.
function handler(elem){
var tname = elem.value;
var request_url = "PHP/weather.php?town=" + tname;
var http_request = new XMLHttpRequest();
try{
// Opera 8.0+, Firefox, Chrome, Safari
http_request = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Some error occured");
return false;
}
}
}
http_request.onreadystatechange = function(){
if (http_request.readyState == 4 )
{
// Javascript function JSON.parse to parse JSON data
var jsonObj = JSON.parse(http_request.responseText);
//Update your page here
}
}
http_request.open("GET", request_url);
http_request.send();
}
<body>
<div id="townInfo">
<div id="town"></div>
<div id="outlook"></div>
<div id="min_temp"></div>
<div id="max_temp"></div>
</div>
<script>
var town = document.getElementById('town');
var outlook = document.getElementById('outlook');
var min_temp = document.getElementById('min_temp');
var max_temp = document.getElementById('max_temp');
var data;
dojo.xhrGet({
// The URL to request
url: "PHP/weather.php?town=" + ntown,
sync: true,
handleAs: 'json',
load: function(result) {
data = result;
town.innerHtml = data['town'];
outlook.innerHtml = data['outlook'];
min_temp.innerHtml = data['min_temp'];
max_temp.innerHtml = data['max_temp'];
}
});
</script>
</body>
warning: not tested
i'm usig this script below, and works perfectly on chrome, and firefox, but on ie, i can't get the response from webservice. I need open/redirect to anothers sites if success or error! Why can read response from webservice on IE, and how resolve this?
function sendInfo(userId, Code) {
// text with all info to send to controller
var values = {
"token": Code,
"code": userId
}
// POST THE CHANGE HERE TO THE DATABASE
var url = "WSFacebook.asmx/saveToken";
$.post(url, values, function(data) {
if (window.ActiveXObject) {
return data.xml;
}
var xmlString = new XMLSerializer().serializeToString(data);
var xml = xmlString,
xmlDoc = $.parseXML(xml),
$xml = $(xmlDoc),
$title = $xml.find("string");
var texto = $title.text();
if ($title.text() == "Success") {
window.location = '<%=ConfigurationManager.AppSettings["successUrl"].ToString() %>';
} else {
window.location = '<%=ConfigurationManager.AppSettings["errorUrl"].ToString() %>';
}
});
}
I am querying a PostGIS database based on where a user clicks on a google map. I am then parsing the JSON response into a googleMaps infoWindow. This has been working great but I'd now like to query multiple urls and use those responses to fill in the infoWindow. Below is an example of the functions I've used that work great. Note: please disregard the url provided as I just made it up for this example.
var clickLoc;
function queryAct(event){
clickLoc=event.latLng;
var clickLat=clickLoc.lat();
var clickLng=clickLoc.lng();
var loUrl = 'http://www.myspatialdataset.com/sql/?q=select%20ownercateg%20from%20stew_owners%20where%20ST_Intersects%28the_geom,%20ST_GeomFromText%28%27POINT%28'+clickLng+'%20'+clickLat+'%29%27,4326%29%29';
if (window.XMLHttpRequest) { // Non-IE browsers
req = new XMLHttpRequest();
req.onreadystatechange = clickResponse;
try {
req.open("GET", loUrl, true);
} catch (e) {
alert(e);
}
req.send(null);
} else if (window.ActiveXObject) { // IE
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req) {
req.onreadystatechange = clickResponse;
req.open("GET", loUrl, true);
req.send();
}
}
}
function clickResponse(){
if (req.readyState == 4) { // Complete
if (req.status == 200) { // OK response
var clickPingBack = JSON.parse(req.responseText);
var loResponse = clickPingBack;
if (loResponse.rows.length>0)
{
var loResponseParsed=loResponse.rows[0].ownercateg;
fillWithClicked(loResponseParsed);
}
else
{
var loResponseParsed=' other';
fillWithClicked(loResponseParsed);
}
}
}
}
var infowindow = new google.maps.InfoWindow;
function fillWithClicked(loResponseParsed){
infowindow.setContent(loResponseParsed);
infowindow.setPosition(clickLoc);
infowindow.open(map);
}
How could I now do this for multiple url requests and pass those responses to the same, fillWithClicked function that fills in the infoWindow?
The code below is obviously wrong but may better explain what I am trying to do i.e. multiple URLS and filling the infoWindow with the response from two url requests. This sometimes works but is totally wrong
var clickLoc;
function distQueryAct(event){
clickLoc=event.latLng;
var clickLat=clickLoc.lat();
var clickLng=clickLoc.lng();
var distUrl = 'http://www.myspatialdataset.com/sql/?q=select%20district%20from%20mt_elk%20where%20ST_Intersects%28the_geom,%20ST_GeomFromText%28%27POINT%28'+clickLng+'%20'+clickLat+'%29%27,4326%29%29';
if (window.XMLHttpRequest) { // Non-IE browsers
distReq = new XMLHttpRequest();
distReq.onreadystatechange = loQueryAct(clickLoc);
try {
distReq.open("GET", distUrl, true);
} catch (e) {
alert(e);
}
distReq.send(null);
} else if (window.ActiveXObject) { // IE
distReq = new ActiveXObject("Microsoft.XMLHTTP");
if (distReq) {
distReq.onreadystatechange = loQueryAct(clickLoc);
distReq.open("GET", distUrl, true);
distReq.send();
}
}
}
function loQueryAct(clickLoc){
var clickLat=clickLoc.lat();
var clickLng=clickLoc.lng();
var loUrl = 'http://www.myspatialdataset.com/sql/?q=select%20ownercateg%20from%20stew_owners%20where%20ST_Intersects%28the_geom,%20ST_GeomFromText%28%27POINT%28'+clickLng+'%20'+clickLat+'%29%27,4326%29%29';
if (window.XMLHttpRequest) { // Non-IE browsers
loReq = new XMLHttpRequest();
loReq.onreadystatechange = distClickResponse;
try {
loReq.open("GET", loUrl, true);
} catch (e) {
alert(e);
}
loReq.send(null);
} else if (window.ActiveXObject) { // IE
loReq = new ActiveXObject("Microsoft.XMLHTTP");
if (loReq) {
loReq.onreadystatechange = distClickResponse;
loReq.open("GET", loUrl, true);
loReq.send();
}
}
}
function distClickResponse(){
if (distReq.readyState == 4 && loReq.readyState == 4) { // Complete
if (distReq.status == 200 && loReq.status == 200) { // OK response
var distPingBack = JSON.parse(distReq.responseText);
var distResponse = distPingBack;
var loPingBack = JSON.parse(loReq.responseText);
var loResponse = loPingBack;
if (distResponse.rows.length>0)
{
var distResponseParsed=distResponse.rows[0].district;
}
else
{
var distResponseParsed=' other';
}
if (loResponse.rows.length>0)
{
var loResponseParsed=loResponse.rows[0].ownercateg;
}
else
{
var loResponseParsed=' other';
}
}
distFillWithClicked(loResponseParsed,distResponseParsed);
}
}
var infowindow = new google.maps.InfoWindow;
function distFillWithClicked(distResponseParsed,loResponseParsed){
infowindow.setContent(distResponseParsed+loResponseParsed);
infowindow.setPosition(clickLoc);
infowindow.open(map);
}
I figured it out. Using getJSON instead of XMLHttpRequest was the key. I know this could be cleaner but it does work.
var clickLoc;
function queryAct(event){
clickLoc=event.latLng;
var clickLat=clickLoc.lat();
var clickLng=clickLoc.lng();
var toFillArray=Array();
var loUrl='http://www.mypostgis.com/sql/?q=select%20ownercateg%20from%20stew_owners%20where%20ST_Intersects%28the_geom,%20ST_GeomFromText%28%27POINT%28'+clickLng+'%20'+clickLat+'%29%27,4326%29%29';
var distUrl='http://www.mypostgis.com/sql/?q=select%20district%20from%20mt_elk%20where%20ST_Intersects%28the_geom,%20ST_GeomFromText%28%27POINT%28'+clickLng+'%20'+clickLat+'%29%27,4326%29%29';
$.getJSON(loUrl,function(tmpLoDat){
if (tmpLoDat.rows.length>0)
{
var tempCat=tmpLoDat.rows[0].ownercateg;
toFillArray.push(tempCat);
}
else
{
var tempCat='other';
toFillArray.push(tempCat);
}
otherFunction(toFillArray,distUrl);
})
}
function otherFunction(toFillArray,distUrl){
$.getJSON(distUrl,function(tmpDistDat){
if (tmpDistDat.rows.length>0)
{
var tempDist=tmpDistDat.rows[0].district;
toFillArray.push(tempDist);
}
else
{
var tempDist='Other';
toFillArray.push(tempDist);
}
fillWithClicked(toFillArray);
})
}
var infowindow = new google.maps.InfoWindow;
function fillWithClicked(toFillArray){
infowindow.setContent(toFillArray[0]+toFillArray[1]);
infowindow.setPosition(clickLoc);
infowindow.open(map);
}
If you want the data to grow your element, let's try something like that :
function fillWithClicked(loResponseParsed){
document.getElementById("regulations").innerHTML += loResponseParsed;
}
If the calls of your function are not in the same page, you'll need to use a cache file and a user_id (session id, cookie id or IP adress...):
// js & jquery for example
function fillWithClicked(loResponseParsed,user_id)
{
$.post('cachecreate.php',{content:loResponseParsed,user_id:user_id},
function()
{
$.get('cachefile_'+user_id+'.html',
function(data)
{
document.getElementById("regulations").innerHTML=data;
});
});
}
// cachecreate.php for example
<?php
$cache = "cachefile_".$_POST['user_id'].".html";
ob_start();
if(file_exists($cache))
{
include($cache);//or readfile(); i forgot...
echo "<hr/>".$_POST['content'];// Strip <hr/> for JSON
}
else
{
echo $_POST['content'];
}
$page_content=ob_get_contents();// if JSON needed : json_encode($page_content);
ob_end_clean();
file_put_contents($cache, $page_content);// PHP 5+ function
?>
I hope that it may help you, or bring you to the solution.
EDIT regarding your new details
Try something like this (I lighten your code...).
With this you can add as multiple urls as you want.
var clickLoc;
function queryAct(event)
{
clickLoc=event.latLng;
var clickLat=clickLoc.lat();
var clickLng=clickLoc.lng();
var url=Array();
var data=null;
url['loUrl'] ="url1";
url['distUrl'] ="url2";
url['otherUrl'] ="urlx";
for(page in url)
{
data+=getJSON(page);
}
fillWithClicked(data);
}
function getJSON(url)
{
if (window.XMLHttpRequest)
{req = new XMLHttpRequest();}// Non-IE
else if (window.ActiveXObject)
{req = new ActiveXObject("Microsoft.XMLHTTP");}// IE
if(req)
{
req.open("GET", url, true);
req.send(null);
req.onreadystatechange = function() {
if(req.readyState == 4)
{
if (req.status == 200)
{ // OK response
var clickPingBack = JSON.parse(req.responseText);
var loResponse = clickPingBack;
if (loResponse.rows.length>0)
{
var loResponseParsed=loResponse.rows[0].ownercateg;
}
else
{
var loResponseParsed=' other';
}
return loResponseParsed;
}
}
}
}
}
var infowindow = new google.maps.InfoWindow;
function fillWithClicked(loResponseParsed)
{
infowindow.setContent(loResponseParsed);
infowindow.setPosition(clickLoc);
infowindow.open(map);
}
EDIT -> External domain files
httpRequest doesn't work with files in another domain.
You can use one of those solutions, I may use the second for me.
PHP Solution
// In your js file, change the urls like this
url['url_x'] ='myphppage.php?url=url_x_to_parse';
// myphpage.php script that displays the content of the external file
<?php
if(isset($_GET['url'])) {
header("Content-type: text/json");
echo file_get_contents(urldecode($_GET['url']));
}
?>
JQUERY solution (better one)
// change the name of getJSON function cause jquery uses the same name...
function getURLcontent(url)
{
$.get(url,function(data){
var clickPingBack = JSON.parse(data.responseText);
var loResponse = clickPingBack;
loResponse=data;
if (loResponse.rows.length>0)
{
var loResponseParsed=loResponse.rows[0].ownercateg;
}
else
{
var loResponseParsed=' other';
}
return loResponseParsed;
});
}
download jquery library http://code.jquery.com/jquery-1.7.1.min.js
include jquery plugin in the head of your page with <script src="jquery-1.7.1.min.js"></script>