I have two scripts refreshing div dynamic:
1) http://project-welcome.ugu.pl/test/ajax.js
2) http://project-welcome.ugu.pl/test/ajax2.js
I tried to combine it:
// Customise those settings
var seconds = 1;
var divid = "timediv";
var divid2 = "points";
var url = "boo.php";
var url2 = "boo2.php";
// Refreshing the DIV
function refreshdiv(){
// The XMLHttpRequest object
var xmlHttp;
try{
xmlHttp=new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari
}
catch (e){
try{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer
}
catch (e){
try{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e){
alert("Your browser does not support AJAX.");
return false;
}
}
}
// Timestamp for preventing IE caching the GET request
fetch_unix_timestamp = function()
{
return parseInt(new Date().getTime().toString().substring(0, 10))
}
var timestamp = fetch_unix_timestamp();
var nocacheurl = url+"?t="+timestamp;
var nocacheurl2 = url2+"?t="+timestamp;
// The code...
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState==4){
document.getElementById(divid).innerHTML=xmlHttp.responseText;
document.getElementById(divid2).innerHTML=xmlHttp.responseText;
setTimeout('refreshdiv()',seconds*1000);
}
}
xmlHttp.open("GET",nocacheurl,true);
xmlHttp.send(null);
xmlHttp.open("GET",nocacheurl2,true);
xmlHttp.send(null);
}
// Start the refreshing process
var seconds;
window.onload = function startrefresh(){
setTimeout('refreshdiv()',seconds*1000);
}
Source of index.html:
<script src="ajax3.js"></script>
<script type="text/javascript"><!--
refreshdiv();
// --></script>
Logs<div id="timediv"></div><br>
Points<div id="points"></div><br>
It doesn't work because two div show the same (in this case points). How correct combine scripts?
P.s You can see it in file original.php
Login: testowyuser Pass: testtest then click "Strona Główna"
Something goes last and overlaps the 1st.
It's Ok that you are complaining ;), look here
xmlHttp.open("GET",nocacheurl,true); // opening 1st URI
xmlHttp.send(null); // requresting. in the mean time we've got the response and our `onreadystatechange` function triggers
xmlHttp.open("GET",nocacheurl2,true); // opening 2nd URI
xmlHttp.send(null); // the same situation. received response, triggered function
You are using 1 xmlHTTP instance to request for both. and using it sequentially, but demanding it works simultaneously.
So when the function triggers (doesn't matter 1st or 2nd time) you suppose (but not the script) to have already 2 responses in 1 variable. Moreover, you want script guess what you actually want.
document.getElementById(divid).innerHTML = xmlHttp.responseText; // getting response text from the current response (it can be 1st or 2nd response)
document.getElementById(divid2).innerHTML = xmlHttp.responseText; // and again getting the current response text from the same instance (not the response you are expecting from the next request). so, you are repeating the same for the another <div>
Actually each time you have only one response text. And each time you are putting in your <div's> the same information (copy info over 2 <div's>) bec. there is no info about the next request yet.
And as the result in your script, I suppose, you have always last request copied over 2 <div's>.
Try to create 1 instance per "channel" (1 instance of xmlHTTP for the 1st script to use and 1 for the second) and set them different (separate) onreadystatechange function. This way you will not have overlap of data and will not be tangled.
Far more elegant solution (less refactoring in JS) is to distinguish responses. For e.g. if you are receiving XML, you can parse it for some flag that will tell you that this response is for <div id=divid> and another one is for another <div> or this request is first and this is the second etc.
Related
I'm very new to PHP/Ajax/Html so here's my baby problem (I'm making a radio station site),
test.php queries my server for the currently playing song name.
listen.php displays this song name in the 'refreshTitle' div tag.
When my station changes song there is a 30-ish second delay, so what I want to do is get the song title every second and compare / delay the update of the display if the title is different to what is actually being heard, easy peasy right?! Here is listen.php:
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
function get_XmlHttp() {
// create the variable that will contain the instance of the XMLHttpRequest object (initially with null value)
var xmlHttp = null;
if (window.XMLHttpRequest) { // for Firefox, IE7+, Opera, Safari, ...
xmlHttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) { // for Internet Explorer 5 or 6
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlHttp;
}
function ajaxrequest(php_file, tagID) {
var request = get_XmlHttp(); // call the function for the XMLHttpRequest instance
// create pairs index=value with data that must be sent to server
var d = new Date();
var t = d.toLocaleTimeString();
var the_data = 'test=' + t;
//append time purely for testing to make sure text updates
request.open("POST", php_file, true); // set the request
// adds a header to tell the PHP script to recognize the data as is sent via POST
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(the_data); // calls the send() method with datas as parameter
// Check request status
// If the response is received completely, will be transferred to the HTML tag with tagID
request.onreadystatechange = function () {
if (request.readyState == 4) {
document.getElementById(tagID).innerHTML = request.responseText;
}
}
}
setInterval(
function () {
ajaxrequest('test.php', 'refreshTitle')
}, 1000); // refresh every 10000 milliseconds
//This time val should vary based on the song title retrieved during the last second
</script>
And somewhere down the rest of the page I have this:
echo "<div id=\"refreshTitle\" style=\"float:left; padding-top:6px;\">\n";
echo "</div>\n";
In test.php (the file with the song name) I have this:
if (isset($_POST['test'])) {
$str = $_POST['test']; // get data
echo $dnas_data['SONGTITLE'] . " Current time " . $str;
}
So basically every second I send the time to test.php, which echos it and that echo I assume is put into 'refreshTitle' with this line:
document.getElementById(tagID).innerHTML = request.responseText;
What I want to do is get the song title into my javascript in listen.php and only run the ajax request after some string comparison / delay logic.
Sorry for the long-winded description but I'm fairly confused and think I've done this whole thing backwards :) Please let me know any thoughts...
First, I would recommend to you to update your jQuery version (1.3 is kinda old, the current version is 2+).
What's more, AJAX requesting is very well abstracted in jQuery : you can use the load() function to simply load an element content.
Source : http://api.jquery.com/load/
I have a friend who call his clients by phone. He want to present his product on his website.
But to be sure they look at the product he want to sell, he want them to go to a page where he can change images by demand. Like running a powerpoint presentation in the clients browser.
If the client for example need other features he can show another image.
During phone call client go to a specific page on my friends website.
The image shown, or html data, change on demand by my friend.
Can this be implemented easily by AJAX?
Sure!
Client side:
<script type="text/javascript">
//The first image to load
CurrentImage="http://images.google.com/intl/en_ALL/images/logos/images_logo_lg.gif";
//The Image, eg: <img id=imgBox src=foo.jpg>
ImgBox = document.getElementById('imgBox');
function CheckForImg()
{
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
try
{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Ajax is kinda disabled :(\n you won't be able to do some stuff around :(");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var str = ajaxRequest.responseText;
if(str != CurrentImage) // we have a new image
{
ImgBox.src = str;
currentImage = str;
}
}
ajaxRequest.open("GET", "getCurrentImagUrl.php", true);
ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
ajaxRequest.send(null);
}
</script>
Now we need a way to keep the client posted, so either we put that to a frequency, or show a button to press which is way better and more efficient:
Method 1(Button):
<Button onclick="CheckForImg();">Check For Image!</button>
Method 2(Periodically check):
Simply call
SetInterval("CheckForImg", 5000);
I'll leave the server side for you :)
Any further help is kindly offered.
been working on a new site, and run into a problem.
I have an ajax loader on my main page, which loads a script every second to check if a background process is completed (usually 20 seconds-ish)
But, once the ajax script has executed (20 seconds later) it still refreshes every second.
I need to redirect the parent page to a new url, once the ajax script has finished its job.
My ajax code:
<script type="text/javascript">
function myFunction()
{
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.getElementById("txtHint").innerHTML=ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", "code/timer.php?file='.$file.'", true);
ajaxRequest.send(null);
}
</script>
<script type="text/javascript">
function forward(){
location.href=\'http://domain/newpage.html\';
}
function setTimer(){
set = setInterval( "myFunction()", 1000 );
}
</script>
the backslashes in forward(); are because my code is echoed from php.
i have tried a few codes, but the main one that should work (in child ajax element) is:
window.opener.forward();
would be greatful of any help you guys can provide... thanks
opener is only available in windows opened with javascript, call simply
forward();
but you should use another name for the function, there is a predefined method window.forward()
How to make javascript code execute on php page which was previously loaded from an ajax call?
code samples:
ajax+function parseScript to force javascript to run on the ajax requested page
Senario: I am selecting a question from selectQuest.php and using ajax it request a page called showRecord.php.
The page showRecord.php will display a table which contain the information corresponding to the quetsion selected.It contains the javascript that do not run.The javascript return will allow me to update info in db when i click submit.
The code sample below is found in the showRecord.php.Finally, if the latter run the showRecord will make another ajax request for updateQuestion.php.
But the javascript is not running in showRecord.php
function show(fileTex,aTex,bTex,cTex,dTex,eTex,newQuestNumTex,textAreaTex,textQuesAnsTex)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4)
{
var resp=xmlhttp.responseText;
document.getElementById("txtHint2").innerHTML=resp;
parseScript(resp);
// document.getElementById("txtHint").style.border="1px solid #A5ACB2";
}
}
xmlhttp.open("POST","updateQuestionAdmin.php?param="+fileTex+"&text_A="+aTex+"&text_B="+bTex+"&text_C="+cTex+"&text_D="+dTex+"&text_E="+eTex+"&text_ID="+newQuestNumTex+"&text_Ques="+textAreaTex+"&text_Ans="+textQuesAnsTex,true);
xmlhttp.send();
}
// this function create an Array that contains the JS code of every <script> tag in parameter
// then apply the eval() to execute the code in every script collected
function parseScript(strcode) {
var scripts = new Array(); // Array which will store the script's code
// Strip out tags
while(strcode.indexOf("<script") > -1 || strcode.indexOf("</script") > -1) {
var s = strcode.indexOf("<script");
var s_e = strcode.indexOf(">", s);
var e = strcode.indexOf("</script", s);
var e_e = strcode.indexOf(">", e);
// Add to scripts array
scripts.push(strcode.substring(s_e+1, e));
// Strip from strcode
strcode = strcode.substring(0, s) + strcode.substring(e_e+1);
}
// Loop through every script collected and eval it
for(var i=0; i<scripts.length; i++) {
try {
eval(scripts[i]);
}
catch(ex) {
// do what you want here when a script fails
}
}
}
</script>
As iyrag said, a Javascript framework would help. jQuery has a callback function that you can run when a script is successfully loaded and finished with ajax.
You'll want to execute some other stuff within that callback function, for instance :
$.ajax({
url: 'test.php',
success: function(data) {
$('#result').html(data); // Display script return on some div
someFunction(); // blabla
// Execute some other javascript here, you'll be abble to access the DOM of the test.html
// page because here you'lle be sure that test.html is loaded.showRecord.php should not contain javascript, which would rather be here
}
});
I also posted this because the tag features jQuery...
Hello I have two dependants select box, the second one is popularited after onchange event.
The first one is loaded with a selected value (selected=selected), what I'm asking, it is possible to send the requested while the page is loading, ie as I have the the selected option, just send the request.
Javascript
function getXMLHTTP() {
var xmlhttp=false;
try{
xmlhttp=new XMLHttpRequest();
}
catch(e) {
try{
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1){
xmlhttp=false;
}
}
}
return xmlhttp;
}
function getSubCat(catId,incat) {
var strURL="../Includes/subcatAds.php?SubCat="+catId+"&incat="+incat;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('subcat').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
The PHP will be provided if needed
You really need to use jQuery and replace all of the above with:
function getSubCat(catId, incat)
{
$('#subcat').load("../Includes/subcatAds.php?SubCat="+catId+"&incat="+incat);
}
// Run on load:
$( function(){
getSubCat(4, 5);
});
It will do the same thing. It's set up to run on load, and you don't have to worry about cross browser compatibility.
You will find yourself using jQuery selectors all the time and your code will be very lightweight. If you link the jQuery library to Google servers people will not even have to download it. Most people have it in cache already.
You could use the onload event like this:
window.onload = function(){
var selectbox = document.getElementById('select box id');
if (selectbox.value !== ''){
// your code to send ajax requests...
}
};
The code runs as soon as page loads. It then checks if the value of the specified select box is not empty meaning something is selected; in that case you put your code for the ajax request which will execute.
Since you are doing this before getting any input from the user, you could immediately make the call to the server, before the DOM is finished, before the page is fully loaded, and then just wait until the onload event takes place, or you get informed that the DOM tree is finished, and you can then safely change the value of any of the html elements.
This way you don't have the user wait for the browser to finish loading before you even start your request, which will improve the user experience.