Javascript AJAX function call delayed - php

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

Related

Second AJAX call unloading result of the first

Code below is run in the onLoad event of the page. I first would like to populate a drop down menu with getCompany() and then fill in data from the server into text boxes and choose the selected option.
Both functions work, in fact when I reload the page with debugger running and step into everything both do what they are supposed to.
When I just open the page or reload with out debugger the text boxes are filled but the options disappear from the dropdown, why is that?
<script>
var result;
function init(){
var name = window.name;
name = name.split(",");
getCompany();
setTimeout(200);
if (name[0] = "update"){
id = name[1];
getTenant(id);
//get the info for the line that called the edit function
//fill fields with information from server
}
}
function getCompany() {
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 x() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("company").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getCompany.php",true);
xmlhttp.send();
}
function getTenant(id){
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 y() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
result = xmlhttp.responseText;
result = result.split(",");
//fill the form with old information
document.getElementById("fname").value = result[0];
document.getElementById("lname").value = result[1];
document.getElementById("company").selectedIndex = result[2];
document.getElementById("phone").value = result[3];
document.getElementById("email").value = result[4];
document.getElementById("crm").value = result[5];
}
}
xmlhttp.open("GET","getTenant.php?p=" + id,true);
xmlhttp.send();
}
</script>
I assume the input fields you are filling in data in the second request belong to the data fetched from the first request. I also assume you are using the setTimeout() to delay the 2nd request...
Javascripts are single threaded. To provide asynchronous behavior js uses callback mechanism. After sending a request to the server, js doesn't wait until the response comes. JS keeps executing the rest of code until the results from the server comes. When the response comes from the server the code in the callback function xmlhttp.onreadystatechange is executed. Because of that, both requests may happen at almost the same time and consequently the response for the 2nd request may come before the first response which leads the behavior you see as an error.
When you debug, you execute line by line. Therefore there is enough time to get the response for the first request before getting the response for the second request.
As a solution you can move the code for the second request inside the xmlhttp.onreadystatechange callback in the code for the first request. Then as the callback is always executed after the results are fetched, the second request is sent after the response for the first one comes.
You may google about asynchronous javascript and learn in details...
<script>
var result;
function init(){
var name = window.name;
name = name.split(",");
getCompany(name);
}
function getCompany(name) {
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 x() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("company").innerHTML = xmlhttp.responseText;
if (name[0] == "update"){
id = name[1];
getTenant(id);
//get the info for the line that called the edit function
//fill fields with information from server
}
}
}
xmlhttp.open("GET","getCompany.php",true);
xmlhttp.send();
}
function getTenant(id){
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 y() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
result = xmlhttp.responseText;
result = result.split(",");
//fill the form with old information
document.getElementById("fname").value = result[0];
document.getElementById("lname").value = result[1];
document.getElementById("company").selectedIndex = result[2];
document.getElementById("phone").value = result[3];
document.getElementById("email").value = result[4];
document.getElementById("crm").value = result[5];
}
}
xmlhttp.open("GET","getTenant.php?p=" + id,true);
xmlhttp.send();
}
</script>
It is happening because of a race condition between the two XHR calls made from getCompany and getTenant methods. Even though you are making the getTenant call 200ms after making the first XHR call there is no guarantee that the getComapny XHR call will finish first. When that happens the follwoing line of code
document.getElementById("company").innerHTML = xmlhttp.responseText;
removes all the options from the menu and also resets the selected index. To circumvent this issue do not make getTenant(id); call from init method. Instead make it from the success handler of the getCompany XHR call.
xmlhttp.onreadystatechange=function x() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("company").innerHTML = xmlhttp.responseText;
**getTenant(id);**
}
}
Make two different object name instead of one (xmlhttp). Like
in 'getCompany()' function object name is 'xmlhttp'
in 'getTenant()' function changed object name to 'xmlTalenthttp' (or any other name which you wish)

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>

XML Request not working properly

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

Modifying Results Table to use AJAX

I have a PHP website that allows users to search a library catalog and then select/add books to a shopping cart. This all works well but we would like to implement AJAX into the search results table so that instead of clicking a link which runs another php script to add the selected record to their cart, it does this inline within the same page. This will remove the search results page refreshing when they "select" a record and it pops back to the top of the page (annoying if you were at the bottom of the page).
I've found a similar example of implementing AJAX with a link - this is my first time with AJAX - but I'm stuck as nothing happens when the user clicks the link.
Here's my script:
function selectRecord() {
// Allocate an XMLHttpRequest object
if (window.XMLHttpRequest) {
// IE7+, Firefox, Chrome, Opera, Safari
var xmlhttp=new XMLHttpRequest();
} else {
// IE6, IE5
var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
// Set up the readyState change event handler
xmlhttp.onreadystatechange = function() {
if ((this.readyState == 4) && (this.status == 200)) {
document.getElementById("selectRecord").innerHTML=xmlhttp.responseText;
}
}
// Open an asynchronous POST connection and send request
xmlhttp.open("POST", "selectRecord.php", true);
return false; // Do not follow hyperlink
}
and here's the table cell with the link:
<td class="hidden-narrow" id="selectRecord">
<?php
if (in_array($bookID, $_SESSION['selectedBooks'])) {
echo "Selected";
} else {
echo 'Select';
}
?>
</td>
In case it's not clear the result I'm after is a link ("Select") in the table cell - when the user clicks this link it then performs the selectRecord.php script which will echo "Selected" or an error message if there was an error. At present nothing happens when the user clicks the Select link.
I also need to work out how to pass the $bookID PHP variable to the AJAX script so the selectRecord.php knows which Book ID to add to the cart.
You can add a parameter to your selectRecord() call like this:
echo 'Select';
Then your selectRecord function should look like this:
function selectRecord(id) {
// Allocate an XMLHttpRequest object
if (window.XMLHttpRequest) {
// IE7+, Firefox, Chrome, Opera, Safari
var xmlhttp=new XMLHttpRequest();
} else {
// IE6, IE5
var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
// Set up the readyState change event handler
xmlhttp.onreadystatechange = function() {
if ((this.readyState == 4) && (this.status == 200)) {
document.getElementById("selectRecord").innerHTML="Selected";
}
}
// Open an asynchronous POST connection and send request
xmlhttp.open("POST", "selectRecord.php", true);
xmlhttp.send("id="+id);
return false; // Do not follow hyperlink
}
This works well as long there is only one element in your document with id selectRecord. You can always modify the id of any link by simply adding the BookId number as a postfix.
Please note your code wasn't working because it was missing the .open call on the xmlHttpRequest object which actually perform the request.

Calling a PHP page with MySQL query from Javascript function then returning results to another javascript function

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 :(";
}

Categories