Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning php associative array from function to ajax call with json_encode() not and object

This is my first post so i apologize if i leave something out or don't explain myself very well. All this code is in the same php file

My ajax call

$.ajax(
{
    type: "POST",
    url: window.location.href,
    data: {func: 'genString'},
    datatype: 'json'
})
.done(function ( response )
{
    console.log( response );
    console.log( repose.string );
});

Which falls into an if statement on the page

if ( isset ($_POST['func'] && $_POST['func'] == 'genString')
{
     exit(json_encode(myFunction()));
}

The function run on the page

function myFunction()
{
    /* Would generate a string based on the database */
    $arr = array('rows' => 1, 'string' => 'My test string');
    // Changes values in the array depending on the database
    return $arr;
}

This function is run to generate the array when the page itself is loaded and use the string portion to display the it and the rows part to set the height of a text area in the browser however when the ajax is called console.log(respose) this logs {"rows":1,"string":"My test string"} instead of an object

However when i try logging or using the string console.log( response.string ); it shows up as undefined

I have done this previously and it has worked and returned an object which i can use in js with response.string. I have tried to use JSON_FORCE_OBJECT this had no effect on the result

like image 536
Dustin Avatar asked Sep 14 '25 05:09

Dustin


1 Answers

Right now, the response is just being treated as a string (datatype). That's why response.string isn't working.

You can just tell by adding this:

console.log( typeof response );

So don't forget to put:

header('Content-Type: application/json');

Inside you if block:

And you have a typo on the if block (isset and response):

if ( isset ($_POST['func']) && $_POST['func'] === 'genString' ) {
    header('Content-Type: application/json');
    exit(json_encode(myFunction()));
}

On the JS typo also:

console.log( response.string );
               ^^
like image 89
Kevin Avatar answered Sep 17 '25 06:09

Kevin