Reputation: 83
Hi i im trying to get a value from a database and display it as a link in my navigation bar but i haven't been very successfull.
Start Off with my JQuery
<script>
$(document).ready(function(){
$.ajax({
type: 'GET',
data: {loadpage: 'table'},
url: 'addtable.php',
success: function(data){
$('.navbar ul').append('<li><a href="#" class="table">'+THE-PHP-ARRAY I WANT TO SHOW+'</a></li>');
}
}); //ajax request
});
</script>
addtable.php
$query = "SELECT * FROM Menus WHERE menuCreator = '".$_SESSION['U_ID']."'";
$result = mysqli_query($con, $query);
$index=0;
while($row = $result->fetch_array()){
$index++;
$data = array(
$index=>$row['menuName']
);
echo json_encode($data);
}
I tried alot of stuff. If i change my dataType to json it doesnt work at all. I tried to put it in an $.each() loop still nothing works. If i go to addtable.php it displays
{"1":"Breakfast"}{"2":"Book Fair"}
which is the correct values in my database
Im sorry if it wasn't too clear im 15 and i only do this between school any help will be greatly appreciated Thanks in advance
Upvotes: 0
Views: 494
Reputation: 608
{"1":"Breakfast"}{"2":"Book Fair"}
is not a valid JSON object. if you want to encode multiple objects, you need to do it like this:
[{"1":"Breakfast"}, {"2":"Book Fair"}]
or if you just need the values:
["Breakfast", "Book Fair"]
For loading it from the server you should use the shorthand function jquery.getJSON
Upvotes: 0
Reputation: 943564
json_encode
outputs a complete JSON text, but outputting it inside a loop you are outputting a bunch of JSON texts butting up against each other. The result isn't a valid, single JSON text.
Put $data
into an array.
Encode that array as JSON after the loop has finished.
Then you'll need to loop over that array (data
) when it gets converted to JavaScript.
Upvotes: 1