views:

46

answers:

1

I have a web page that thats sends an Ajax request with a javascript object, using JQuery, to a PHP script which processes the data and then returns a JSON array.

I then need to present the first items in the array within a HTML DIV and at the click of a button swap the HTML to present the next items in the array.

Here is the PHP script code.

$arr[] = array("firstname"=>"Mike", "surname"=>"Jones");
$arr[] = array("firstname"=>"James", "surname"=>"Smith");
$arr[] = array("firstname"=>"Jenny", "surname"=>"Williams");

$json = json_encode($arr);
echo $json;

Here is the JSON array whic the PHP script returns.

[
{
    "firstname": "Mike",
    "surname": "Jones"
},
{
    "firstname": "James",
    "surname": "Smith"
},
{
    "firstname": "Jenny",
    "surname": "Williams"
}
]

Here are parts in question within the HTML.

<div id="person"><div>
<button id="next">Next Person</button>

Here is the JavaScript using the JQuery library.

$.ajax({
type: "POST",
url: "request.php",
dataType: 'json',
data: datasend,
success: handleRequest
});

function handleRequest(response) 
 {
 var jsondata = response;
 //want to show the first, firstname and surname within person div, from json array
 //$('#person').html("Firstname =" + firstnamevar + "Surname = " + surnamevar);
 }

$('#next').click(function() 
  {
  //want to move to the next firstname and surname, in the son array
  });

Within the 'handleRequest' function I want to add the first firstname and surname to the html within the person div.

Then on the next button click I want to move along the JSON array and add the next persons firstname and surname to the div.

Thanks for any help!

Dave

+1  A: 
function handleRequest(response) 
{
    responseArray = response;

    showOnePerson();
}

var arrayIndex = 0;
var responseArray = null;

function showOnePerson(){
    // check if there still are names in the array
    if(!responseArray[arrayIndex]) return false;

    $('#person').html("Firstname =" + responseArray[arrayIndex].firstname + "Surname = " + responseArray[arrayIndex].surname);
    arrayIndex++;
}

$('#next').click(function() 
{
    //want to move to the next firstname and surname, in the son array
    showOnePerson();
});

This should help.

Slavic
Spot on, thanks Slavic! Been struggling with that. Appreciate the quick response.
daviemanchester