javascript - Get multiple PHP arrays within Ajax and create DIV tags

688

I'm returning multiple entries from the database and putting them into an array; however in the second part which involves parsing them using ajax and loops I'm unsuccessful.

PHP array:

$historyl = array();
while($h=mysql_fetch_assoc($sql)){
   $historyl[] = $h;
}
foreach ($historyl as $his){
    echo json_encode( array('type' => 1, 'picture' => "{$his[picture]}", 'artist' => "{$his[artist]}", 'title' => "{$his[title]}")) . '%#%';
}

I'm spiting each entry by %#%.

useHttpResponse:

var lastResponse = '';

function useHttpResponse() {
    if (http.readyState == 3) {
        // Get the original response before we edit it
        var originalResponse = http.responseText;
        // Replace the found last response in our original response with nothing(basically editing out the last response)
        var newResponse = originalResponse.replace(lastResponse, '');
        // Add our new response to the last response
        lastResponse += newResponse;
        var responses = newResponse.split("%#%");
        $.each(responses, function (index, value) {

            if (value != '') {

                var textout = eval('(' + value + ')'); 
                document.getElementById('title').innerHTML =  textout.title;
                document.getElementById('artist').innerHTML =  textout.artist;
                document.getElementById('picture').innerHTML = http://blu.com/textout.picture;
            }
        });
    }
}

In the Ajax part I need to somehow put the results in DIVs like below, so that later I could call them by div tags from another file.

document.getElementById('title').innerHTML =  textout.title;
document.getElementById('artist').innerHTML =  textout.artist;
document.getElementById('picture').innerHTML = http://blu.com/textout.picture;

Does anyone know how should I fix the div section?

EDIT: Here's the final look; however still no luck!

<html>
<head>
<title>Recently</title>

<script language="JavaScript">
 var http = getXMLHTTPRequest();
var counter;

function getXMLHTTPRequest() {
try {
 req = new XMLHttpRequest();
} catch(err1) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (err2) {
  try {
  req = new ActiveXObject("Microsoft.XMLHTTP");
  } catch (err3) {
    req = false;
  }
}
}
return req;
}
///////
function getServerText() {
  var myurl = 'http://blu.com/recentlyajax.php'; // enter the full path to the aj_TimeRemain.php path
  var modurl = myurl;
  http.open("GET", modurl, true);
  http.onreadystatechange = useHttpResponse;
  http.send(null);
}
var lastResponse = '';
function useHttpResponse()
{

  if(http.readyState == 3)
  {
    // Get the original response before we edit it
      var originalResponse = http.responseText;
      // Replace the found last response in our original response with nothing(basically editing out the last response)
      var newResponse = originalResponse.replace(lastResponse, '');
      // Add our new response to the last response
      lastResponse += newResponse;
      var responses = newResponse.split("%#%");
      var histItems = JSON.parse(originalResponse);

    // histItems is now a regular array, containing objects with title,artist,picture fields
    $.each(histItems, function(i, item){
        document.getElementById('title').innerHTML =  item.title;
        document.getElementById('artist').innerHTML =  item.artist;
        document.getElementById('picture').innerHTML = "http://blu.com/"+item.picture;
    });


   }

}

$.ajax({
url: "http://blu.com/recentlyajax.php",
data: {arg1: val1, arg2: val2, ...},
dataType: "json",  // <- this instructs jQuery to parse answer as json
success: function(histItems){
    $.each(histItems, function(i, item){
        document.getElementById('title').innerHTML =  item.title;
        document.getElementById('artist').innerHTML =  item.artist;
        document.getElementById('picture').innerHTML = "http://blu.com/"+item.picture;
    });
}
});

          </script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"><style type="text/css">
<!--
body,td,th {
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 12px;
color: #999999;
 }
-->
</style></head>
<body>
<script language="JavaScript">
var $div = $('<div></div>')
.addClass('histItem')
.append('<span class="title">'+item.title+'</span>');
$('#histList').append( $div );
</script>
</body>
</html>
741

Answer

Solution:

document.getElementById('picture').innerHTML = http://blu.com/textout.picture;

change to

document.getElementById('picture').innerHTML = 'http://blu.com/' + textout.picture;
349

Answer

Solution:

The data returned from database has to be formatted in json format, and returned. It will be easy to get the data from the json format and process using javascript/jquery. for example:

var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );
389

Answer

Solution:

As has been suggested, use json to its full extent :

//PHP
$historyl = array();
while($h=mysql_fetch_assoc($sql)){
   $historyl[] = $h;
}
$histItems = array();
foreach ($historyl as $his){
    $histItems[] = array('type' => 1, 'picture' => $his['picture'], 'artist' => $his['artist'], 'title' => $his['title']));
}
echo json_encode($histItems);


// javascript
var histItems = JSON.parse(originalResponse);

// histItems is now a regular array, containing objects with title,artist,picture fields
$.each(histItems, function(i, item){
    document.getElementById('title').innerHTML =  item.title;
    document.getElementById('artist').innerHTML =  item.artist;
    document.getElementById('picture').innerHTML = "http://blu.com/"+item.picture;
});

// javascript, using jQuery :
$.ajax({
    url: "url/to/fetch/json.php",
    data: {arg1: val1, arg2: val2, ...},
    dataType: "json",  // <- this instructs jQuery to parse answer as json
    success: function(histItems){
        $.each(histItems, function(i, item){
            document.getElementById('title').innerHTML =  item.title;
            document.getElementById('artist').innerHTML =  item.artist;
            document.getElementById('picture').innerHTML = "http://blu.com/"+item.picture;
        });
    }
});

To create a div :$(validHtml) will create a new node instead of selecting existing node(s). You can then use regular jQuery manipulators on that node :

var $div = $('<div></div>')
       .addClass('histItem')
       .append('<span class="title">'+item.title+'</span>')
       .append( ... )...;
// you then need to insert this new node somewhere on your page :
$('#histList').append( $div );

People are also looking for solutions to the problem: php - Preg replace with array of patterns not working as expected

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.