reload php code with ajax - php

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.

Related

Sql Querying with Ajax while offline returning blank

I'll over simplify the problem in order to make it easier. I'm using the following Ajax script to call another .php file and have it return the results to the original page. I'm using Apache offline and the page is unfortunately returning blank.
<html>
<head>
<script>
function showInfo(str) {
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("result").innerHTML= xmlhttp.responseText;
}
}
xmlhttp.open("GET","practice.php?q="+str,true);
xmlhttp.send();
}
window.onload = function() { showInfo('bleh'); };
</script>
</head>
<body>
<div id="result"></div>
</body>
//Then the code below is another file called practice.php, which corresponds the ajax above
<?
$test = $_GET['q'];
echo $test;
?>
I am pretty sure $_GET is a case-sensitive variable name on most OSes, so $_Get would be empty.
I would comment if I could -
What happens when you try to hit the page directly (ie put practice.php?q=test) in the browser?
Also I can't find any documentation (it's hard to google it), but it wouldn't hurt to make the opening tag <?php instead of just <?

AJAX no data in responsetext

Right up front...I am very new to using Ajax.
I'm working on a web site where I want the results of one Select object to determine the options in the second Select object(from a database query). I'm using PHP and it appears that the only way to do this is to use Ajax. I've written a short html page to test my Ajax knowledge and it seems to work just find on Firefox but not on Chrome or IE. I've done a lot of research and found all sorts of folks with similar problems but no real solution.
I'm making the XMLHTTPRequest call to a local file in the same folder even so I should not be experiencing any cross-domain problems. Any help would be greatly appreciated.
Here's my Javascript function that gets called when the Select box is changed:
...
function getData(str)
{
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.open("GET","ajax_info.php?color=",true);
xmlhttp.setRequestHeader("Content-Type", "text/xml");
xmlhttp.send();
alert(xmlhttp.responseText);
}
********ajax_info.php
+++++++++++++++++++++
//this is the php file that runs in response to the xmlhttprequest. It just generates a string of number at this time.
<?php
$str = "";
$i = 0;
for($i; $i<1000; $i++)
{
$str = $str.$i."-";
}
echo $str;
?>
You need to attach an event handler to your xmlhttp object to catch the onreadystatechange event. Note that when you alert your value, the asynchronous ajax call has just fired and has not finished yet (you are not checking for that anyway):
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
alert(xmlhttp.responseText);
}
}
xmlhttp.open("GET","ajax_info.php?color=",true);
xmlhttp.setRequestHeader("Content-Type", "text/xml");
xmlhttp.send();
Well in that case you should try jQuery. It will be lot easier for you to make ajax request.
Here is an example for your problem
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
// FOR GET REQUEST
$.get("ajax_info.php",{color:'value'},function(data) {
alert(data); // RETRIEVE THE RESULT
});
</script>

multi pages in AJAX

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/.

Refresh javascript calculations without reloading page

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)
});
}
})

Data output using Ajax with PHP

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'];

Categories