1

I'm getting two random values from a table. The values are in the same row.

<?php
    $result = mysql_query("SELECT * FROM people ORDER BY RAND() LIMIT 1", $connection);
    $row = mysql_fetch_array($result);
    echo $row["name"];
    echo $row["surname"];
?>

And I want to display these two values at different div's on my HTML page by using jQuery Ajax functions.

$(function()
{
    $("#sentence-form").submit(function()
    {
        $.ajax(
        {
            type: "GET",
            url: "newperson.php",
            success: function(response)
            {
                $("#top-container").append(response);  /* Both name and surname  */
            }
        });
    });
});

The problem is separating two values to display different in div's. I tried to use two Ajax calls and I send boolean data to PHP to use with an if statement. So one of the Ajax calls displays name and the other one displays surname. But because of randomization, it's a bit complicated to find surname of a name.

What is a better approach?

4 Answers 4

8

Yes: send the data in a data structure – probably JSON – so your client-side code knows which bit is which.

First, send the data with PHP's json_encode function:

echo json_encode(array(
    'name' => $row['name'],
    'surname' => $row['surname']
));

Then use your browser's ability to parse JSON:

$.ajax({
    type: "GET",
    url: "newperson.php",
    dataType: 'json',
    success: function (response) {
        $("#name-container").append(response.name);
        $("#surname-container").append(response.surname);
    }
});

response is now a Javascript object (something like {name: 'John', surname: 'Smith'}), so you can access the two parts as normal object members.

Sign up to request clarification or add additional context in comments.

Comments

2

Send the variables as a JSON array

<?php
    $result = mysql_query("SELECT * FROM people ORDER BY RAND() LIMIT 1", $connection);
    $row = mysql_fetch_array($result);
    $output['name'] = $row["name"];
    $output['surname'] = $row["surname"];
    echo json_encode($output);
?>

And on the JavaScript code, access it as:

data.name and data.surname

Comments

1

Although I like lonesomeday's answer, and I think that that is the way to go, I will post the alternative:

Relevant PHP:

echo $row["name"].'||'.$row["surname"];

Relevant JavaScript code:

success: function (response) {
    var parts = response.split('||');
    $("#name-container").append(parts[0]); //name
    $("#surname-container").append(parts[1]); //surname
}

2 Comments

1) will fail if the name contains "||" for some reason. 2) Why NOT use JSON?
@gregmac. Please read my statement prior to the code example... If you would have done that most likely you would not have posted your comment. However if for whatever reason this is selected and the more preferred JSON method is not the delimiter can be anything just make sure to update it in both scripts.
1

Use this:

<?php
    $result = mysql_query("SELECT * FROM people ORDER BY RAND() LIMIT 1", $connection);
    $row = mysql_fetch_array($result);
    echo $row["name"]."&".$row["surname"];
?>

$(function(){
  $("#sentence-form").submit(function(){
    $.ajax({
      type : "GET",
      url : "newperson.php",
      success : function(response){
        items=response.split('&')
          $("#top-container").append(items[0]);  /* name  */
          $('#bottom-container").append(items[1]); / /*s(u should be i)rname */
        }
      });
   });
});

3 Comments

1) will fail if name contains "&" 2) you're splitting by a space, and not "&" 3) "surname" is indeed spelled correctly 4) why is this better than JSON which is a standard and already handles encoding/escaping and splitting?
whoops sorry. I was first thinking about using a space, and then thought that it was quite likely that the first or last name could contain spaces, so changed it to &. editing now. A way around this entire problem would be to encode them in json for example, but that seems too complex for what Heem is trying to do.
surname is perfectly all right: The name a person shares with other members of that person's family, distinguished from that person's given name or names; a family name.. Can you edit your answer?

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.