Wrox Programmer Forums
Go Back   Wrox Programmer Forums > Web Programming > JavaScript > Javascript How-To
| Search | Today's Posts | Mark Forums Read
Javascript How-To Ask your "How do I do this with Javascript?" questions here.
Welcome to the p2p.wrox.com Forums.

You are currently viewing the Javascript How-To section of the Wrox Programmer to Programmer discussions. This is a community of software programmers and website developers including Wrox book authors and readers. New member registration was closed in 2019. New posts were shut off and the site was archived into this static format as of October 1, 2020. If you require technical support for a Wrox book please contact http://hub.wiley.com
 
Old June 10th, 2008, 11:51 AM
Registered User
 
Join Date: Jun 2008
Location: , , .
Posts: 7
Thanks: 0
Thanked 0 Times in 0 Posts
Default Passing data from PHP to Javascript

Hi
How can you get the AJAX response text that is written to a div tag innerHTML to do more than just write to the screen. The info shows up on my web page but when I try to use the value with innerHTML, I get the previous value. So far the only way I can get it to update the value is to do my Ajax call twice, which requires two submit clicks, which I don't want to have to do. I'd appreciate any ideas.

Thanks!

 
Old June 10th, 2008, 12:31 PM
Friend of Wrox
 
Join Date: Oct 2004
Location: delhi, delhi, India.
Posts: 553
Thanks: 0
Thanked 1 Time in 1 Post
Send a message via MSN to vinod_yadav1919 Send a message via Yahoo to vinod_yadav1919
Default

Hi oldBroh!!
technically i don't think so..."The info shows up on my web page but when I try to use the value with innerHTML, I get the previous value".

when your ajax response text is written to innerHTML it will contain new value and when you retrieve it,it will always contain new value!!
If possible could you provide your sample code..


try this,its only for showing new value always retained!!
<script>

function setHtml()
{
document.getElementById("mydiv").innerHTML="new value";
}

function getHtml()
{
alert(document.getElementById("mydiv").innerHTML)
}
</script>
<div id="mydiv">Test</div>
<input type=text id="mytext">
<input type=button onclick="setHtml()" value=sethtml>
<input type=button onclick="getHtml()" value=gethtml>

Cheers :)

vinod
 
Old June 10th, 2008, 04:15 PM
Registered User
 
Join Date: Jun 2008
Location: , , .
Posts: 7
Thanks: 0
Thanked 0 Times in 0 Posts
Default

Hello vinod

Thanks for the fast reply. Sorry I wasn't close by. I am kinda slow at this, so I will have to play with the code you sent, but I will for sure. In the meantime heres a stripped down version of my code. Its pretty much self explanatory, but what I want, is for the value of innerHTML in A to be available for use after submitting only once. The refresh of values seems to be tied to submit buttons and alert calls. Btw I am only interested in making it work in IE for the time being.

