1

Using the method found here, I am collecting form values and posting them using the following code:

$.ajax({
    type: "POST",
    url: "http://"+document.domain+"/SimplaAdmin/includes/rpc.php",
    data: { data:postdata, method: 'addSite'},
    dataType: "json",
.......

Posted data is:

data:{
    "textfield": ["",""],
    "dropdown": ["option1","option1"],
    "siteTitle":"this is the site title",
    "siteKey":"",
    "siteurl":"",
    "address1":"",
    "address2":"",
    "address3":"",
    "landline":"",
    "method":"addSite",
    "small-input":"",
    "medium-input":"",
    "large-input":""
}

Then I try to get the value siteTitle using:

$data = $_POST['data'];
$obj=json_decode($data) ;
$title = $obj->{'siteTitle'};

But it does not work, where is the flaw in my thinking?

Community
  • 1
  • 1
maxum
  • 2,825
  • 4
  • 33
  • 49

3 Answers3

1

Your syntax is incorrect- You just need $title = $obj->siteTitle;

Also, I presume you added data: to the start of your JSON string for the purpose of this post? That also shouldn't be there.

Take for example:

<?php 

$string = '{"textfield":["",""],"dropdown":["option1","option1"],"siteTitle":"this is the site title","siteKey":"","siteurl":"","address1":"","address2":"","address3":"","landline":"","method":"addSite","small-input":"","medium-input":"","large-input":""}';

$obj = json_decode($string); 

print_r( $obj->siteTitle );

?>

Which outputs

this is the site title

Ben Swinburne
  • 25,669
  • 10
  • 69
  • 108
0

JSON was escaping the POST. Removed slashes and it worked.

maxum
  • 2,825
  • 4
  • 33
  • 49
-1

Change $title = $obj->{'siteTitle'} to

$title = $obj['siteTitle'];
max_
  • 24,076
  • 39
  • 122
  • 211
  • It's not an array though. You need to pass a second argument with `TRUE` if you want an array returned. – alex Oct 13 '11 at 00:19
  • This will not work as by default `json_decode` returns an object. This will result in a Fatal error: Cannot use object of type stdClass as array error – Ben Swinburne Oct 13 '11 at 00:21