Reputation: 115
Could someone help me out with a small problem and an explantaion on what would be wrong? What i would like to do is return a result from a MySQL query, and pass it through JSON and display the value. What i have got so far is as follows:
$qry = "SELECT first_name, last_name FROM user_profile";
$result = mysql_query($qry);
while($row = mysql_fetch_array($result)) {
$name = $row['first_name'];
}
I am currently getting the error.
JSON.parse: unexpected character at line 1 column 1 of the JSON data
<div id="profile">
<div id="photo-frame">
<img class="circle" src="images/photo.jpg">
</div>
<h3 id="name"></h3>
</div>
<script type="text/javascript">
var text = <?php echo json_encode($name)?>;
var obj = JSON.parse(text);
$('#name').text(obj.name);
</script>
Upvotes: 2
Views: 1905
Reputation: 281
Your SQL query "SELECT first_name, last_name FROM user_profile" without any WHERE clause may return one or two dimensional array. When you use the json_encode to encode your result, the JSON string format will be different for one and two dimensional array. It will cause headache in the Javascript Part.
So if this is for a Single Profile- Dont use JSON
PHP
$qry = "SELECT first_name, last_name FROM user_profile WHERE id = $id";
$result = mysql_query($qry);
if (mysql_num_rows($results) == 1) {
while($row = mysql_fetch_array($result)) {
$name = $row['first_name'];
}
}
If this is for Multiple Profile
PHP
$qry = "SELECT first_name, last_name FROM user_profile";
$result = mysql_query($qry);
if (mysql_num_rows($results) > 0) {
$jsonData = [];
$jsonData['profiles'] = mysql_fetch_array($result)
json_encode($jsonData, JSON_FORCE_OBJECT);
}
HTML, JAVASCRIPT AND JQUERY
<div id="profile"></div>
<script>
$(document).ready(function() {
var data = <?php echo $jsonData;?>;
$.each(data.profiles, function() {
$('#profile').append(
'<div id="photo-frame">' +
'<img class="circle" src="images/photo.jpg">' +
'</div>' +
'<h3 id="name">' + this.first_name + ' ' + this.last_name + '</h3>' +
'<hr/>'
);
}
}
</script>
Upvotes: 1
Reputation: 98921
I don't see the need to use json
here, you can simply:
<?php
$qry = "SELECT first_name, last_name FROM user_profile";
$result = mysql_query($qry);
while($row = mysql_fetch_array($result)) {
$name = $row['first_name'];
}
?>
<div id="profile">
<div id="photo-frame">
<img class="circle" src="images/photo.jpg">
</div>
<h3 id="name"></h3>
</div>
<script type="text/javascript">
var text = '<?=$name;?>';
$('#name').text(text);
</script>
Upvotes: 0
Reputation: 2490
this is not json u have in $name (its plane text) try:
var text = <?php echo $name; ?>;
but keep in mind that this is not a good coding style php>js>html
remove the "obj" part. just:
$('#name').text(text);
Upvotes: 0