0

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 Answer 1

1
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.

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

1 Comment

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

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.