Getting json from an URL and displaying specific data - javascript

I got a problem when I try to get the json from an URL in my reverse geocoding method :
I tried this based on a solution found on stackoverflow.
When I try to show the json in my alert it shows: undefined
adressReverseGeoCode(item: any, elementId: any) {
var getJSON = (url: any, callback: any) => {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'json';
xhr.onload = () => {
var status = xhr.status;
if (status == 200) {
callback(null, xhr.response);
} else {
callback(status);
}
};
xhr.send();
};
getJSON('http://nominatim.openstreetmap.org/reverse?format=json&lat=' + item.latitude + '&' + 'lon=' + item.longitude + '&addressdetails=1',
(err: any, data: any) => {
if (err != null) {
alert('Something went wrong: ' + err);
} else {
alert(data.result);
}
});
}
I want to get the "display_name" from the json in order to put it in a text input later.
You can try this link to see the json file
{
"place_id":"154253419",
"licence":"Data © OpenStreetMap contributors, ODbL 1.0. http:\/\/www.openstreetmap.org\/copyright",
"osm_type":"way",
"osm_id":"424211755",
"lat":"-23.56183",
"lon":"-46.6598392",
"display_name":"Alameda Ministro Rocha Azevedo, Jardim Paulista, São Paulo, Microrregião de São Paulo, RMSP, Mesorregião Metropolitana de São Paulo, São Paulo, Southeast Region, 01410-001, Brazil",
"address":{"road":"Alameda Ministro Rocha Azevedo","suburb":"Jardim Paulista","city_district":"Jardim Paulista","city":"São Paulo","county":"Microrregião de São Paulo","state_district":"Mesorregião Metropolitana de São Paulo","state":"São Paulo","postcode":"01410-001","country":"Brazil","country_code":"br"},
"boundingbox":["-23.5642064","-23.5601209","-46.662319","-46.6580485"]
}
Thank you in advance for any help you can give me !

There is not data.result! thats why it is undefined. Your data is the JSON. so just do data.display_name. Probably!
var obj = JSON.parse(data); // as suggested by #charlietfl
console.log(obj.display_name);
alert(obj.display_name);

Related

How could I cast to DateTimeInterface from String?? Symfony Ajax

