I've not found a tutorial/ explanation that deals with this side of the 'php array -> jQuery' issue. (Or one I understand, I'm new to all this :S)
I have working SQL in a PHP file:
$sql = "SELECT * FROM notes WHERE username = '$uname' and notetype = 'todo'";
$result = mysql_query($sql,$conn);
$i = 0;
while($row = mysql_fetch_assoc($result))
{
$notes[$i] = $row['note'];
echo json_encode($notes[$i]);
$i += 1;
}
Which will echo into a div/DOM(!?) element successfully through Ajax:
$.ajax({
url:'getnotestodo.php',
data: "",
datatype: 'json',
success: function(data)
{
$('<div class="stickit" />').text(data).appendTo('#stickitholder');
}
});
But obviously the trouble I'm having is that it is all echoed into the one new <div class="stickit">
i.e. "note1""note2"note3" etc. - every note into one div, rather than one new div for each new note.
So I am trying to populate a jQuery array with a PHP array, in order to run a "while" loop client side to create a new div on each index with that index's data - this process, but in a loop:
$('<div class="stickit" />').text(data).appendTo('#stickitholder');
I had imagined json_encode()
over the whole PHP array would return an object that jquery would be able to use one of the map()
type functions. But I'm having terrible script failures leading to terrible troubleshooting attempts and crashing and am at a complete dead end.
PHP:
$sql = "SELECT * FROM notes WHERE username = '$uname' and notetype = 'todo'";
$result = mysql_query($sql,$conn);
$i = 0;
while($row = mysql_fetch_assoc($result))
{
$notes[$i] = $row['note'];
$i += 1;
}
json_encode($notes[]);
slightly different jQuery:
$.ajax({
url:'getnotestodo.php',
data: "",
datatype: 'json',
success: function(data)
{
$('<div class="stickit" />').text(data).appendTo('#stickitholder');
var notesarray = new Array();
notesarray = data;
while (notesarray.length >= 0){
$('<div class="stickit" />').text(data).appendTo('#stickitholder');
}
}
});
I'm learning as I'm going but I'm not going anywhere now so help would be massively appreciated.
Problem you are facing is because you are trying to pass many json objects in one response. So javascript wont be able to recognize it as json object. Your object will look like
[1,2,3][2,3,1]
Now you are doing it right(little bit) You can have your divs like this.
<div id="appendMe">
</div>
<script>
$.ajax({
url:'getnotestodo.php',
data: "",
datatype: 'json',
success: function(data)
{
jquery.each(data,function(index,val){
$('#appendMe').append("<div class='stickit'>"+val+"</div>");
}
});
</script>
NOw in your php code, change this line json_encode($notes[]) to json_encode($notes)