clarkseth
clarkseth

Reputation: 229

How can I send JSON data from a PHP script to be used by jQuery?

I have a problem with some JSON data. I don't know how to take some data generated in PHP and turn that into something that I can use in my jQuery script. The functionality I need is this: I need to be able to click on images on the page, and depending on the selected element, I need to show results from my DB.

Here's the HTML page that I've got:

<html>
  <head>
  <title>pippo</title>
  <script><!-- Link to the JS snippet below --></script>
  </head>
  <body>
    Contact List:
    <ul>
      <li><a href="#">
        <img src="contacts/pippo.png" onclick="javascript:change('pippo')"/>pippo
      </a></li>
      <li><a href="#">
        <img src="contacts/pluto.png" onclick="javascript:change('pluto')"/>pluto
      </a></li>
      <li><a href="#">
        <img src="contacts/topolino.png" onclick="javascript:change('topolino')"/>topolino
      </a></li>
    </ul>
  </body>
</html>

Here's PHP code being called:

<?php
include('../dll/config.php');

$surname = $_POST['surname'];

$result = mysql_query("select * from profile Where surname='$surname'") or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
    $_POST['name'] = ucfirst($row['name']);
    $_POST['tel'] = $row['telephone'];
    $_POST['companymail'] = $row['companymail'];
    $_POST['mail'] = $row['email'];
    $_POST['fbid'] = $row['facebook'];
}
?>

Here's the Ajax JavaScript code I'm using:

<script type="text/javascript">
    function change(user) {
        $.ajax({
            type: "POST",
            url: "chgcontact.php",
            data: "surname="+user+"&name=&tel=&companymail=&mail=&fbid",
            success: function(name,tel,companymail,mail,fbid){
                alert(name);
            }
        });
        return "";
    }
</script>

Someone told me that this JS snippet would do what I want:

$.getJSON('chgcontact.php', function(user) {
    var items = [name,surname,tel,companymail,email,facebook];
    $.each(user, function(surname) {
        items.push('surname="' + user + "'name='" + name + "'telephone='" + telephone + "'companymail='" + companymail + "'mail='" + mail + "'facebook='" + facebook);
    });
    /*
    $('<ul/>', {
        'class': 'my-new-list',
        html: items.join('')
        }).appendTo('body');
    */
});

But it is not clear to me - I don't understand how I need to use it or where I should include it in my code.

Upvotes: 0

Views: 1267

Answers (4)

Matt H
Matt H

Reputation: 6530

JSON that is POSTed to a PHP page generally isn't in the $_POST variable, rather it is in $HTTP_RAW_POST_DATA.

Upvotes: 0

amlane86
amlane86

Reputation: 678

And to expand on Brian Driscoll's answer. You will need to use the user.name format to access the name field from the returned $.getJSON("blah", function(user){});

so...

items.push('surname="'+user+"'name='"+user.name+"'telephone='"+user.telephone+"'companymail='"+user.companymail+"'email='"+user.email+"'facebook='"+user.facebook+);

In this format that you have created it will just push a long ugly looking string so you might want to spend some time making it look better. Good luck!

Upvotes: 2

Billy Moon
Billy Moon

Reputation: 58619

There are several problems with your code I have tried to explain via the corrected and commented code here:

HTML & JavaScript

<html>
<head><title>pippo</title>
<!-- added link to jQuery library -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<!-- javascript can go here -->
<script type="text/javascript">
    $.ajax({
        type: "POST",
        url: "chgcontact.php",
            // use javascript object instead of `get` string to represent data
        data: {surname:user, name:'', tel:'', companymail:'', mail:'', fbid:''},
        success: function(data){
                // removed name,tel,companymail,mail,fbid
                alert(JSON.parse(data));
            }
        });
        return "";
    }
</script>
</head>
<body>
Contact List:
<ul>
<!-- removed `javascript` form onclick handler -->
<li><a href="#"><img src="contacts/pippo.png" onclick="change('pippo')"/>pippo</a></li>
<li><a href="#"><img src="contacts/pluto.png" onclick="change('pluto')"/>pluto</a></li>
<li><a href="#"><img src="contacts/topolino.png" onclick="change('topolino')"/>topolino</a></li>
</ul>
</body>
</html>

PHP

<?php

    $surname = $_POST['surname'];

    $result = mysql_query("select * from profile Where surname='$surname'")
    or die(mysql_error());

    while ($row = mysql_fetch_array( $result )){

        // create data object
      $data = new stdClass();

      // add values to data object
        $data->name = ucfirst($row['name']);
        $data->tel = $row['telephone'];
        $data->companymail = $row['companymail'];
        $data->mail = $row['email'];
        $data->fbid = $row['facebook'];

        // send header to ensure correct mime type
        header("content-type: text/json");

        // echo the json encoded data
      echo json_encode($data);

    }

?>

All code is untested, but you should be able to see what I have done at each step. Good luck.

Upvotes: 2

Brian Driscoll
Brian Driscoll

Reputation: 19635

You will have to create a proper JSON string in your PHP script, and then echo that string at the end of the script.

A simple example:

$person = new stdClass;

$result = mysql_query("select * from profile Where surname='$surname'")
or die(mysql_error());
while ($row = mysql_fetch_array( $result )) {
    $person->name = ucfirst($row['name']);
    $person->tel = $row['telephone'];
    $person->companymail = $row['companymail'];
    $person->mail = $row['email'];
    $person->fbid = $row['facebook'];
}
echo json_encode($person);

Upvotes: 2

Related Questions