gANDALF gANDALF - 2 years ago 117
PHP Question

Cant access json encoded data in ajax success function returned from php

I am returning json encoded data from php to ajax success function ,here is the code

<?php
if ($run) {
$response=array();
$response['email']=$email;
$response['name']=$name;
echo json_encode($response);
exit();

}

?>


I want to access this data through ajax success function ,this is what I have tried

<script type="text/javascript">
$("#contact-form").submit(function(e){
e.preventDefault();

if (check()) {



$.ajax({
url: 'reguser.php',
async: true,
cache: false,
data: $('#contact-form').serialize(),
type:'post',
success: function (result) {
var json = result;
obj = JSON.parse(json);

alert(obj.email);


}




});
}
});

</script>


how to retrieve email and name ,I echoed in backend php..

Answer Source

You have to set that the return data is json, this should work

$.ajax({
        url: 'reguser.php',
        async: true,
        cache: false,
        data: $('#contact-form').serialize(),
        type:'post',
        dataType:'json',
        success: function (result) {     
          alert(result.email);
           }
      });
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download