This all works. (just not like I want it to:()



Mypage.html

<html>

<head>
<script src="getdata.js"></script>
<script language = "JavaScript" type = "text/javascript">
    var data = ""
    var dataA = ""

    function prepdata(){
        data = document.getElementById("data").value
        getdata(data)

        document.getElementById("B").innerHTML=document.ge tElementById("A").innerHTML
        dataA = document.getElementById("A").innerHTML
        alert("This is what shows in A before calling alert : "+dataA)

        document.getElementById("B").innerHTML=document.ge tElementById("A").innerHTML
        dataA = document.getElementById("A").innerHTML
        alert("This is what shows after calling alert : "+dataA)
    }
    function copydata(){
        document.getElementById("B").innerHTML=document.ge tElementById("A").innerHTML
    }
</script>
</head>

<body>

Data to send: <input type="text" size="40" id="data" value="Send this to retrieve new data"/>
<input type="button" name="send" onclick="prepdata()" value="Submit"/>
Submiting twice causes data to update
<br></br><br></br>
A. Data returns here, and then is copied to B:<p><div id="A"> A data</div></p><br></br>
B. Data read from A :<p><div id="B">blank</div></p><br></br>
Manual copying of data from A to B causes correct updated reading of innerHTML:<br></br>
<input type="button" name="copy" onclick="copydata()" value="Submit"/>
</body>
</html>




getdata.js

var xmlHttp

function getdata(str){
    xmlHttp=GetXmlHttpObject();
    if (xmlHttp==null) {
        alert ("Your browser does not support AJAX!");
        return;
    }
    var url="getdata.php";
    url=url+"?data="+str;
    url=url+"&sid="+Math.random();
    xmlHttp.onreadystatechange=stateChanged;
    xmlHttp.open("GET",url,true);
    xmlHttp.send(null);
}

function stateChanged(){
    if (xmlHttp.readyState==4){
        document.getElementById("A").innerHTML=xmlHttp.res ponseText;
        mydata=xmlHttp.responseText;
    }
}

function GetXmlHttpObject(){
    xmlHttp=null;
    try {
        xmlHttp=new XMLHttpRequest();
    }
    catch (e){
        try{
            xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e){
            xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    return xmlHttp;
}





getdata.php

<?php
$response="Data from PHP";
echo $response;
?>



Thanks again,
oldBroh

 
Old June 10th, 2008, 05:53 PM
Friend of Wrox
 
Join Date: Jun 2008
Location: Snohomish, WA, USA
Posts: 1,649
Thanks: 3
Thanked 141 Times in 140 Posts
Default

You have to *WAIT* for the data to *GET* there!!!!

So if you need to process the *NEW* data in div "A", you have to wait until your "stateChanged()" function has fired!

So two ways:
(1) Just move the code that needs to manipulate the data *INTO* the stateChange() function.

(2) Use setTimeout( ) to repeatedly wait until the data has, indeed, changed.

Number (1) is by far the easier and more logical route.
 
Old June 11th, 2008, 04:56 PM
Registered User
 
Join Date: Jun 2008
Location: , , .
Posts: 7
Thanks: 0
Thanked 0 Times in 0 Posts
Default

Dear Old Pendant

I agree that I am probably less patient than I should be. But I think patience is something you exercise with humans, not browsers. I have tried all kinds of manipulations to be able to access the value in the innerHTML after it has been written to the screen, and the data is just unavailable until I call an alert or a submit. I'm loosing my patience, lol. I'm to the point of just working with what is, but I would really like to know why it is behaving this way. It seems that if you can't depend on code being executed sequentially, then chaos is a real posibility. I thot maybe there was something related to AJAX that was letting my code continue executing before the javascript function was complete, but I get the same situation if I just have a regular JS function,(not an AJAX call) return a value to inner html. Im not the smartest guy on the planet so probably I'm missing something, but I sure can't see it. It also displays similar delayed or missed action using image.scr and timing loops. Is this maybe my personal browser settings, Internet Explorer peculiarities in general, or the nature of javascript. If you know, please help me to understand. And btw, thanks for the post

Good day to ya,
oldBroh

 
Old June 11th, 2008, 06:18 PM
Friend of Wrox
 
Join Date: Jun 2008
Location: Snohomish, WA, USA
Posts: 1,649
Thanks: 3
Thanked 141 Times in 140 Posts
Default

So I have to assume that the code you showed is dummy code, just to illustrate the problem???

Because clearly if you simply changed your stateChanged code to do

function stateChanged(){
    if (xmlHttp.readyState==4){
        document.getElementById("A").innerHTML = xmlHttp.responseText;
        document.getElementById("B").innerHTML=document.ge tElementById("A").innerHTML;
    }
}

Then hopefully and presumably there's no possible way that B isn't changed to match A as soon as A changes.

So, now, I didn't actually try your code. And now I'm going to have to, aren't I?? <grin style="sickly"/>
 
Old June 11th, 2008, 11:53 PM
Registered User
 
Join Date: Jun 2008
Location: , , .
Posts: 7
Thanks: 0
Thanked 0 Times in 0 Posts
Default

Old Pedant

First, sorry about the "Pendant", mental typo. And the code is no dummy, It works, I'm the dummy here.

I tried adding the line to stateChanged like you showed, and it made B look like A. But this is still just on the screen as far as mypage is concerned. If youll notice, the Alert, which shows the innerHTML of A right before it is called is still the old A value, even tho you appear to have verified the value to be updated by copying it to B. I think I hate alert(). There has to be a better way to monitor variables than this. Why cant javascript have a step function for debugging like old basic.

Can you tell me this... I have read that javascript is a single thread, (im fuzzy on all this) so to me it seems like the code written after a function call, cant be executed until thefunction is finished, right?

Anyway, thanks for the suggested code change, it has given me an idea or two to try.

oldBroh

 
Old June 12th, 2008, 12:28 AM
Registered User
 
Join Date: Jun 2008
Location: , , .
Posts: 7
Thanks: 0
Thanked 0 Times in 0 Posts
Default

Old Pedant

Im sure you caught this but to correct myself, yes, the php file is a dummy, it only returns a value to test.


 
Old June 12th, 2008, 01:24 AM
Friend of Wrox
 
Join Date: Jun 2008
Location: Snohomish, WA, USA
Posts: 1,649
Thanks: 3
Thanked 141 Times in 140 Posts
Default

Yes, JS is single threaded.

Tell you the truth, I never thought about whether that meant that all execution is suspended when you are doing a call to
    alert( )
but it's easy enough to test.

Let me do so:

Code:
<script>
var tick = new Date(2008,1,1,0,0,0);

function sillyWayToWait( )
{
    alert( "first alert: " + tick.toString() + "\nWait 20 seconds before hitting OK");
    alert( "SECOND alert: " + tick.toString() + "\nSee?  time not changed.  Click OK");
    setTimeout( 'alert("but now look:" + tick.toString())', 1 ); // wait 1 millisecond
}

function changeTick( )
{
    tick = new Date();
}
</script>
<body onLoad="setTimeout('changeTick( )', 10000);">
<a href="#" onclick="sillyWayToWait();">click me fast!</a>
</body>
Try that HTML page. Guess what? Yep, alert() is part of the thread.

Notice how even a 1 millisecond delay, though, allows the postponed event (the timeout() event) to come in and do its job.

So... alert() is a lousy way to debug realtime JS, indeed!

But so is dumping data to a visible area of the screen, because if your JS code "hangs" the redraw of the screen, the visible area can't be updated. (After all, when you do something like
    document.getElemntById("FOO").innerHTML = "BAR";
that doesn't *REALLY* update the screen! It just modifies the DOM representation of it in memory; it's up to the browser's rendering engine to move the pixels around to effect the visible change. And if the rendering engine isn't able to run because you are holding an alert() open...)
 
Old June 12th, 2008, 01:31 AM
Friend of Wrox
 
Join Date: Jun 2008
Location: Snohomish, WA, USA
Posts: 1,649
Thanks: 3
Thanked 141 Times in 140 Posts
Default

DUMBO ME!

An easier way to demo that alert stalls everything!

Code:
<script>
function changeTick( )
{
    document.getElementById("TOCK").innerHTML = (new Date()).getSeconds();
    setTimeout("changeTick()", 1000);
}
</script>
<body onLoad="changeTick( );">
<h1>Seconds: <span id="TOCK"></span></h1>
<P>
<a href="#" onclick="alert('See?  The clock can NOT update!');">demo</a>
</body>




Similar Threads
Thread Thread Starter Forum Replies Last Post
Passing javascript variable to html or php ashraf_gawdat Javascript How-To 3 July 12th, 2006 02:48 PM
Passing data from PHP to Javascript youngj PHP How-To 4 February 22nd, 2006 11:55 PM
Passing PHP variables to javascript wfrisch Pro PHP 10 April 5th, 2005 05:13 AM
passing php variable to javascript and vice versa onmcv Beginning PHP 0 March 24th, 2005 01:00 PM
passing javascript to php by Snib ismnanie Pro PHP 5 February 4th, 2005 07:07 AM





Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
Copyright (c) 2020 John Wiley & Sons, Inc.