Reputation: 343
I'm trying to use my MYSQL result, I'm calling with PHP, in JavaScript.
My Code in the PHP-file:
$con = mysqli_connect($kalenderCFG['server'], $kalenderCFG['username'], $kalenderCFG['password'], $kalenderCFG['database'], $kalenderCFG['port']);
$strSQL = "SELECT DATE_FORMAT(`Datum`, '%d.%m.%Y') AS Datum, `Titel`, `Beschreibung` FROM `cal` WHERE month(`Datum`) = '" . $month . "' AND year(`Datum`) = '" . $year . "' ORDER BY `Datum`";
$result = mysqli_query($con, $strSQL);
$data = array();
while ($row = mysqli_fetch_assoc($result)){
$data[] = $row;
}
echo json_encode($data);
That's working fine so e.g. I get the following
[{"Datum":"02.12.2014","Titel":"Mathe KA","Beschreibung":"ABI-Vorklausur"},{"Datum":"12.12.2014","Titel":"Physik KA","Beschreibung":"ABI-Vorklausur"},{"Datum":"13.12.2014","Titel":"Mein erster Termin","Beschreibung":"Das ist einfach nur ein Testeintrag um die Funktion zu testen."}]
When I now try to use this Code in JavaScript by the following Code:
var json = String($.get('myPhpFile.php'));
listEvents = JSON && JSON.parse(json) || $.parseJSON(json);
$('.container').prepend(listEvents[1].Datum);
I get a "Uncaught SyntaxError: Unexpected token o"
When I now try to do it by another way:
var json = String($.get('myPhpFile.php'));
$('.container').prepend(json[1].Datum);
This prints the whole json variable.
And this:
var json = $.get('myPhpFile.php');
$('.container').prepend(json[1].Datum);
Uncaught TypeError: Cannot read property 'Datum' of undefined
So what am I doing wrong. Hope you can help me.
Upvotes: 0
Views: 70
Reputation: 10677
$.get
does not return a string, it returns a JQXHR object because your data has not yet been retrieved. You need to handle the return in a callback, and if you do this properly you don't have to decode the JSON: jQuery will handle it for you. Try something like this:
$.get('myPhpFile.php', {}, function(json) {
$('.container').prepend(json[1].Datum);
}, 'json');
Also, if you provide the correct Content-Type
header in your PHP, jQuery would have automatically set the dataType to JSON.
Upvotes: 1
Reputation: 963
Try this
$.get( "myPhpFile.php", {}, function( data ) {
console.log(data);
}, "json" );
It should write to console json response, because $.get()
is async so you must wait for result from server and also does not return string.
Upvotes: 1