im trying to grab search items from twitter via PHP curl, process and update them every second. In this simple version im just trying to refresh the search results for “bieber” every second. i have combined php with the javascript and im guessing its the reason things don’t work…but I need to understand why. In my understanding Apache sends only html back to the browser…so why is there a problem with the innerHTML specification:
Here’s the script
<head>
<script type = 'text/javascript'>
function refresh(){
document.getElementById('target').innerHTML= <?
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'http://search.twitter.com/search.json?q=bieber&rpp=100');
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
$var = curl_exec($ch);
curl_close($ch);
$obj = json_decode($var, true);
for($i = 0; $i<500; $i++){
if(empty($obj['results'][$i]['text'])){
echo $i;
break;
}
echo $obj['results'][$i]['text']."<br/>";
}
?>
;
var refresher = setTimeout("refresh()",1000);
}
</script>
</head>
<body onLoad="refresh()">
<div>
<span> stuff </span>
<div id ='target'>
</div>
<div id= 'rest'>
The Rest of the page that does not refresh
</div>
</div>
</body>
</html>
I know there’s AJAX and JQuery etc but let’s mention them only after we’ve explained to me why there’s a problem with this code and why what im doing is not possible without those technologies.
Thanks!
Take a look at your HTML source that is returned to the browser after the PHP executes on the server side:
Basically, because the PHP code is executed before the page is returned to the page, the content that is fetched is effectively a static string in the javascript code, not something that will ever change.
What you need to do is add a separate PHP script that just fetches the new content and then have your Javascript make an AJAX request to periodically fetch the new version of the content from the second PHP script.
This tutorial describes how to do the javascript end of the request. The PHP end will just be a script that performs your curl requests and returns the output: