Here, I want to encode php return in json output.I'm so confused to implement on there. So, how the correct way I have to do.
index.html
$(function(){
$.ajax({
type: 'GET',
url: "profile.php",
success: function(resp){
var username = JSON.parse(resp).username;
var profile = JSON.parse(resp).profile;
$('.test').html(username+profile );
}
});
});
profile.php
<?php
require_once('class.php');
?>
<?php
if ($user->is_logged == 1) {
$txtuser = '';
if (empty($D->me->firstname)) $txtuser = $D->me->username;
else $txtuser = $D->me->firstname;
if (empty($D->me->avatar)) $txtavatar = 'default.jpg';
else $txtavatar = $D->me->avatar;
}
?>
<?php
echo json_encode(array('username' => '{$C->SITE_URL.$D->me->username}', 'profile' => '{$txtuser}' ));
?>
clean it out this way, and let me know if you still have issues:
<?php
require_once('class.php');
if ($user->is_logged == 1) {
$txtuser = '';
if (empty($D->me->firstname)) $txtuser = $D->me->username;
else $txtuser = $D->me->firstname;
if (empty($D->me->avatar)) $txtavatar = 'default.jpg';
else $txtavatar = $D->me->avatar;
}
$arr = array(
"username" => $C->SITE_URL . $D->me->username,
"profile" => $txtuser
);
echo json_encode($arr);
?>
in your Ajax response use console.log(resp)
to see any errors in the console.
Set the dataType
option to json
, that way you will tell the jQuery that the data expected from the server is in JSON format, and jQuery will try to convert a JSON string into an object. It is not necessary manually do that with JSON.parse()
.
$.ajax({
type: 'GET',
url: "profile.php",
dataType: 'json',
success: function( resp ){
console.log( resp );
}
});
Use console.log()
to inspect the result ( Mozilla, Chrome ).
Another thing is that you should remove the quotation marks and just concatenate strings with dot ( PHP String Operators ). Also, there should not be any output before and after json_encode()
because it will break json string, su just use die().
die( json_encode( array( 'username' => $C->SITE_URL . $D->me->username, 'profile' => $txtuser ) ) );