I have a submit button that uses a javascript xmlhttp request to call a php page that's sole function is to write a kml file for a google earth window on my main page. The php page is not viewable within the web browser as html.
The formulas in the php file work as intended. The problem I'm having is that after I manually press submit the first time I would like the script to continue to repeat every 5 seconds until I manually reload the page (or press a button to stop the script). Because I plan on having multiple users at the same time viewing the page each user is assigned a random 5 digit number to hold their session information and to create the kml files within the newly created session folder until they reload the page (which will then create a new session number for the user).
Because each user is designated with a unique session id the page cannot reload as the php calculations repeat. Because of this I have a return false line at the end of my javascript function.
I would like to be able to use javascript to call setInterval to repeat the function without reloading the page. If the page were to reload the just created kml file will now not be viewable within the new session. Let me know if anyone has any suggestions. Below is the applicable code.
DIV id on main index.php page
<div>
<form id="KMLsubmit" name=KMLsubmit >
<input class="KMLsubmit" type="submit" value="Create KML" onclick="createKML()"/>
</form>
</div>
JavaScript function on main index.php page
function createKML() {
$('#KMLsubmit').submit(function () {
$.get("generateKML.php",function(data,status){
});
//alert("Generating your KML files!");
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 && xmlhttp.status==200)
{
document.getElementById("kmldetails").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","generateKML.php?session=" + session,true);
xmlhttp.send();
return false;
});
}
Let me know if anyone has any suggestions on how to do this. Thanks for the help.
make createKML() external, call it on KMLsubmit submit event, set timeout function of 5 sec and clear the timeout on next submition then restart the process like this:
var myTimer = false;
function createKML() {
var xmlhttp = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("kmldetails").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST", "generateKML.php", true);
xmlhttp.send("session=" + session);
myTimer = setTimeout(function(){createKML()}, 5000);
}
document.getElementById('KMLsubmit').onsubmit = function(event){
(event.preventDefault) ? event.preventDefault() : event.returnValue = false; //prevent the form from submitting and reloading the page
if(myTimer) clearTimeout(myTimer);
createKML();
}
Try
$(function(){
$('#KMLsubmit').submit(function () {
$.get("generateKML.php",function(data,status){
});
update();
return false;
});
function update(){
$.ajax({
url: 'generateKML.php',
data: {
session: session
}
}).done(function(result){
$('#kmldetails').html(result);
setTimeout(update, 5000)
});
}
})
Related
I have menu that is included and many other modules (leftside, rightside, content ect.).
I want to load some PHP page to specific place (content) on link click.
Use Ajax on button click and then fill the div in with the php from the ajax response.
function dispRecords()
{
if (window.XMLHttpRequest)
{
// Create the object for browsers
xmlhttp=new XMLHttpRequest();
}
else
{
// Create the object for browser versions prior to IE 7
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
// if server is ready with the response
if (xmlhttp.readyState==4)
{
// if everything is Ok on browser
if(xmlhttp.status==200)
{
//Update the div with the response
document.getElementById("YOURDIV").innerHTML=xmlhttp.responseText;
}
}
}
//send the selected option id to the php page
xmlhttp.open("GET","YOURPHP.php",true);
xmlhttp.send();
}
I just built a web site by using this script:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script>
function loadpage(page)
{
document.getElementById("pageContent").innerHTML="Yükleniyor...";
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 && xmlhttp.status==200)
{
document.getElementById("pageContent").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET",page,true);
xmlhttp.send();
}
</script>
It can load any page thanks to AJAX. But yet there is a question: when I load any page containing any HTML form, when i click "submit", it leaves the main page, I mean I can't send form variables by AJAX. the only thing I need is to pass form variables by using "href" and the loadpage() function I mentioned above.
How can I do get form input's values and send to another PHP file?
you can use jQuery.
$(document).ready(function(){
$("#div_load").load("page.html");
});
whit this code you can open any page (Ex: page.html) in any div(Ex:div whit id=div_load).
and for sending data use it:
$(".class_div").click(function(){
$.post("ajax.php",
{
name:"naser",
age:"23"
},
function(data,status){
// do something when done
});
});
As you are using jQuery, you can do:
$('form').submit(funciton() {
var data = $(this).serialize();
// Call Ajax
return false;
});
I advice you to read about:
http://api.jquery.com/category/ajax/ and http://api.jquery.com/serialize/.
I have php code like this :
<div>
<?php if($link AND $access AND !$timer_expired): ?>
<font color="green">Status: Unlocked - You have successfully unlocked "<?php echo htmlspecialchars($link['link_title']);?>", the website is listed below.</font>
<?php else:?>
<font color="red"> Status : Locked - To Unlock "<?php echo htmlspecialchars($link['link_title']);?>" Please Complete the Survey.</font>
<?php endif;?>
</div>
I need to let it reload it self until the status be "Unlocked" then stop load
There is many of posts talking about reload php file..but i don't need that..i just want to reload php code
Any idea please ?
First of all, if it is PHP page, you'd better to control status on the PHP side. Be independent of client-side.
For "Locked" status page set the HTML meta header:
<meta http-equiv="refresh" content="5">
For "Unlocked" status do nothing.
That's all!
It's not totally clear what you're asking, but you need to keep in mind that PHP code is executed on the server. AJAX is executed in the client's browser. So, the way to achieve what you want is to use AJAX to continuously reload the HTML in the client's browser, which you would request from a PHP script on the server.
HTML:
<div id="myDiv">AJAX response will load here</div>
Javascript:
function loadPage(your_page)
{
var xmlhttp;
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 && xmlhttp.status==200)
{
// This javascript executes when you receive the HTML from your AJAX request
return xmlhttp.responseText;
}
}
xmlhttp.open("GET",your_page,true);
xmlhttp.send();
}
var repeat = window.setInterval(checkResponse,3000);
function checkResponse()
{
var response = loadPage('your_php_script.php');
if(response.indexOf('Unlocked') !== -1)
window.clearInterval(repeat);
}
you want to use this function and call ajax like this.
<script type="text/javascript">
jQuery(document).ready(function() {
setInterval(function(){
jQuery("#divid").load('http://example.php',
function(response, status, xhr) {
if (status == "error") {
jQuery("#divid").html(msg + xhr.status + " " + xhr.statusText);
}
});
}, 500);
});
</script>
You also apply condition to check response is 'Locked' or 'Unlocked'.
Hope it helps to you.
I will break this question into paragraphs for easier reference.
I have a script that calls a php file using Ajax; the script is executed once a button is pressed.
The PHP file contains a simple code that plusses a number with 1.
<?php
$response = $response + 1;
echo $response;
?>
However, something goes wrong when the button is pressed multiple times. I have done some research and I can conclude that there is either something wrong with the simple PHP script that I have made, or the code is only executed once per page reload.
I read an article explaining a lot of work using Javascript if I want an Ajax command to execute multiple times during the same script but I don't see the reason that it can't execute multiple times already when the button is pressed.
Question: Is the PHP file "post.php" even getting executed everytime the button is pressed? Is it something with my PHP file?
How can I make the script plus the number by 1 everytime the button is pressed? And is it because I need some extra Javascript to do that?
The rest of the script is here:
<head>
<script>
function loadXMLDoc()
{
var xmlhttp;
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 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","post.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
<p>This button will execute an Ajax function</p>
<button type="button" onclick="loadXMLDoc()">Press here!</button>
<div id="myDiv"></div>
<script type="text/javascript" src="http://www.parameter.dk/counter/5b0d9873158158e08cad4c71256eb27c"></script>
</body>
If I wasn't clear enough at some point, please pick out the paragraph number and I'll deepen that part.
In your code $response is always 1 because php by default have no state. You can fix it by saving response inside a session.
session_start();
if (isset($_SESSION['response'])) {
$_SESSION['response'] = $_SESSION['response'] + 1;
} else {
$_SESSION['response'] = 1;
}
echo $_SESSION['response'];
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...