Hey there! any question in your mind? Ask It Now!.

Popular Categories





Access php variable inside javascript

+1 vote
75 views
asked in Programming by Aman

I have a java script function :

function take_snapshot(){
            // take snapshot and upload to server
            webcam.snap();

          document.getElementById('pic').value =""; // here in value i have to echo a php variable which will come from a another file
        }

Please give me the solution how can I print a variable from another file inside the javascript.

1 Answer

0 votes
answered by Jake
Use an xmlhttp request to send the variable from one php file to another.

function httpRequest(x,y,z)
{
    var messageData = [x,y,z];
    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)
      {
        //logic for after successful request
      }
    }
    xmlhttp.open("GET","phpFile.php?messageData="+messageData,true);
    xmlhttp.send();
}

If you are simply trying to refer to a php variable via javascript you need to refer to it by ID like you did above or pass it via a method call on an event such as an onClick to your javascript function. Since javascript is client side it is responsive to what is on the page so it will process after the trigger on the page. Then your server side logic, such as php, is executed after.

Related Questions

Not a Member yet?

Ask to Folks Login

My Account
336 Folks are online
27 members and 309 guest online
Your feedback is highly appreciated