user892134
user892134

Reputation: 3224

getJSON with jquery

When i try to display the data with getJSON nothing happens, $('#child-left-container-2') should display data from the php file. Where did i go wrong?... Below is brief example of my code.

php file

while($row = mysql_fetch_assoc($query)) {

//code

    $array[] = "<div class='array-container-2' $style id='$id' data-sid='$sid' data-user='$user'>$details1</div>";


            }

            echo json_encode($array);

jquery

$(function() {
    $('.next_button').click(function() {

var id =  $('#container').find('.graphic-blank:visible').siblings().attr('id');

        $.getJSON('fetchstack.php?id='+id,function(data) {

            $('#child-left-container-2').html(''); //clear div

            $.each(data,function(i,result) {
                $('#child-left-container-2').append(result);
            });
        });

          });
});

Upvotes: 5

Views: 1740

Answers (7)

Garry Lachman
Garry Lachman

Reputation: 1

before you set the response to html elements with to debug it with console.log,

i dont see you created a div to response = $('#child-left-container-2') check if you have

<div id="child-left-container-2" />

and check you response, maby the json in under array... try console.log(data) and open debbuger with F12

Upvotes: 0

djleop
djleop

Reputation: 697

try to put this juste before echo json_encode($array);. Eventually put an exit call to avoid extra output.

header('Content-type:application/json;charset=utf-8');
echo json_encode($array);
exit();

Upvotes: 0

aki
aki

Reputation: 709

Well this is my solution and works flawless:

PHP:

<?php

ini_set('magic_quotes_gpc', false);
header('Content-type: text/plain');

      //DB connection credentials
$dbhost = 'hostname';
$dbuser = 'database_username';
$dbpass = 'database_password';
$dbname = 'database_name';

// allow cross-browser acces
header('Access-Control-Allow-Origin: *');

// query SQL
$sql = "do your DB query SELECT what ever here";

  //do our thingies withouth hacks (SQL Injection, etc)
try {
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->query("set names utf8");
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->query($sql);  
$json_export = $stmt->fetchAll(PDO::FETCH_OBJ);
$dbh = null;

    // return JSON format DATA
echo '{"items":'. json_encode($json_export) .'}'; 
} catch(PDOException $e) {

    // return error
echo '{"error":{"text":'. $e->getMessage() .'}}'; 
}

?>

HTML LISTVIEW:

<div data-role="page" id="myPage"><div data-role="content" id="myContent">
       //my HTML list tag
  <ul data-role="listview" id="myList"></ul>
</div></div>

JAVASCRIPT

  //trigger script on show page
$('#myPage').live('pageshow',function (event) {
       //get our JSON data
    $.getJSON('path_to_your_php_json_generator_file_declared_upper',function(data){
          //append our JSON data to a variable
       var json_entries = data.items;
                //for each JSON data, append it to our list as one element
       $.each(json_entries,function(index,entry){
           $('#myList').append('<li><a href="#">' + entry.title + '</a></li>');
             //assuming we have a field named "title" in JSON data
       });
             //refresh the list for layout (style) loading
       $('#myList').listview('refresh');
    });
});

And this is how you populate a list on jQuery Mobile with JSON data generated by a php file. You can adapt this kind of script to every JSON interpreter in your jQuery code, even with parameters (id,category, etc)!

Hope it helps one way or another!

Upvotes: 0

Martti Laine
Martti Laine

Reputation: 12985

Why don't you simply echo the HTML in the PHP-file and then fill the container with it?

while($row = mysql_fetch_assoc($query)) {
    echo "<div class='array-container-2' $style id='$id' data-sid='$sid' data-user='$user'>$details1</div>";
}

$.getJSON('fetchstack.php?id='+id,function(data) {
    $('#child-left-container-2').html(data);
});

Upvotes: 0

petervaz
petervaz

Reputation: 14175

I dont't know if this would solve the problem you are experiencing but this would be how I would solve this particular problem. Give this code a try, if it works, stopping sending html thru json would be a bonus.

$key = 0;
while($row = mysql_fetch_assoc($query)) {
    //code
    $array[$key]['id']      = $id;
    $array[$key]['sid']     = $sid;
    $array[$key]['user']    = $user;
    $array[$key]['content'] = $details1;
    $array[$key]['style']   = $style;
    $key++;
}

echo json_encode($array);

JS:

$(function() {
    $('.next_button').click(function() {

        var id =  $('#container').find('.graphic-blank:visible').siblings().attr('id');
        $.getJSON('fetchstack.php?id='+id,function(data) {
            $('#child-left-container-2').html(''); //clear div

            for (var i in data){
                var id      = data[i].id;
                var sid     = data[i].sid;
                var user    = data[i].user;
                var content = data[i].content;
                var style   = data[i].style;
                $('#child-left-container-2').append($('<div />').addClass('array-container-2')attr('id', id)
               .attr('data-sid', sid).attr('data-user', user).html(content);
            }           
       });
   });
});

I confess that not knowing what $style is or how it would appear rendered I couldn't add it to the chain. If you post the content of $style I can update the anwser. I hope this helps.

Upvotes: 1

Adam Fowler
Adam Fowler

Reputation: 1751

I don't mean to insult you at all, but what you are doing is bad practice. If you create the HTML from the client side you can have shorter requests. Also, if you use firebug, you can see a chart of your output JSON. Its really a nifty feature. You can also check to see if its being saved under the DOM section in Firebug. Good Luck.

Upvotes: 0

Zak Henry
Zak Henry

Reputation: 2185

In the second line of your jQuery

var id =  $('#container').find('.graphic-blank:visible').siblings().attr('id');

you are trying to access the id attribute of an array of jQuery objects (the siblings()). You need to specify one jQuery object to get the id for your $getJSON function

Update If there is only one sibling, specify this by doing

var id =  $('#container').find('.graphic-blank:visible').siblings().eq(0).attr('id');

Upvotes: 0

Related Questions