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
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 );
^^
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With