-2

Possible Duplicate:
Sending JSON jQuery Ajax to PHP and back

i need to send the following object to a php file i tried it through json stringify but could not do it .i dont want to change the format in which these attributes are already defined and also is json the only way to send such objects? i wand to do something like this

function contact()
{
contact.menu=null;
contact.access=null;
contact.state=null;
}
$.post("myfile.php",{contact:contact},function(data){alert(data);});
///php code
$contact= $_POST['contact'];
echo $contact['menu'];  

thanks in advance

Community
  • 1
  • 1
user1542
  • 49
  • 1
  • 9

2 Answers2

4

JavaScript:

var contact = {
    menu: null,
    access: null,
    state: null
};
$.post("myfile.php", {contact: contact}, function(data) { 
    alert(data);
});

PHP:

$contact = $_POST['contact'];
echo $contact['menu'];

UPDATE:

Answer to your question in comments:

var contact = {
    menu: null,
    state:  null,
    access: null,
    fill: function() {
        this.menu = 1; // $("div#sm").html(); 
        this.state = 2;
        this.access = 3;
    }
};

contact.fill();

$.post("myfile.php", {contact: contact}, function(data) { 
    alert(data);
});
Eugene Naydenov
  • 7,165
  • 2
  • 25
  • 43
  • i am changing the class attributes down the code like contact.menu=$("div#sm").innerhtml();so i dont want to change the format . can i do contact['menu']=$("div#sm").innerhtml(); using your code ?instead . ill try that right now! – user1542 Oct 01 '12 at 21:23
  • Check the update of my answer. Also there's a jQuery method `$.html()`, not `innerhtml`, as you're writing. – Eugene Naydenov Oct 01 '12 at 21:30
  • that innerhtml was just to tell you want i wanted and thanks for the answer .also figured that now anywhere in the code i can do contact['menu']=$("div#sm").html(); – user1542 Oct 01 '12 at 21:36
  • in php when im only getting the first index of the contact only menu and not echo $contact['access']; – user1542 Oct 01 '12 at 21:53
  • Yea, you can initialize object's property later. `var contact = {};` then: `contact.menu = $("div#sm").html();` or `contact['menu'] = $('div#sm');` – Eugene Naydenov Oct 02 '12 at 06:17
0

Object contact is supposed to be like this

 var contact = {
    menu :null,
    access:null,
    state:null
   }
Sushanth --
  • 55,259
  • 9
  • 66
  • 105