I have a javascript that does an AJAX-request to a PHP-script which starts a loop. This loop returns data to the javascript. I want to be able to send arrays from the PHP-script back to the javascript but this doesn't seem to be working properly.
Mainly because it sometimes returns 2(or more) arrays at the same time. How would I get this to work? Tried searching for JSON-help but didn't find anything that explained my problem.
In my HTTP-Response method:
if(http.readyState == 3)
{
console.log( http.responseText );
var toBeEvaled = "(" + http.responseText + ")";
console.log( toBeEvaled );
var textout = eval( toBeEvaled );
console.log( textout.name );
}
My PHP looks like this:
echo json_encode( array( 'type' => 1, 'name' => $stringVar, 'id' => $id ) );
Log 1 becomes:
{"type":1,"name":"String1","id":"1000004"}
{"type":1,"name":"String2","id":"60220"}
As you see, there are 2 arrays in that one. Another problem is that new arrays gets added onto http.responseText so somehow I need to get rid of those that I have already processed so that I can process only the new ones that I haven't processed yet.
Example, log 2 looks like this:
{"type":1,"name":"String1","id":"1000004"}
{"type":1,"name":"String2","id":"60220"}
{"type":1,"name":"String3","id":"5743636"}
{"type":1,"name":"String4","id":"8555983"}
{"type":1,"name":"String5","id":"7732"}
{"type":1,"name":"String6","id":"92257"}
Any ideas??
::::EDIT::::
Solved it! Did the following..
PHP:
echo json_encode( array( 'type' => 1, 'name' => $stringVar, 'id' => $id ) ) . '%#%';
Notice the '%#%' at the end.
Javascript:
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 + ')' );
console.log( 'Name: ' + textout.name + ', ID: ' + textout.id );
}
});
}
}
Working excellent! :)