2

I make an AJAX request:

   function getdbsite(wantedid) {
      alert(wantedid);
      $.ajax({
         url: 'public/xml/xml_getdbsite.php',
         dataType: 'text',
         data: {"wantedid": wantedid},
         type: 'POST',
         success: function (data) {
            resultObj = eval(data);
            site=resultObj[0];
           // alert(site->language);  }These cause errors
           // alert(site->name);      }
            reply=resultObj[1];
         }
      });
   }

The server side PHP:

<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
require_once '../../includes/initialize.php';
header("Content-Type: application/json");
$id=$_POST['wantedid'];
$site = Website::find_by_id($id);
if($site){
   $arr[0] = $site;
   $arr[1] = "OK";
}else {
   $arr[0] = "$id";
   $arr[1] = "Failed";
}
$arr = json_encode($arr);
echo("$arr");

AJAX responce: [{"id":"19","idlanguage":"1","name":"QI"},"OK"]

But I am unable to access the db row.

I have searched and found: Parse PHP array of objects with jQuery Ajax

but do not understand the answers, their examples only have 1 field. Please help.

Community
  • 1
  • 1
  • `dataType: 'text',` <-- jquery already can convert `json` string into an object for you if you specify the `json` `dataType` – zerkms Oct 13 '14 at 00:20
  • `alert(site->language); }These cause errors` <--- that's expected, there is no `->` operator in javascript. – zerkms Oct 13 '14 at 00:21

1 Answers1

2

I strongly suggest don't use eval() function for this.

Instead, explicitly set that you are going to receive JSON from the server:

dataType: 'JSON',

Example:

PHP:

if($site){
   $arr['data'] = $site;
   $arr['message'] = "OK";
}else {
   $arr['data'] = $id;
   $arr['message'] = "Failed";
}

echo json_encode($arr);
exit;

JS:

$.ajax({
    url: 'public/xml/xml_getdbsite.php',
    dataType: 'JSON',
    data: {"wantedid": wantedid},
    type: 'POST',
    success: function(response) {

        // use dot notation not -> arrow notation
        var data = response.data;
        var message = response.message;
        alert(message);

        alert(data.id);
        alert(data.idlanguage);

    }
});
Kevin
  • 41,694
  • 12
  • 53
  • 70