5

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?

1
  • Try console.log(data) in success. Tell me the result. Commented Aug 10, 2015 at 6:59

4 Answers 4

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

please do mark my answer as correct if the code helped you. thanks @Steven Jacks
1

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

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

Comments

0
<?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

Comments

0

you must pass array to json_encode not object

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.