I'm having an issue accessing a json file from a js script in a Laravel project.
I am using the Google maps API to add markers to a map, which are all currently hard-coded because I can only seem to access the json from within a listener function.
I am fully able to access my json through the placeMarker click listener, but when i try to make the "otherPlace" using json values, the values cannot be found. Not sure what's going on here.
Sorry for the likely noob question but I am stumped and couldn't find any similar questions.
Map script Example:
function myMap() {
var mapProp= {
center:new google.maps.LatLng(44.5458062,-83.54936229999996),
zoom:8,
};
var map = new google.maps.Map(document.getElementById("googleMap"),mapProp);
var place = new google.maps.LatLng(44.453,-83.45773609999998);
var placeMarker = new google.maps.Marker({position: place});
var otherPlace = new google.maps.LatLng(json.locations[4].lat,json.locations[4].lng);
var otherPlaceMarker = new google.maps.Marker({position: otherPlace});
placeMarker.setMap(map);
otherPlaceMarker.setMap(map);
placeMarker.addListener('click', function() {
map.setZoom(13);
map.setCenter(placeMarker.getPosition());
console.log(json.locations[5].address);
var infowindow = new google.maps.InfoWindow({
//content: json.locations[5].name + "\r\nAddress: " + json.locations[5].address
});
infowindow.setContent(
"<p>" + json.locations[5].name + "<br />" + json.locations[5].address + "<br/> <a href='#'>Get Directions</a> </p>"
);
infowindow.open(map,placeMarker);
});
}
In my controller I grab the json file and pass it to the view
public function locations() {
$path = storage_path() . "/json/locations.json";
$json = json_decode(file_get_contents($path), true);
return view('home/locations', compact('json'));
}
In my locations.blade.php I add the map script and pass the json to javascript
#section('scripts')
<script src="/js/locationsMap.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key={{ env('APP_GOOGLE_MAPS') }}&callback=myMap"></script>
<script>
var json = {!! json_encode($json) !!};
</script>
#endsection
Try removing var from var json if that doesn't work, put your function below json = {!! json_encode($json) !!}; and try then
I refer to the question Polygon "Drawing and Getting Coordinates with Google Map API v3" and the code by jhawes which works fine; BUT I've struggle to post the lat/lng-values to a DB using php.
In other scripts with single coordinates I use the following (whereas the variables "BlattNr, Quadrant, MTBlat, MTBlng, Qmlat, Qmlng" are of no interest for that question):
function saveData(BlattNr, Quadrant, MTBlat, MTBlng, Qmlat, Qmlng) {
var latlng = marker.getPosition();
window.location.href = "schritt_2.php?lat=" + latlng.lat() +
"&lng=" + latlng.lng() + "&MTBNr=" + BlattNr + "&Quadrant=" + Quadrant + "&MTBlat=" + MTBlat + "&MTBlng=" + MTBlng + "&Qmlat=" + Qmlat + "&Qmlng=" + Qmlng;
marker.setMap(null);
}
With this I can post the lat and lng of the single point coordinate - but how to pass the multiple lat and lng of various points? I don't know how to define the variable and how to construct the "saveData" function...
Many thanks in advance for any help :-)
Okay, I copy/pasted the code that jhawes put in jsFiddle
I added a few things.
add jQuery
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Save_data
function save_data() {
var data = [];
var len = myPolygon.getPath().getLength();
for (var i = 0; i < len; i++) {
data.push([myPolygon.getPath().getAt(i).lat(), myPolygon.getPath().getAt(i).lng()]);
}
// send data to the server
$.ajax({
url: 'save.php?p=' + JSON.stringify(data),
success: function (message) {
$('#ajaxresponse').html(message);
}
});
}
A button and a display div. Put them somewhere at the bottom of the markup.
<input type="button" onclick="save_data()" value="SAVE">
<div id="ajaxresponse"></div>
Server side: I don't do much here; I'm sure you can handle it.
save.php
<?php
if (isset($_GET['p'])) {
$locations = json_decode($_GET['p'], true);
echo print_r($locations, true) . '<br>';
echo "let's print the second point: lat=" . $locations[1][0] . ", lng=" . $locations[1][0];
}
?>
I am following some tutorial to pass a JSON text file from server to display the data after some javascript processing on a html file. As a test, try to display a LI of one column, but cannot get any output in the browser. Your help is appreciated.
I tried two approaches.
Approach 1 xmlhttp:
Apparently, the browser complain about the html format:
Uncaught SyntaxError: Unexpected string (15:08:42:080 | error, javascript)
at testJSON3.html:12
Is my xmlhttp call format correct?
Thank you for your help in advance.
Here's JSON text myTutorial.txt:
[
{
"active":"1",
"courseCode":"208.01.00",
"courseName":"course name 1",
"eventDesc":"2015 class of course name 1"
},
{
"active":"1",
"courseCode":"208.01.00",
"courseName":"course name21",
"eventDesc":"2015 class of course name "
}
]
And processed by the below html to process the xmlhttp access to the file on server localhost directory phpTWLLT
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript' src='js/jquery.min.js'></script>
<meta charset="UTF-8">
</head>
<body>
<div id="id01"></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://localhost/phpTWLLT/myTutorial.txt";
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myArr = JSON.parse(xmlhttp.responseText);
myFunction(myArr);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
var out = "";
var i;
for (i = 0; i < arr.length; i++) {
out += '<li'> + arr[i].courseCode +'</li><br>';
}
document.getElementById("id01").innerHTML = out;
}
</script>
</body>
</html>
Approach 2 getJSON():
This one is interesting. If the server side is static array ($DEBUG = true:), javascript is able to process and get browser display. But fail when generate the text from mysql ($DEBUG = false).
I am scratching my head to get the $DEBUG=false work? Apparently, both cases generated a valid JSON text.
If $DEBUG is set true,
output from localhost/phpTWLLT/json_encode_array.php
[{"active":"0","first_name":"Darian","last_name":"Brown","age":"28","email":"darianbr#example.com"},{"active":"1","first_name":"John","last_name":"Doe","age":"47","email":"john_doe#example.com"}]
the list displayed in browser.
0
1
If $DEBUG is set false,
output from localhost/phpTWLLT/json_encode_array.php
[{"active":"1"},{"active":"1"}]
The browser display is blank.
html file:
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<!--
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js'> </script>
-->
<script type='text/javascript' src='js/jquery.min.js'></script>
<meta charset="UTF-8">
</head>
<body>
<!-- this UL will be populated with the data from the php array -->
<ul></ul>
<script type='text/javascript'>
$(document).ready(function () {
/* call the php that has the php array which is json_encoded */
//$.getJSON('json_encoded_array.php', function(data) {
$.getJSON('json_encoded_array.php', function (data) {
/* data will hold the php array as a javascript object */
$.each(data, function (key, val) {
$('ul').append('<li id="' + key + '">' + val.active + '</li>');
});
});
});
</script>
</body>
</html>
PHP script: json_encoded_array.php
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/* set out document type to text/javascript instead of text/html */
$DEBUG = true;
if ($DEBUG) {
header("Content-type: text/javascript");
$arr = array(
array(
"active" => "0",
"first_name" => "Darian",
"last_name" => "Brown",
"age" => "28",
"email" => "darianbr#example.com"
),
array(
"active" => "1",
"first_name" => "John",
"last_name" => "Doe",
"age" => "47",
"email" => "john_doe#example.com"
)
);
} else {
require_once('connection.php');
// $m_id= 8 has many enrolled course and 11 got exactly one course enrolled.
$m_id = 8;
$p_id = 1;
$qry1 = "SELECT distinct event.active as active, subject.code as 'courseCode', subject.name as 'courseName', event.event_desc as 'eventDesc' FROM applicant, event, subject, part where applicant.applicant_id = $m_id and applicant.event_id = event.id and event.subject_id=subject.id and part.id = subject.owner_id and part.id = $p_id order by event.active DESC, event.from_month DESC ";
mysqli_set_charset($bd, 'utf-8');
$result = mysqli_query($bd, $qry1);
$arr = array();
$i = 0;
if (mysqli_num_rows($result) > 0) {
while ( $rs = mysqli_fetch_assoc($result) ) {
$colhead = "active";
$str = $rs['active'];
$arr[$i] = array($colhead => $str);
$i++;
// just generate two record for testing
if ($i === 2)
break;
}
}
}
echo json_encode($arr);
?>
For approach 2, did you try debugging the javascript code to check if the data variable contains the expected data?
You could also check the network tab to see if the response data sent from your server is correct.
So basically I'm making cURL request and getting response that looks like this(var_dump):
string(595) "{"user_id":1,"currency":"eur","purchase_packs":{"1":{"amount":500,"allowed_payment_methods":["ideal","paypal","visa","mc"]},"3":{"amount":1000,"allowed_payment_methods":["mc","ideal","paypal","visa"]},"6":{"amount":2500,"allowed_payment_methods":["mc","ideal","paypal"]},"8":{"amount":5000,"allowed_payment_methods":["ideal"]},"9":{"amount":10000,"allowed_payment_methods":["ideal"]}},"payment_methods":{"ideal":{"name":"ideal","allow_recurring":false},"paypal":{"name":"paypal","allow_recurring":false},"visa":{"name":"visa","allow_recurring":false},"mc":{"name":"mc","allow_recurring":false}}}"
What I want is to access it in the JS file like this:
success: function (data) {
alert(data.user_id);
}
But I don't know how to convert(?) it properly.
And my next step(question) after that will be if I can do a for loop for every purchased pack, so I can create button for each one of them
Probably something like this:
var pack;
var packs = data.purchase_packs;
for (pack= 0; pack < packs.length; pack++) {
console.log(packs[pack]);
}
I'm tried to understand your "question"....
In js:
$.post('/some/url',{query: 'somequery'},
function (data) {
try {
data = JSON.parse(data);
} catch (e) {
return false;
}
console.log(data);
});
In PHP:
data = json_decode(rtrim($myJSONEncodedString, "\0"));
if (!empty($data->purchase_packs)
foreach ($data->purchase_packs as $key => $value)
var_dump($value);
After receiving response using cURL, just echo that json string between <script></script> tag.
Then json string will look like:
<script>
var jsondata = {"user_id":1,"currency":"eur","purchase_packs":{"1":{"amount":500,"allowed_payment_methods":["ideal","paypal","visa","mc"]},"3":{"amount":1000,"allowed_payment_methods":["mc","ideal","paypal","visa"]},"6":{"amount":2500,"allowed_payment_methods":["mc","ideal","paypal"]},"8":{"amount":5000,"allowed_payment_methods":["ideal"]},"9":{"amount":10000,"allowed_payment_methods":["ideal"]}},"payment_methods":{"ideal":{"name":"ideal","allow_recurring":false},"paypal":{"name":"paypal","allow_recurring":false},"visa":{"name":"visa","allow_recurring":false},"mc":{"name":"mc","allow_recurring":false}}};
</script>
Then, your javascript code between <script></script>. Like this:
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
alert(jsondata.user_id); // return user_id value
jQuery.each(jsondata.purchase_packs, function(i, val) {
alert(val.amount); // return amount
var paymentMethod = val.allowed_payment_methods;
jQuery.each(paymentMethod, function() {
alert(this); // will return all payment gateway method
});
});
</script>
Hope will help!
My script currently looks like this:
<script type="text/javascript">
function updateMe(){
var x = 0;
var jsonstr = '{"date":"July 4th", "event":"Independence Day"}';
var activity=JSON.parse(jsonstr);
while(x<10){
date = document.getElementById("date"+x).innerHTML = activity.date;
event = document.getElementById("event"+x).innerHTML = activity.event;
x++;
}
}
</script>
Where date"x" and event"x" are a series of html tags. This function runs when the page loads (onload). My goal is to do this exact same thing, only from a local .json file as opposed to the hard code that I've got above. I've already checked out http://api.jquery.com/jQuery.getJSON/.
The local .json file looks like this:
{"date":"July 4th", "event":"Independence Day"}
Any suggestions?
Assuming you mean "file on a local filesystem" when you say .json file.
You'll need to save the json data formatted as jsonp, and use a file:// url to access it.
Your HTML will look like this:
<script src="file://c:\\data\\activity.jsonp"></script>
<script type="text/javascript">
function updateMe(){
var x = 0;
var activity=jsonstr;
foreach (i in activity) {
date = document.getElementById(i.date).innerHTML = activity.date;
event = document.getElementById(i.event).innerHTML = activity.event;
}
}
</script>
And the file c:\data\activity.jsonp contains the following line:
jsonstr = [ {"date":"July 4th", "event":"Independence Day"} ];
NOTICE: AS OF JULY 12TH, 2018, THE OTHER ANSWERS ARE ALL OUTDATED. JSONP IS NOW CONSIDERED A TERRIBLE IDEA
If you have your JSON as a string, JSON.parse() will work fine. Since you are loading the json from a file, you will need to do a XMLHttpRequest to it. For example (This is w3schools.com example):
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = myObj.name;
}
};
xmlhttp.open("GET", "json_demo.txt", true);
xmlhttp.send();
<!DOCTYPE html>
<html>
<body>
<h2>Use the XMLHttpRequest to get the content of a file.</h2>
<p>The content is written in JSON format, and can easily be converted into a JavaScript object.</p>
<p id="demo"></p>
<p>Take a look at json_demo.txt</p>
</body>
</html>
It will not work here as that file isn't located here. Go to this w3schools example though: https://www.w3schools.com/js/tryit.asp?filename=tryjson_ajax
Here is the documentation for JSON.parse(): https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
Here's a summary:
The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.
Here's the example used:
var json = '{"result":true, "count":42}';
obj = JSON.parse(json);
console.log(obj.count);
// expected output: 42
console.log(obj.result);
// expected output: true
Here is a summary on XMLHttpRequests from https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest:
Use XMLHttpRequest (XHR) objects to interact with servers. You can retrieve data from a URL without having to do a full page refresh. This enables a Web page to update just part of a page without disrupting what the user is doing. XMLHttpRequest is used heavily in Ajax programming.
If you don't want to use XMLHttpRequests, then a JQUERY way (which I'm not sure why it isn't working for you) is http://api.jquery.com/jQuery.getJSON/
Since it isn't working, I'd try using XMLHttpRequests
You could also try AJAX requests:
$.ajax({
'async': false,
'global': false,
'url': "/jsonfile.json",
'dataType': "json",
'success': function (data) {
// do stuff with data
}
});
Documentation: http://api.jquery.com/jquery.ajax/
You can do it like...
Just give the proper path of your json file...
<!doctype html>
<html>
<head>
<script type="text/javascript" src="abc.json"></script>
<script type="text/javascript" >
function load() {
var mydata = JSON.parse(data);
alert(mydata.length);
var div = document.getElementById('data');
for(var i = 0;i < mydata.length; i++)
{
div.innerHTML = div.innerHTML + "<p class='inner' id="+i+">"+ mydata[i].name +"</p>" + "<br>";
}
}
</script>
</head>
<body onload="load()">
<div id= "data">
</div>
</body>
</html>
Simply getting the data and appending it to a div... Initially printing the length in alert.
Here is my Json file: abc.json
data = '[{"name" : "Riyaz"},{"name" : "Javed"},{"name" : "Arun"},{"name" : "Sunil"},{"name" : "Rahul"},{"name" : "Anita"}]';
Actually, you are looking for the AJAX CALL, in which you will replace the URL parameter value with the link of the JSON file to get the JSON values.
$.ajax({
url: "File.json", //the path of the file is replaced by File.json
dataType: "json",
success: function (response) {
console.log(response); //it will return the json array
}
});
Instead of storing the data as pure JSON store it instead as a JavaScript Object Literal;
E.g.
window.portalData = [
{
"kpi" : "NDAR",
"data": [15,152,2,45,0,2,0,16,88,0,174,0,30,63,0,0,0,0,448,4,0,139,1,7,12,0,211,37,182,154]
},
{
"kpi" : "NTI",
"data" : [195,299,31,32,438,12,0,6,136,31,71,5,40,40,96,46,4,49,106,127,43,366,23,36,7,34,196,105,30,77]
},
{
"kpi" : "BS",
"data" : [745,2129,1775,1089,517,720,2269,334,1436,517,3219,1167,2286,266,1813,509,1409,988,1511,972,730,2039,1067,1102,1270,1629,845,1292,1107,1800]
},
{
"kpi" : "SISS",
"data" : [75,547,260,430,397,91,0,0,217,105,563,136,352,286,244,166,287,319,877,230,100,437,108,326,145,749,0,92,191,469]
},
{
"kpi" : "MID",
"data" : [6,17,14,8,13,7,4,6,8,5,72,15,6,3,1,13,17,32,9,3,25,21,7,49,23,10,13,18,36,9,12]
}
];
You can then do the following in your HTML
<script src="server_data.js"> </script>
function getServerData(kpiCode)
{
var elem = $(window.portalData).filter(function(idx){
return window.portalData[idx].kpi == kpiCode;
});
return elem[0].data;
};
var defData = getServerData('NDAR');