Call javascript function in parent window from child ajax - php

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()

Related

How can I make an AJAX call that periodically refreshes a part of the page?

I am working in a chat system that relies on a mysql database.
At the beginning of the first loading of the page sending the following query:
SELECT * FROM `Shoutbox` ORDER BY `Shoutbox`.`ID` ASC LIMIT 0 , 30
and then using a while loop mold all messages (with user names and date) in a div.
while($array=mysql_fetch_array($dati)) {
echo "<div class='tag_li $array[ID]'><span class='when'>$array[DateTime]</span><span class='linea mess'><span id='author'><a onclick='ajaxLoadContent(this)' link='profile.php?name=$array[User]'>$array[User]</a></span>: $array[Message]</span></div>";
}
Now I would like to be sent every second query, and then updates the contents of the div with new messages if any.
How can I send a SQL query in a range?
I will assume you are using javascript and want to make an ajax call.
Start with the timer on the client side
window.setInterval("ajaxFunction()",milliseconds);
And the ajax function
function ajaxFunction(){
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){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxDisplay.innerHTML + ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", "ajax-example.php" , true);
ajaxRequest.send(null);
}
the php part
while($array=mysql_fetch_array($dati)) {
echo "<div class='tag_li $array[ID]'><span class='when'>$array[DateTime]</span><span class='linea mess'><span id='author'><a onclick='ajaxLoadContent(this)' link='profile.php?name=$array[User]'>$array[User]</a></span>: $array[Message]</span></div>";
}
And the html part
<div id="ajaxDiv"></div>
That should give you an idea how it is done.

change images in clients browser on my demand

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.

Adding more parameters in ajax

I am using AJAX function. I am passing 3 variables to the next page using AJAX. When I add the 4th variable the function doesn't get called.
Code:
<script language="javascript" type="text/javascript">
//Browser Support Code
function ajaxFunction(){
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){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var count = document.getElementById('count').value;
var type = document.getElementById('type').value;
var sem = document.getElementById('sem').value;
var rid = document.getElementById('room').value;
ajaxRequest.open("GET", "add_requi_ajax.php?count=" + count+"&type="+ type+"&sem="+sem+"&rid="+rid, true);
ajaxRequest.send(null);
};
</script>
Your code is syntactically and logically correct, which means that the problem is likely one of your input IDs is wrong (typo? Should room be rid?), or you call the function before the inputs are rendered on the page (use window.onload).
Verify each of your input IDs. If they all look correct, then comment them out and hard code the values to rule out your inputs as a problem. Watch the error console for any error messages. If an uncaught error is encountered, it can appear that the function isn't being called.
You probably need to urlencode your values.

passing information through AJAX POST

I am doing something like this, I am passing a variable to a php script via post with AJAX. It is actually getting inside my php and running my echo, however it is not printing anything out when I print the $_POST array.
function ajaxFunction(data){
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;
}
}
}
ajaxRequest.open("POST", "process.php", true);
ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxRequest.setRequestHeader("Content-length", data.length);
ajaxRequest.setRequestHeader("Connection", "close");
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
//var data = array();
//data = document.forms["order_form3"].getElementsByTagName("input");
}
}
ajaxRequest.send(data);
}
I recommend to use a plugin like firebug or even the built in functionalities of Chrome or Firefox to see what has been sent and what has been received in your post request.
The ajax response is not printed somewhere on your screen as you might know it from "normal" http POST requests to a php page. It will be returned as part of your ajaxRequest object and you can fetch it from there to use Javascript to "print" it.
Seems you need to encode your parameters, calling your function does submit your data, however they are unbound to a variable on the other end. I'm not surprised PHP throws your data away.
See here: AJAX XMLHttpRequest POST

How to combine the two scripts refreshing div into one?

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.

Categories