sebastiano
sebastiano

Reputation: 31

I can't receive data in JS from my PHP file

I've been trying receive information with AJAX,JS,JSON and PHP. The context is the following:

I have a JS file, i sending from this file an id, that it receive a PHP file and this file makes some queries, of which the data is stored in an object and sent to a JS file to update some attributes of HTML. I can send the id from JS to PHP correctly. Then, i've checked that i can pass the information from the queries information to an PHP object correctly too.

Here's the problem...when i receive the data in the JS file and this information pass to the eval() function, it give me an error.

Notes:

infoAction.php

<?php
  include 'sitioTuristico.php';

    $id = $_GET['id'];

    $sitio = new sitioTuristico("SI01");

    if($sitio->getID_SI()=="INEX"){
      print "The place doesn't exist";
      exit;
    }

    $response = new stdClass();

    $response->ID_SI = $sitio->getID_SI();
    $response->URL = $sitio->getURLS();
    $response->Nombre = $sitio->getNombre();
    $response->Descripcion = $sitio->getDescripcion();
    $response->Promedio_nota = $sitio->getPromedio_Nota();
    $response->Nombre_Cat = $sitio->getNombre_Cat();
    $response->Nombre_Ciu = $sitio->getNombre_Ciu();


/* i tried this way too
    $arr =    array('ID_SI' => $sitio->getID_SI(),
                    'URL' => $sitio->getURLS(),
                    'Nombre'=> $sitio->getNombre(),
                    'Descripcion'=> $sitio->getDescripcion(),
                    'Promedio_nota'=> $sitio->getPromedio_Nota(),
                    'Nombre_Cat' => $sitio->getNombre_Cat(),
                    'Nombre_Ciu' => $sitio->getNombre_Ciu());
*/
    echo json_encode($response);

?>

info-turistica-info.js

$(document).ready(function(){
  $.ajax({
    type: "GET",
    url: "php/indexAction.php",
    data: { id:loadData() },
    async: true,
    success: function(datos){

        var dataJson = eval(datos); **//here throws an error**
        alert(datos); **//It print all the information correctly**
        alert(datos.ID_SI); **//It print "undefined"**

        $('img[name=imagenPrincipal]').attr("src",dataJson[i].URL[0]);
        $('img[name=imagenPrincipal]').attr("id",dataJson[i].ID_SI);

    },

Upvotes: 1

Views: 64

Answers (2)

undone
undone

Reputation: 7888

First, use JSON.parse(datos); instead of eval. Secondly, You need to use something like this:

   $('img[name=imagenPrincipal]').prop("src",dataJson.URL);
   $('img[name=imagenPrincipal]').prop("id",dataJson.ID_SI);

Upvotes: 1

HenryDev
HenryDev

Reputation: 4953

You are using dataJson[i].URL[0] and you don't even have "i" defined anywhere. Also don't ever use eval because eval === evil according to Douglas Crockford. Use JSON.parse(datos) and then do this:

$('img[name=imagenPrincipal]').prop("src",dataJson.URL);
$('img[name=imagenPrincipal]').prop("id",dataJson.ID_SI);

Hope it helps!

Upvotes: 1

Related Questions