My real problem is that I am sending an Ajax Jquery Request to an API of mine, the server response is 'Argument #1 of ::setDate() must be DateTimeInterface, string given'
I tried to cast but it was useless.
My Ajax at JQUERY:
$.ajax({
type: "PUT",
url: "/api/distribucion",
data: JSON.stringify(dist),
dataType: "json",
success: function (response) {
console.log("mesa " + response.id + " actualizada");
}
});
My API at PHP (Symfony's controller):
public function putDistribucion(ManagerRegistry $mr, Request $request): Response
{
$datos = json_decode($request->getContent());
$datos = $datos->distribucion;
// Cogemos el ID de el Distribucion a editar
$id = $datos->id;
// Obtenemos el Distribucion
$distribucion = $mr->getRepository(Distribucion::class)->find($id);
// Cambiamos todos sus campos
$distribucion->setPosicionX($datos->pos_x);
$distribucion->setPosicionY($datos->pos_y);
$distribucion->setFecha($datos->fecha);
$distribucion->setMesaId($datos->mesa_id);
$distribucion->setAlias($datos->alias);
$distribucion->setReservada($datos->reservada);
$manager = $mr->getManager();
try {
// Lo mandamos a actualizar
$manager->persist($distribucion);
$manager->flush();
} catch (PDOException $e) {
$this->json(['message' => $e->getMessage(), "Success" => false], 400);
}
# Creado con éxito => Devolvemos la ID
return $this->json(
[
"message" => "Éxito al editar la distribucion " . $id,
"Success" => true
],
202 // Aceptado
);
}
The Object I'm sending:
Your entity Distribucion probably has a setter that look like this:
public function setFecha(DateTimeInterface $fecha): self
{
$this->fecha = $fecha;
return $this;
}
The setter is typehinted with DateTimeInterface so you need to use a DateTime object and not a string.
You may create a DateTime easily with DateTime::createFromFormat
So $distribucion->setFecha($datos->fecha); will turn into something like:
$distribucion->setFecha(DateTime::createFromFormat('YYYY-MM-DD HH:ii:ss.u', $datos->fecha));
You may want to verify the date format I used as the first parameter of DateTime::createFromFormat
public static DateTime::createFromFormat(string $format, string $datetime, ?DateTimeZone $timezone = null)

I can't create a file download controller

When I try to use the .pipe() function in my controller I get an error and I don't know why. Attached my code below, thank you very much for the help in advance
const fs =require('fs');
module.exports={
inputs:{
name_file:{
type:"string",
required:true
}
},
exits: {
success: {
description: "Return matching data.",
},
defaultError: {
description: "It catches any error.",
responseType: "defaultError",
},
},
fn:function (inputs,exits){
//Comprobamos si el fichero viene en la peticion
if (!inputs.name_file) return exits.defaultError("No se ha adjuntado el nombre del archivo")
var nameFile=inputs.name_file
//Creamos ruta completa del fichero
var URL_FILE=process.cwd()
URL_FILE= URL_FILE.concat("\\.tmp\\uploads\\",nameFile,'.csv')
//Comprobamos si el fichero existe
fs.access(URL_FILE,fs.constants.F_OK,(err)=>{
return "El fichero no existe"
})
var response={}
var SkipperDisk = require('skipper-disk');
var fileAdapter = SkipperDisk(/* optional opts */);
// Stream the file down
var filedown=fileAdapter.read(URL_FILE)
filedown.on('error', function (err){
return exits.defaultError(err);
})
filedown.on('line',(linea)=>{
console.log(linea)
})
filedown.pipe(exits.success(response))
}
}
TypeError: Cannot read property 'on' of undefined```

VueJS doesn't work on mobile

I have a problem with running VueJS on mobile devices. I created a weather prediction app on copepen.io
Here is the link for the project:
http://codepen.io/techcater/pen/xOZmgv
HTML code:
<div class="container-fluid text-center">
<h1>Your Local Weather</h1>
<p>
{{location}}
</p>
<p>
{{temperature}}
<a #click="changeDegree">{{degree}}</a>
</p>
<p>
{{weather | capitalize}}
</p>
<img :src="iconURL" alt="" />
<br>
by Dale Nguyen
<!-- <pre>{{$data | json}}</pre> -->
</div>
JS code:
new Vue({
el: '.container-fluid',
data: {
location: "",
temperature: "",
degree: "C",
weather: "",
iconURL: ""
},
created: function(){
this.getWeather();
},
methods: {
getWeather: function(){
var that = this;
this.$http.get("http://ipinfo.io").then((response) => {
console.log(response.data);
that.location = response.data.city + ", " + response.data.country;
// Get weather informaiton
var api = 'ebd4d312f85a230d5dc1db91e20c2ace';
var city = response.data.city;
var url = "http://api.openweathermap.org/data/2.5/weather?q={CITY}&APPID={APIKEY}&units=metric";
url = url.replace("{CITY}",city);
url = url.replace("{APIKEY}", api);
that.$http.post(url,{dataType: 'jsonp'},{
headers : {
'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
}}).then((response) => {
console.log(response.data);
that.temperature = response.data.main.temp;
that.weather = response.data.weather[0]['description'];
that.iconURL = "http://openweathermap.org/img/w/" + response.data.weather[0]['icon'] + ".png";
}, (response) => {
// error callback
});
}, (response) => {
console.log(response.data);
});
},
changeDegree: function() {
if(this.degree == "C"){
this.degree = "F";
this.temperature = Math.round((this.temperature*9/5 + 32)*100)/100;
}else {
this.degree = "C";
this.temperature = Math.round(((this.temperature - 32)*5 /9)* 100)/100;
}
}
}
})
It works well on my laptop but not on mobile. At first, I thought that it is because of Codepen. It may cause something when running through the site. However, when I created a project on my website, it also doesn't work.
Can you help to find the issue? Thanks,
Your code seems to be working well, except that on codepen it gives me error XMLHttpRequest cannot load http://ipinfo.io/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://s.codepen.io' is therefore not allowed access..
You can put your domain name on headers options to enable cross-origin, here is example:
this.$http.get('http://ipinfo.io', {
'headers': {
'Origin': 'http://yourdomain.com'
}
})
See example: http://bozue.com/weather.html
I also noticed you put vue.min.js and vue-resource.js scripts in wrong order that might trigger some error, vue.min.js should be on the first place.
I found a solution for this. I works on my mobile now. I believe that I will work on other browses too. The problem is that some browsers doesn't recognize the operation ">", so I changed it.
Here is the new code:
getWeather: function(){
var that = this;
this.$http.get('http://ipinfo.io', {'headers': {
'Origin': 'http://yourdomain.com'}
}).then(function(response) {
console.log(response.data);
that.location = response.data.city + ", " + response.data.country;
// Get weather informaiton
var api = 'ebd4d312f85a230d5dc1db91e20c2ace';
var city = response.data.city;
var url = "https://crossorigin.me/http://api.openweathermap.org/data/2.5/weather?q={CITY}&APPID={APIKEY}&units=metric";
url = url.replace("{CITY}",city);
url = url.replace("{APIKEY}", api);
that.$http.post(url,{dataType: 'jsonp'},{
headers : {
'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
}}).then(function(response) {
console.log(response.data);
that.temperature = response.data.main.temp;
that.weather = response.data.weather[0]['description'];
that.iconURL = "http://openweathermap.org/img/w/" + response.data.weather[0]['icon'] + ".png";
}).then(function(){
// error callback
});
}).then(function(){
console.log(response.data);
});
},

Deal with the result of postJSON

I'm trying to implement something with jQuery and Vue.js:
And here is my script part:
<script>
function initVM(result) {
// alert(result.num)
var vm2 = new Vue({
el: '#vm2',
data: {
// ③bind one item of the result as example
rrr: result.num
}
});
$('#vm2').show();
}
$(function() {
var vm = new Vue({
el: '#vm',
data: {
content: ''
},
methods: {
submit: function(event) {
event.preventDefault();
var
$form = $('#vm'),
content = this.content.trim();
// ①post textarea content to backend
$form.postJSON('/api/parse', {
content: content
}, function(err, result) {
if (err) {
$form.showFormError(err);
}
else {
// ②receive a result dictionary
$('#vm').hide();
initVM(result);
}
});
}
}
});
});
</script>
Here is my html part:
<html>
<form id="vm", v-on="submit: submit">
<textarea v-model="content" name="content"></textarea>
<button type="submit">Have a try!</button>
</form>
<div id="vm2" style="diplay:none;">
<!-- ④show the result-->
The result:
{{ rrr }}
</div>
</html>
Here is the definition of postJSON
<script>
// ...
postJSON: function (url, data, callback) {
if (arguments.length===2) {
callback = data;
data = {};
}
return this.each(function () {
var $form = $(this);
$form.showFormError();
$form.showFormLoading(true);
_httpJSON('POST', url, data, function (err, r) {
if (err) {
$form.showFormError(err);
$form.showFormLoading(false);
}
callback && callback(err, r);
});
});
// ...
// _httpJSON
function _httpJSON(method, url, data, callback) {
var opt = {
type: method,
dataType: 'json'
};
if (method==='GET') {
opt.url = url + '?' + data;
}
if (method==='POST') {
opt.url = url;
opt.data = JSON.stringify(data || {});
opt.contentType = 'application/json';
}
$.ajax(opt).done(function (r) {
if (r && r.error) {
return callback(r);
}
return callback(null, r);
}).fail(function (jqXHR, textStatus) {
return callback({'error': 'http_bad_response', 'data': '' + jqXHR.status, 'message': 'something wrong! (HTTP ' + jqXHR.status + ')'});
});
}
</script>
The process can be described as:
Post the content to backend
Receive the result and hide the form
Create a new Vue with the result
Show the result in a div which is binding with the new Vue instance
Actually, I do receive the result successfully, which is proved by the alert(result.num) statement, but nothing find in vm2's div except The result:
Where is the problem? Or please be free to teach me a simpler approach if there is, because I don't think what I am using is a good one.
Here's questioner.
Finally I found where is the problem.
The problem lays in Mustache: {{ }}
I use jinja2, a template engine for Python and Vue.js, a MVVM frontend framework. Both of them use {{ }} as delimiters.
So if anyone got trapped in the same situation with me, which I don't think there will be, please:
app.jinja_env.variable_start_string = '{{ '
app.jinja_env.variable_end_string = ' }}' # change jinjia2 config
OR
Vue.config.delimiters = ['${', '}'] # change vue config

POST 500 (Internal Server Error) when I use the JEditable plugin

I'm trying to use JEditable plugin in my Symfony2 application. PYS entity is a a films and TV shows entity; then I've got Usuario and Critica entities. I want to manage the user's critics with the plugin. I've analyzed more and more examples, but I can not get it to work. The value (in this case the title of critic) is update in the template but not in the db; when I refresh the browser the old value appears.
THE ERROR:
This is my JS:
$('.edit').editable(function(value, settings) {
var data = {};
data[this.id] = value;
console.log(path);
console.log(data);
$.post(path, data);
return(value);
}, {
indicator : 'Saving...',
tooltip : 'Click to edit...'
});
This is the route:
critica_ajax:
locales: { es: "/gestion-critica/{pysStr}/", en: "/manage-critic/{pysStr}/" }
defaults: { _controller: UsuarioBundle:Default:gestionarCritica }
This is the controller:
public function gestionarCriticaAction($pysStr)
{
$em = $this->getDoctrine()->getManager();
$pys = $em->getRepository('PYSBundle:Pys')->findPys($pysStr);
$usuario = $this->get('security.context')->getToken()->getUser();
$critica = $em->getRepository('UsuarioBundle:Usuario')->findCritica($usuario, $pys);
if(!$critica)
{
$critica = new Critica($usuario, $pys);
}
$criTitulo = $this->request->get('value');
$critica->setCriTitulo($criTitulo);
$critica->setCriContenido($criContenido);
$critica->setCriFecha(new \DateTime("now"));
$em->persist($critica);
$em->flush();
return new Response($criTitulo);
}
The Twig template:
<h2 class="edit">{{ critica.criTitulo }}</h2>
<script>
var path = "{{ path('critica_ajax', { 'pysStr': pelicula.pysStr}) }}";
</script>
EDIT (The Symfony's return)
Notice: Undefined property: Filmboot\UsuarioBundle\Controller\DefaultController::$request
in C:\Programming\xampp\htdocs\filmboot\src\Filmboot\UsuarioBundle\Controller\DefaultController.php line 236
THIS IS THE LINE 236: $criTitulo = $this->request->get('value');
at ErrorHandler ->handle ('8', 'Undefined property: Filmboot\UsuarioBundle\Controller\DefaultController::$request', 'C:\Programming\xampp\htdocs\filmboot\src\Filmboot\UsuarioBundle\Controller\DefaultController.php', '236', array('pysStr' => 'machete', 'em' => object(EntityManager), 'pys' => object(Pys), 'usuario' => object(Usuario), 'critica' => object(Critica)))
in C:\Programming\xampp\htdocs\filmboot\src\Filmboot\UsuarioBundle\Controller\DefaultController.php at line 236 +
at DefaultController ->gestionarCriticaAction ('machete')
at call_user_func_array (array(object(DefaultController), 'gestionarCriticaAction'), array('machete'))
in C:\Programming\xampp\htdocs\filmboot\app\bootstrap.php.cache at line 1003 +
at HttpKernel ->handleRaw (object(Request), '1')
in C:\Programming\xampp\htdocs\filmboot\app\bootstrap.php.cache at line 977 +
at HttpKernel ->handle (object(Request), '1', true)
in C:\Programming\xampp\htdocs\filmboot\app\bootstrap.php.cache at line 1103 +
at ContainerAwareHttpKernel ->handle (object(Request), '1', true)
in C:\Programming\xampp\htdocs\filmboot\app\bootstrap.php.cache at line 413 +
at Kernel ->handle (object(Request))
in C:\Programming\xampp\htdocs\filmboot\web\app_dev.php at line 26 +
You need to get the request like this :
$request = $this->getRequest();
instead of
$request = $this->request;
the request is returned using a method its not a class property

Categories