var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST","test.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("abc=123");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
<?php if(isset($_POST['abc'])) {
$test123 = 'worked';
}
?>
}}
var worked = '<?php echo $test123;?>'; // <--- this is not working
How can I make this work? I don't receive the variable in PHP whether I use get or post methods.
You seem to have two fundamental misunderstandings. One is about AJAX, and the other is about client side vs. server side code. The latter is more important.
Server vs. Client
Essentially PHP and JavaScript are totally agnostic to each other. They do not run in parallel. In this context, they don't even run on the same machine (the PHP code runs on your server, the JavaScript on the user's computer). The only communication each script can do with the other is via HTTP.
It's test.php that needs to have the code
<?php if(isset($_POST['abc']))
{
$test123 = 'worked';
}
?>
As long as test.php exists, this should work, but I'm thinking of it as a standalone script.
Using AJAX
Because of the asynchronous nature of AJAX and its HTTP dependency, you can't rely on when an ajax request will complete or even if it will complete. That is to say that any code that depends on the result of an AJAX call must be done in the ajax response callbacks.
That is, you would do something like this:
//php
<?php if (isset($_POST['abc']) { echo json_encode(array('success' => true)); }
//JavaScript
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
if (JSON.parse(xmlhttp.responseText).success) {
console.log('it worked!');
}
}
Additionally to what #Explosion Pills explained this means the php inside the ajax doesn't work as you expect.
At the place inside test.php put this:
<?php if(isset($_POST['abc']))
{
$test123 = 'worked';
}
echo $test123;
?>
Then in the code you have up there replace this:
<?php if(isset($_POST['abc']))
{
$test123 = 'worked';
}
?>
by:
var worked = xmlHttp.responseText;
and finally remove this last line:
var worked = '<?php echo $test123;?>';
And check out what happens.
Related
my problem is I am not sure how to call my php function from JS. I am trying to learn xmlhttprequest but something seems to be wrong with my code:
HTML:
<input type="button" id="btn" value="Click">
JS:
window.onload = initForms;
function initForms(){
document.getElementById("btn").onclick = doSomething;
}
function doSomething(){
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
// response
}
}
try {
xmlhttp.open("GET", "test.php", true);
xmlhttp.send();
} catch (e) {
alert(e);
}
}
PHP:
<?php
echo "Echo!";
EDIT: My question is "Echo" doesn't appear, so test.php doesn't seem to be called?! Why not?
EDIT: In the Firefox console i get the following error: "XML Parsing Error: no root element found". Not sure what to make of it (yes, I googled it..)
"// Response, you have to actually do something with the response, such as console.log(xmlhttp.response);"
console.log is worthless, especially if you are wanting to do something with the data.
getElementById("idName").innerHTML = xmlhttp.response;
Is more likely what the OP is looking for.
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'm trying to get a page with AJAX, but when I get that page and it includes Javascript code - it doesn't execute it.
Why?
Simple code in my ajax page:
<script type="text/javascript">
alert("Hello");
</script>
...and it doesn't execute it. I'm trying to use Google Maps API and add markers with AJAX, so whenever I add one I execute a AJAX page that gets the new marker, stores it in a database and should add the marker "dynamically" to the map.
But since I can't execute a single javascript function this way, what do I do?
Is my functions that I've defined on the page beforehand protected or private?
** UPDATED WITH AJAX FUNCTION **
function ajaxExecute(id, link, query)
{
if (query != null)
{
query = query.replace("amp;", "");
}
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)
{
if (id != null)
{
document.getElementById(id).innerHTML=xmlhttp.responseText;
}
}
}
if (query == null)
{
xmlhttp.open("GET",link,true);
}
else
{
if (query.substr(0, 1) != "?")
{
xmlhttp.open("GET",link+"?"+query,true);
}
else
{
xmlhttp.open("GET",link+query,true);
}
}
xmlhttp.send();
}
** Solution by Deukalion **
var content = xmlhttp.responseText;
if (id != null)
{
document.getElementById(id).innerHTML=content;
var script = content.match("<script[^>]*>[^<]*</script>");
if (script != null)
{
script = script.toString().replace('<script type="text/javascript">', '');
script = script.replace('</script>', '');
eval(script);
}
}
and on certain events, I had to within the script addevent listeners instead of just making a "select onchange='executeFunctionNotIncludedInAjaxFile();'" I had to addEventListener("change", functionName, false) for this. In the script that is being evaluated.
When you update your page by doing something like setting a container's innerHTML to some updated content, the browser simply will not run the scripts in it. You can locate the <script> tags, get their innerHTML (IE may prefer innerTEXT), and then eval() the scripts yourself (which is pretty much what jQuery does, though it finds the scripts with a regex before updating the DOM).
Use this function:
function parseScript(_source) {
var source = _source;
var scripts = new Array();
// Strip out tags
while(source.indexOf("<script") > -1 || source.indexOf("</script") > -1) {
var s = source.indexOf("<script");
var s_e = source.indexOf(">", s);
var e = source.indexOf("</script", s);
var e_e = source.indexOf(">", e);
// Add to scripts array
scripts.push(source.substring(s_e+1, e));
// Strip from source
source = source.substring(0, s) + source.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
}
}
// Return the cleaned source
return source;
}
then do parseScript(xmlhttp.responseText); when you're replacing/adding content.
In case some other people stumble upon this old thread, there is one issue with the accepted answer by Deukalion, there is one issue that may have been overlooked: as written, the script only looks for the first script tag. If multiple script tags exist, all others are overlooked.
A few minor tweaks would resolve the issue. Change one line from:
var script = content.match("<script[^>]*>[^<]*</script>");
To:
var script = content.match(/<script[^>]*>[^<]*<\/script>/g);
And another from:
script = script.toString().replace('<script type="text/javascript">', '');
To:
script = script.join("").replace(/<script type="text\/javascript">/g, '');
Now it will gather all the <script> code and execute them in the order found on the page. Otherwise it was an excellent solution.
After the AJAX request, you can make an "on success" function which can take the returned html and do something with it. Then something will be executed.
If there was a code example, then I could provide a code solution to the situation. But using just standard xmlhttprequest, the following could be done:
xhr = new XMLHttpRequest();
xhr.open("GET","ajax_info.txt",true);
xhr.onreadystatechange=function()
{
if (xhr.readyState==4 && xhr.status==200)
{
document.getElementById("myDiv").innerHTML = xhr.responseText;
}
}
xhr.send();
I have a variable localStorage.lastUpdate which stores a timestamp such as 1332237161. I need to pass that timestamp to the server which im trying to do by the line below with:
listener.php?q="+localStorage.lastUpdate
I also have another variable, localStorage.numUpdates that should receive the number of updates back from the server. I am confused whether I can use the below code with xml to run commands. Can my server side php file do something of the following
echo "localStorage.numUpdates=".$currentCount.";";
echo "localStorage.lastUpdate=".time().";";
where it would take affect on my localStorage variables in the javascript portion?
function contactServer()
{
if (window.XMLHttpRequest){ xmlhttp=new XMLHttpRequest();}
else{xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
xmlhttp.responseText;
}
}
xmlhttp.open("GET","listener.php?q="+localStorage.lastUpdate,true);
xmlhttp.send();
}
Any information would be helpful, thanks!
That won't work (and don't use eval()!).
But you can just output JSON in your PHP script:
echo json_encode( array('lastUpdate' => time(), 'numUpdated' => $currentCount) );
And in your JavaScript code:
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var result = JSON.parse(xmlhttp.responseText);
localStorage["lastUpdate"] = result["lastUpdate"];
localStorage["numUpdated"] = result["numUpdated"];
}
The scenario is , below is the html file through which i want to display the content of a text file at div id="myDiv".
The file will be read by php . The php content is given below.
I am unable to get the content from the text file . Please tell me what should be added in the ajax part to correct the program.
<html>
<head>
<script type="text/javascript">
function ajaxRequest(tb) {
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=statechange()
{
if (xmlhttp.readyState==4 && XMLHttpRequestObject.status == 200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","http://localhost/TBR/getdata.php?tb="+tb,true);
xmlhttp.send();
}</script>
</head>
<body>
<div >
<div id="myDiv">Text from file should come here.</div>
<button type="button" onclick="ajaxRequest(myfile.txt)">Change Content</button>
</div>
</body>
</html>
Below is the PHP file
<?php
$tbName = $_GET['tb'];
$file = "/home/$tbName";
$f = fopen("$file", "r");
echo "<ul>";
while(!feof($f)) {
$a= fgets($f);
echo "<li>$a</li><hr/>";
}
echo "</ul>";
?>
Fix quotes
onclick="ajaxRequest('myfile.txt')"
make sure you use encodeURIComponent() on tb
xmlhttp.open("GET","http://localhost/TBR/getdata.php?tb="+encodeURIComponent(tb),true);
Test your php page in the browser: does http://localhost/TBR/getdata.php?tb=myfile.txt provide the data you want?
If so test the function gets called. (Place an alert or debug the code and place a breakpoint within the function, or use console.debug if your browser supports it)
If the function gets called then your event handler is working correctly, if not try to rewrite it or attach it differently like onclick="ajaxRequest('myfile.txt');" though I suspect the missing semicolon isn't the problem.
If that is called you can try to see if the ajax call is carried out my inspecting the network traffic. Any decent browser will let you do that (hit f12 and look for the network tab). You should be able to see the request and response if the ajax request is being issued and responded to.
Supposing that is all working fine, ensure that your event ajax event handler is getting called. I suspect there is an issue here because you are not setting the event handler to a function...
xmlhttp.onreadystatechange = function statechange()
{
if (xmlhttp.readyState==4 && XMLHttpRequestObject.status == 200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
And failing all of that your data insert code isn't working.
<button type="button" onclick="ajaxRequest('myfile.txt')">Change Content</button>
Remember to quote the string in the onclick.
Here's a fixed version:
<html>
<head>
<script type="text/javascript">
function ajaxRequest(tb) {
if (window.XMLHttpRequest){
var xmlhttp= new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status == 200){
document.getElementById("myDiv").innerHTML=xmlhttp.responseText; }
}
xmlhttp.open("GET","http://localhost/TBR/getdata.php?tb="+ encodeURIComponent(tb),true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<div id="myDiv">Text from file should come here.</div>
<button type="button" onclick="ajaxRequest('myfile.txt')">Change Content</button>
</body>
</html>
What was wrong:
the presence of XMLHttpRequest was tested, but the function was not wrapped in an if, making that useless.
The variable names were a little mismatched - double check that
EncodeURI Component, as mentioned below
The proper syntax for a callback function is window.onload = function(){ alert('func!'); } not window.onload = alert(){ alert('load!'); }
That should be it, unless there's a problem with the PHP Script, try testing that out by visiting the URL directly.