user2417624
user2417624

Reputation: 693

json string shown in console, but the php variable print null

I have the following peace of javascript:

$('.showEditForm').click(function () {
    var webpagefileID = this.id;
    if($('#editForm').css('display', 'none')) {
        $('#editForm').css('display','block');
        $('#allFilesTable').css('display','none');
    }    
    $.post
    ('http://localhost/myproject/Controllername/display_edit_record_form', { webpagefileID: webpagefileID }, function(result) {

    });       
});

Using the post, I am calling method display_edit_record_form in my Codeigniter Controller

Here is the code of the method named display_edit_record_form in my CodeIgniter Controller:

public function display_edit_record_form($webpagefileID) {
    $webpagefileID = $this->input->post('webpagefileID');
    $data['webpagefile'] = $this->Webpage_file_model->get($webpagefileID);
    //$this->output->set_content_type('application/json');
    $this->output->set_output(json_encode($data['webpagefile']));
    echo json_encode(array("message" => $data['webpagefile'] ));
}

In the php view, I am trying to display the data with following code:

var_dump($message);
echo "<br />";
$myarr1 = json_decode($message);
print_r($myarr1);
echo "<br />";
$myarr2 = json_decode($data['webpagefile']);
print_r($myarr2);
echo "<br />";
$myarr3 = json_decode($webpagefile);
print_r($myarr3);

And I get one NULL and 2 empty arrays In the console however I can see this:

Now, in the console, when the edit form is opened, I can see the json string

{"message":
    {"webpagefileID":"10",
    "webpageID":"38",
    "webpagefileName":"New file",
    "webpagefileShowInRelatedFiles" :"1",
     .......continues.....

I need help to display this string in my php code in the view, so I can populate my form fields there....

Upvotes: 1

Views: 139

Answers (2)

Sayantan Das
Sayantan Das

Reputation: 1641

That is because the output you are getting from display_edit_record_form() method is received in ajax. So your $message variable is showing blank. What you need to do is after receiving the data from the post request, update your view using jquery.

$.post
    ('http://localhost/myproject/Controllername/display_edit_record_form', { webpagefileID: webpagefileID }, function(result) {
        result = $.parseJSON(result);
        // considering you have a text field with id myID
        $('#myID').val(result.message.webpagefileID);
        // similarly you can add any of your returned values
    });

Upvotes: 1

vikkio
vikkio

Reputation: 91

when json_decode() result is null it means that the parsing was unsuccessful (usually is because of the string enconding). You should be able to see the errorCode printing the output of json_last_error

Upvotes: 0

Related Questions