I've implemented more complex AJAX before with javascript and PHP, but for some reason this refuses to work. This is copied almost directly from the W3 example.
var xmlhttp;
function changeLoc(str)
{
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Browser does not support HTTP Request");
return;
}
var url="action.php";
url=url+"?q="+str;
url=url+"&sid="+Math.random();
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
function stateChanged()
{
if (xmlhttp.readyState==4)
{
alert(xmlhttp.responseText);
}
}
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
And the simple action.php
<?php
echo 'here';
?>
The function changeLoc is called from a link on the html page. It gets into the readyState = 4 condition , but the alert is blank. I know it's something really simple, but I can't find it.
Thank you.
Use firebug to see if there are any issues(like there are any 404 etc). Also its better to choose a javascript framework like jQuery for AJAX.
After seeing some of the suggestions I saw that the call to my php file was never occurring through firebug. The action that was occurring was when I navigated back to my index through the links on my page that call the Ajax functionality. Once i removed the href from my links, the php worked!
Very tricksy, but now I know better
Thank you for your help.
Related
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 <?
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>
I have an XML request in my javascript file that is not transferring my variable correctly to PHP and I cannot figure out why. Could I possibly be missing a reference library of some sort?
Here is the function in question. I do know that the str variable has what I want inside. I am leaving old trial code in comments just in case you want to see what I have tried.
function PHP_Con(str)
{
var xmlhttp;
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
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("txtHint").innerHTML=xmlhttp.responseText;
}
}
if(!xmlhttp)
{
alert("Fehler");
}
else
{
/*$.ajax({
type:"POST",
url:"dbConnection.php",
data:{"test" : "str"},
success:function()
{
alert("success");
}
});*/
alert(str);
xmlhttp.open("GET","dbConnection.php?test="+str,true);
// Requestheader senden
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
// Request senden
xmlhttp.send();
/*var json_string= JSON.stringify(str); // convert it into a json string.
$.post('dbConnection.php' , {test : json_string },function(){
alert("success");
}); */
}
}
And here is my corresponding PHP code:
$test = intval($_POST['test']);
echo $test;
Also, I know about isset but I am trying to get the variable to show up. I'd rather get an error when it is not there, if that makes since...
Thank you very much. :) If there are easier ways to do this, I would be interested in that as well.
But as of now I feel like I do need to have a Form that calls a JS function, then my JS has variables retrieved from user input, and then those variables go to PHP so that they can be checked against my database... it all seems like the right order to me, but I admit to not having a very clear view of how JS variables show up in PHP and also of how PHP can respond in a way that is reflected through HTML code... for example I would like to "echo" back to a span in a p with the results of the comparison (user input against the database contents) and I have no idea of how that is done...
You are sending a GET request so you have to use $_GET instead of $_POST
$test = intval($_GET['test']);
echo $test;
a POST request would look like
xmlhttp.open("POST","dbConnection.php",true);
// Requestheader senden
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
// Request senden
xmlhttp.send("test="+encodeURIComponent(str));
I can't seem to figure out how to get this function working. The crucial thing to see is that the tStat = xmlhttp2.responseText seems to be delayed. I have it test this out with the .innerHTML +=" withintest "+Stat. It prints out "withintest withintest withintest 0". So it does a few iterations until it has the value?? 0 is the value of Stat that I want, and the checktStatus.php gets it from a database.
But since this function returns a value, and I have it being called from another function into a variable for that value, it can't be delayed DB read before it returns. But I can't figure out how to accomplish this! Help?
EDIT: took out some commented code, but the problem still remains. It returns an "undefined" value before it can get a real one.
function gettStatus()
{
var tStat;
if (window.XMLHttpRequest)
{ // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp2=new XMLHttpRequest();
}
else
{ // code for IE6, IE5
xmlhttp2=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp2.onreadystatechange=function()
{
if (xmlhttp2.readyState==4 && xmlhttp2.status==200)
{
tStat=xmlhttp2.responseText;
document.getElementById("txtHint").innerHTML+=" withintest "+tStat;
return tStat;
}
}
xmlhttp2.open("GET","checktStatus.php?tID=1",true);
xmlhttp2.send();
}
How onreadystatechange works
onreadystatechange event handler - as the name of the event suggests - is called when the readyState is changed. So you must check for the state and status (as you did in the part you commented).
See more details here: Mozilla Developer Network: AJAX - Getting Started
List of readyState values
From the page referenced above (link to the section):
The full list of the readyState values is as follows:
0 (uninitialized)
1 (loading)
2 (loaded)
3 (interactive)
4 (complete)
Asynchronous nature of AJAX
You should also be aware of the fact, that usually AJAX works asynchronously, so it would be easier for you to just pass callbacks that will be executed once the response is received, like that:
function gettStatus(callback){
// do something here...
callback(result); // ...and execute callback passing the result
}
Solution
Thus you should edit your code to look similarly to this (with readyState / status conditions uncommented):
function gettStatus(callback)
{
var tStat;
if (window.XMLHttpRequest)
{ // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp2=new XMLHttpRequest();
}
else
{ // code for IE6, IE5
xmlhttp2=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp2.onreadystatechange=function()
{
if (xmlhttp2.readyState==4 && xmlhttp2.status==200)
{
tStat=xmlhttp2.responseText;
document.getElementById("txtHint").innerHTML+=" withintest "+tStat;
callback(tStat);
}
}
xmlhttp2.open("GET","checktStatus.php?tID=1",true);
xmlhttp2.send();
}
and then just use it like that:
gettStatus(function(tStat){
// tStat here is accessible, use it for further actions
});
instead of using it in the following manner:
var tStat = gettStatus();
// tStat would be available here, if gettStatus() would not involve
// asynchronous requests
The lines you have commented out serves the purpose of filtering readystates.
/*if (xmlhttp2.readyState==4 && xmlhttp2.status==200)
{*/
tStat=xmlhttp2.responseText;
document.getElementById("txtHint").innerHTML+=" withintest "+tStat;
return tStat;
//}
Should be
if (xmlhttp2.readyState==4 && xmlhttp2.status==200)
{
tStat=xmlhttp2.responseText;
document.getElementById("txtHint").innerHTML+=" withintest "+tStat;
return tStat;
}
I am refactoring some code. I have a PHP page that contains a MySQL query and stores the result in a PHP variable $my_result. This result is then echoed to a Flash SWF during embedding with SWFObject.
I now want to call this PHP page that makes the query from a javascript function like so - one change I have made to the PHP is that instead of storing the result in a variable $my_result I am echoing the result.
Javascript function to call the PHP page and make the database query
function getNewUploads() {
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) {
alert(xmlhttp.responseText); // shows the correct output in an alert box
return xmlhttp.responseText;
}
}
xmlhttp.open("GET","dBaseConnect_uploadStep2.php",true);
xmlhttp.send();
}
Then I have the embedding of the Flash which I only want to happen when a certain tab is clicked on a page and is handled by jabvascript -
function show_tab(tab_id) {
$(tab_id).show();
if(tab_id == "#tab_2") {
var data_string = getNewUploads(); // CALLING THE FUNCTION TO CALL THE PHP QUERY
alert(data_string); // shows undefined in the alert box
var so = new SWFObject(".....");
so.addVariable("theDataString", data_string);
so.write("flashcontent2");
}
}
So it seems that the getNewUploads() function does not return the result from the PHP page.
Can anyone shed some light on my mistake please. Thanks
The call is asynchronous. After you call send, the call begins in the background. In the meantime, getNewUploads returns. Later, the function you've assigned is called with the answer. When you do return xmlhttp.responseText, you're returning from this anonymous function (assigned to onreadystatechange), not from getNewUploads (which is already done).
You can use a callback instead. Something like:
function getNewUploads(callback) {
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) {
callback(xmlhttp.responseText);
}
}
xmlhttp.open("GET","dBaseConnect_uploadStep2.php",true);
xmlhttp.send();
}
function show_tab(tab_id) {
$(tab_id).show();
if(tab_id == "#tab_2") {
getNewUploads(function(data_string) {
alert(data_string);
var so = new SWFObject(".....");
so.addVariable("theDataString", data_string);
so.write("flashcontent2");
}); // CALLING THE FUNCTION TO CALL THE PHP QUERY
}
}
We define getNewUploads to take a single argument, callback. Then, in the success function, we call the callback with a single argument, the response text. In show_tab, we pass an anonymous function that takes a single parameter (the response text) to getNewUploads, as the callback parameter.
The true in xmlhttp.open("GET","dBaseConnect_uploadStep2.php", true); makes it asynchronous and hence the error. Change it to:
function getNewUploads() {
//initialize xmlhttp
xmlhttp.open("GET", "dBaseConnect_uploadStep2.php", false);
xmlhttp.send();
if(xmlhttp.status == 200)
return xmlhttp.responseText;
else
return "Oops :(";
}