Steven Jacks
Steven Jacks

Reputation: 413

Returning json data from php to ajax

I'm trying to get a json object from php so I can work with it in ajax. Here is my ajax code:

 $.ajax({
   type: 'get',
   url: eventsListPath,
   dataType : "json",
   data: {},
   success: function (data) {
       $('#eventInformation').html(data.table);
       alert(data.table);
   }
});

And my PHP:

$obj->table="hey";
echo json_encode($obj, JSON_UNESCAPED_SLASHES);

But the line

alert(data.table);

comes back with 'undefined'. Any ideas?

Upvotes: 5

Views: 1538

Answers (4)

jinglebird
jinglebird

Reputation: 578

you must pass array to json_encode not object

<?php
$array['table'] = "hey";
echo json_encode($array, JSON_UNESCAPED_SLASHES);

Upvotes: 0

Voro
Voro

Reputation: 66

<?php
$obj = new stdClass();
$obj->table="hey";
echo json_encode($obj)

produces

{"table":"hey"}

Check it using Firebug. Also check the content-type, should be Content-Type: application/json

Upvotes: 0

Kamuran S&#246;necek
Kamuran S&#246;necek

Reputation: 3333

if I'm not mistaken, json_encode just works for arrays

$obj = [{table:"hey"}];

Upvotes: 1

Harish Lalwani
Harish Lalwani

Reputation: 774

Try this in your php code. Json encode an array.

$obj['table']="hey";
echo json_encode($obj, JSON_UNESCAPED_SLASHES);

Alternate - Or your class should be like this

class your_classname
{
  public $table;
 //other class related code
}
$obj = new your_classname;

$obj->table="hey";
echo json_encode($obj, JSON_UNESCAPED_SLASHES);

Upvotes: 1

Related Questions