1

Hi guys I´m new at stackoverflow and also new at Jquery

Well hope I can make myself understandable. Here is what I want: I have made a query to my MySQL db, using a class with PHP

public function User($id) {
    $this->connect_db_web($conn);
    $sql = mysql_query("SELECT * FROM users WHERE id='".$id."'");
    while ($values = mysql_fetch_array($sql)) {
        $arr[]=array(
        'id'=>$values['idUsers'],
        'name'=>$values['name'],
        'name2'=>$values['name2'],
        'lname'=>$values['lname'],
        'lname2'=>$values['lname2'],
        'email'=>$values['email'],
        'phone'=>$values['phone'],
        'address'=>$values['address'],
        'bday'=>$values['bday'],
        'password'=>$values['password']
        );
    }
    echo '{"user":'.json_encode($arr).'}';
}

Then I have a php code where I call this function

$name = $user->User($id);

I think this works ok (if I´m wrong please help). Now what I´m really trying to do is getting the values from the JSON array into specific divs, example:

$.getJSON("user.php",function(data){
$.each(data.user, function(i,user){
    name = user.name;
    $(name).appendTo('#getname');
});
}); 

And inside my HML i Have a <p id="getname"></p>wich is the tag I want the value to be displayed

But no value is displayed, why?, what am I doing wrong?

Thanks for the help I apreciate it

0

4 Answers 4

3

Your JSON is malformed. You are appending a bunch of objects {.1.}{.2.}{.3.}. Instead, try {"users":[{.1.},{.2.},{.3.}]}.

In PHP you'll do something like this (note that I've changed the response type to JSON-P rather than JSON by adding a callback parameter):

public function User($id) {
    $users = array();

    $this->connect_db_web($conn);
    $sql = mysql_query("SELECT * FROM users WHERE id='".$id."'");
    while ($values = mysql_fetch_array($sql)) {
        $users[] = array(
          'id'=>$values['idUsers'],
          'name'=>$values['name']
          // etc.
        );
    }
    $obj['users'] = $users;

    $callback = (empty($_GET["callback"])) ? 'callback' : $_GET["callback"];
    echo $callback . '(' . json_encode($obj) . ');';
}

Then you'll be able to do:

$.getJSON("user.php?callback=",function(data){
  $.each(data.users, function(i,user){
    $('#getname').append(user.name);
  });
}); 
Sign up to request clarification or add additional context in comments.

8 Comments

Hi Jens, using your code, it all went very nice, at least I´m getting values, but for some reason I still get null, using firebug I get {"users":[]} why is that so?
Are you loading the JSON from a different (sub)domain? Then it could be a cross-domain policy issue. Try JSON-P instead. I'll update the code
No Jens, same site same domain, actually is a localhost test site, so nothing from outside
Oh wait. Your DIV id is getname (no caps) but my jQuery selector was $('#getName') (capital N). Change THAT and try again.
I realize that, that´s not it, the difficulty is that JSON is not displaying and values in JQeury format, I have the values from the php class, but cannot get them using Jquery, I alway get Null or {users:[]} (taked from firebug)
|
2

probably safer to do like this:

echo json_encode(array("user" => $arr));

on the other end you would receive an object which, I would suggest iterating like this:

var k;

for (k in data.user){
     $("#getname").append($("<span></span>").html(data.user[k].name));
} 

Given that you are fetching information for one user only, following I would suggest

$id = (int) $_GET["id"]; // or wherever you get it from.
if ($r = $db->mysql_fetch_assoc()){
    $response = array(
        "name" => $r["name"];
    );
    echo json_encode($response);
} else {
    echo json_encode(array("error" => "Could not get name for user " . $id));
}

Then, on front-end, all you need to do is:

if (typeof(data.name) != "undefined"){
    $("#getname").html(data.name);
} else if (typeof(data.error) != "undefined"){
    $("#getname").html(data.error); //or handle otherwise
}

9 Comments

Hi Jancha, got the same value as with Jens, {users:[]}, what should I do instead?
seems like problem with data fetching. revisit mysql query, if that works. also -- while loop is not good idea, as you are doing id matching. so there can be only one record. this means that you should optimize everything to start with. will update my note for better solution.
Actually the data is perfectly displayed, from db, the problem focus in the Jquery getJSON function, it doesn´t display no data, wich is weird. sued your script and same thing it doesn´t get any value, JSON is empty, what the hell can be happening?
do console.log(data) and paste here results from inspector
I am sorry I went in and saw it was not accepted, better after than never!!
|
0

You've misinterpreted your JSON structure. You're appending your DB rows to an array, and embedding that inside an object. If you'd do a console.log(user) inside your .getJSON call, you'd see you'll have to do:

user[0].name

instead. As well, your code assumes that the user ID exists, and returns data regardless of how many, or how few, rows there actually are in the result set. At minimum your JS code code should check users.length to see if there ARE are any rows to begin with. Beyond that, unless you're doing it in another section of code somewhere, that $id value is probably coming from the web page, which means your query is vulnerable to SQL injection attacks.

Comments

0

OK got it, was a php code error and JSON structre as marc said, here I´m gonna post what finally I had PHP Class

public function User() {
$users = array();
$this->connect($conn);
$sql = mysql_query("SELECT * FROM users WHERE id='1'");
    $values = mysql_fetch_array($sql);
        $users[] = array(
            'id'=>$values['id'],
            'name'=>$values['name'],
            'name2'=>$values['name2'],
            'lname'=>$values['lname'],
            ...//rest of values
            );

    echo json_encode($users);
}

PHP module to get class

include"class.php";
$user = new Users();
$user->User();

Now how did I got the values using JQuery

$.getJSON('user.php', function(data){
        $('wherever_you_want_to_point_at').text(data[0].name);
    });

Hope it helps someone, Thanks again guys, very very helpful Take care you all

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.