views:

162

answers:

2

Hi there,

If someone could assist me please. I'm doing a jquery Ajax post, for some reason the Json object isn't working so just returning a php array instead

$.post
(  
  "classes/RegisterUser.php",  
  $("#frmRegistration").serialize(),  
  function(data)
  {  
   alert(data);  
  } 
);

The data is returned to Javascript 100% as

array
(
   [key]=>value
   [Name] => SomeOneName
   [Surname] => SomeOneSurName
)

How would i go about getting the value of Surname in Javascript?

Thanks for your assistance? Regards

A: 

Maybe your PHP script should return json (right now it seem to return something like var_dump($some_ary);. A proper way to do this is via php's json_encode.

The MYYN
I used the json_encode method which returns the databack 100%, when i then try to display the data in javascript as e.g. alert(data.Name);I get the error undefined?
+2  A: 

Expanding on The MYYN's answer, after you get your script to return JSON, you must specify that you're receiving JSON and act accordingly. You can do this with .ajax():

$.ajax({
    type: 'post',
    url: 'classes/RegisterUser.php',
    data: $("#frmRegistration").serialize(),
    dataType: 'json',
    success: function(obj) {
        // This alerts SomeOneSurName
        alert(obj.Surname);
    }
});
Tatu Ulmanen
Thanks Tatu, worked like a charm!