Tuesday, February 14, 2012

Including a file in json_encode()


Thsi does not seem to work:




$msg="Your changes have been saved successfully";

$view=include('application/view/admin/cms/_slides-current.php');

$return_array=array('success'=>true, 'msg'=>$msg, 'view'=>$view);

echo json_encode($return_array);



The array needs to be passed back to a jQuery ajax success callback. Anybody know how it should be done?



The include file is simply a HTML template. This HTML template will be inserted on to the page.



Is there any way other than using json_encode() to do what I am trying to do?




success: function(result){
alert(result.msg);

if(result.success == true)
{
$('#slides').html(result.view);
}
}

3 comments:

  1. include is a statement and not a function (disregard the function.include.php part). It will not return the parsed result to your $view variabe, although the file will be included just above your json_encode.

    You should use ob_start to capture the evaluated result of the view in the manner described by mihneasime:

    ob_start();
    include 'application/view/admin/cms/_slides-current.php';
    $view = ob_get_clean();

    ReplyDelete
  2. ob_start();
    include 'application/view/admin/cms/_slides-current.php';
    $view = ob_get_clean();


    Should do the trick as joar suggested.

    ReplyDelete
  3. Use fopen and friends to read files. include is for including them.

    ReplyDelete