4

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

1
  • 2
    You have a typo in repose.string Commented Nov 30, 2016 at 0:36

2 Answers 2

3

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 );
               ^^
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks the header fixed it the grammar errors were only from me typing it . I never knew of typeof in js thanks
@Dustin sure glad this helped
0

Well, it is a grammatical errors. The request option

datatype: 'json' 

should be

dataType: 'json'

1 Comment

Thanks that is something I've overlooked

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.