Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 12 of 12
  1. #1
    New Coder
    Join Date
    Nov 2008
    Posts
    93
    Thanks
    12
    Thanked 0 Times in 0 Posts

    pass a variable from php file to javascript? surey this is simple?

    Hi guys I ahve had a good look around and cant seem to find a simple answer to something I feel is really simple.

    I have my own Ajax call to a php file, this php file quieries the database and then gives a variable one of three different results.

    I basically then need javascript to read the value of that variable and perform a task.

    Everything is working but I cant seem to send a varialbe from php to javascript.

    For instance I can echo the variable from the php file, which is then placed by javascript via innerHTML into a div, I can then do an indexOf on the innerHTML and then perform the relevant other Javascript functions depending on the result.

    But this really isnt ideal....

    How can I simply pass a php variable into javascript?


    I dont really want to use eval (not sure why but I have heard its bad!)

  • #2
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,151
    Thanks
    203
    Thanked 2,548 Times in 2,526 Posts
    JavaScript cannot actively read variables from the server, but when a page loads, PHP can pass variables to JavaScript by writing to the page the JavaScript is on.

    PHP Code:
    <?php
        $username 
    "Philip";
    ?>
    ...

    Code:
    <script  type="text/javascript">
    var sStr = "My name is <?php echo $username ?>.";
    document.write(sStr);   //  My name is Philip.
    </script>
    If there are only three possible results (values) then I would use a regex.

    if (/Philip/gi.test(sStr)) { // do something
    if (/Peter/gi.test(sStr)) { // do something else




    "Before a man speaks it is safe to assume that he is a fool. After he speaks it is seldom necessary to assume". - H.L. Mencken 1880-1956, American Editor, Author, Critic, Humorist
    Last edited by Philip M; 05-14-2009 at 07:58 PM.

  • Users who have thanked Philip M for this post:

    chidge (05-15-2009)

  • #3
    New Coder
    Join Date
    Nov 2008
    Posts
    93
    Thanks
    12
    Thanked 0 Times in 0 Posts
    Thanks. I am looking into JSON it seems to fit the bill a little better. What do you think?

  • #4
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    26,576
    Thanks
    80
    Thanked 4,497 Times in 4,461 Posts
    Make up your mind: Do you want to do this via an AJAX call--for which JSON might be appropriate, but not if it's just for a single value--or do you want to do it by creating the JavaScript from PHP code?

    Philip's answer had nothing to do with an AJAX call, by the by.

    And if you can "echo the variable from the php file, which is then placed by javascript via innerHTML into a div" then you *MUST* have had the value from PHP in JS variable. So you must have already done this.

  • #5
    New Coder
    Join Date
    Nov 2008
    Posts
    93
    Thanks
    12
    Thanked 0 Times in 0 Posts
    lol,

    I want to have a variable from an ajax call that calls a php file and then returns a qury from the database so i can then peform a task in Javascript

    So currently yes I am echoing the variable from php, into a div.innerHTML and then I am readin the innerHTML of the div and performing an action on the contents.

    What I want to do is to echo a variable from php, which then will be placed into div.innerHTML and then
    I can use Javascript on completion of the ajax call to perform an action

    if variable == 'option1' then do this.

    To me it seems a little wrong to be placing an echo into a div and then either using indexOf or regex to read this and perform an action, it feels cleaner to use a variable? (if possible)

    And yes JSON looks pretty cool I will look into but as you pointed out this is only returning a single variable so no point and I have used phillips idea before but as you pointed out it istn for this situation.

    Whats your suggestion on the best way to go? Thanks

  • #6
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    26,576
    Thanks
    80
    Thanked 4,497 Times in 4,461 Posts
    I'm still mystified. HOW are you "echoing the variable from php, into a div.innerHTML"???

    How about showing some code?

    If you are doing something like
    Code:
    <textarea name="foobar"><?= $somePHPvariable ?></textarea>
    then, yes, you could surely do as Philip showed you and just code
    Code:
    <script>
    var jsFoobar = "<?= $somePHPvariable ?>";
    ...
    </script>
    (And yes, <?= $x ?> is just PHP shorthand for <? echo $x; ?> ... How come so few PHP people use the shorthand notation?)

  • #7
    New Coder
    Join Date
    Nov 2008
    Posts
    93
    Thanks
    12
    Thanked 0 Times in 0 Posts
    Ajax Call

    Code:
    	
    
    var emailResponse = document.getElementById('email_response');	
    
    	
    ajax({
      url: "invite.php",
    				
      type: "POST",
    					
      info: info,
    								
      onError:	function(){ 
                      //do something error wise
                    }  
      },			
    									
      onSuccess: function(html){
    
    	emailResponse.innerHTML = html;
    							
    	if( emailResponse.innerHTML.indexOf('variablefromphp'){ 
                 //do something with the variable
            }
    
      },
    									
      onTimeOut:function(){		
    		   //do something time out wise		        
                     }									
        });	
    }

    Php file invite.php


    Code:
    <?php
    #AJAX RESPONSE FOR CHECKING NEW EMAIL. if its in the db, once (wheather its one of two differnt types), or if its in the db twice
    
    $email = $_POST['inemail'];
    			
    $OK = false;
    
    $email = "SELECT id, other
    	     FROM users
    	     WHERE blah= ?";
    
    	$stmt = $conn->stmt_init();
               if ($stmt->prepare($email)){
                   $stmt->bind_param("s", $email, $otherRtn);
    	       $stmt->bind_result($userid);			  
          $OK = $stmt->execute();
    	       $stmt->store_result();
    	       $stmt->fetch();	
    	      $numRows = $stmt->num_rows;					
    	   }
    
    	if (isset($stmt) && !$OK){
    		echo "<span class='red'><img src='../images/exclamation.png' alt='' class='exclamation'/> Problem speaking with database</span>";
    	}
    			
      if ($numRows == 1 ){//the email is in the db
    
        if(	$otherRtn != ''){
            echo "option 1";
        }else{
            echo "option 2";
        }
    
      }else if($numRows == 2 ){ //the email is not in db
            echo "option 3";
      }
    	
       $stmt->free_result();
       $stmt->close();
    	
    ?>


    hope that helps
    Last edited by chidge; 05-14-2009 at 09:21 PM.

  • #8
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    26,576
    Thanks
    80
    Thanked 4,497 Times in 4,461 Posts
    *OH*!!!!

    It's *YOUR CODE*!!!

    You *CHOSE* to do
    Code:
    onSuccess: function(html){
    
    	emailResponse.innerHTML = html;
    All you had to do, instead, was declare some variable global to the page, say
    Code:
    var getAjaxResponse;
    and then do
    Code:
    onSuccess: function(html)
    {
        getAjaxResponse = html;
    Or you could call some function as part of onSuccess. Or or or...

    Nobody ever said you *had* to dump the returned value into a form field!

    If you *want* it there, as well as in the variable, you could simply do:
    Code:
    onSuccess: function(html)
    {
        emailResponse.innerHTML = getAjaxResponse = html;
    But I can't make much sense out of this, in any case.

    The value returned from that AJAX call is going to be one of five possible values:
    Code:
    <span class='red'><img src='../images/exclamation.png' alt='' class='exclamation'/> Problem speaking with database</span>
    or
    option 1
    or
    option 2
    or 
    option 3
    or 
    [a blank string...no text]
    Why would you want to dump *any* of those values into a <textarea> on the web page???

    On top of that, the PHP code doesn't make sense:
    Code:
    $email = $_POST['inemail'];
    ...
    $email = "SELECT id, other
    	     FROM users
    	     WHERE blah= ?";
    So when you do that second assignment to the variable $email, you just wiped out whatever value you got from the AJAX call.

    Even your comment doesn't make sense:
    Code:
    }else if($numRows == 2 ){ //the email is not in db
    HUH? If $numRows is 2, then the email is in the db *twice*, I think.

    And what about if it's in the DB 3 or more times? Or zero times? You don't handle those cases, so in those ever happened, you would return NOTHING AT ALL from the AJAX query.

    If this thing works at all, as it is, I don't understand how.

    You really have a DB field named blah??
    Last edited by Old Pedant; 05-14-2009 at 09:47 PM. Reason: typos

  • Users who have thanked Old Pedant for this post:

    chidge (05-15-2009)

  • #9
    New Coder
    Join Date
    Nov 2008
    Posts
    93
    Thanks
    12
    Thanked 0 Times in 0 Posts
    Sorry I forgot to mention that quite tiredly i have edited and changed the code to place it on the site. The code works fine that wasnt the point of this thread, it is the theory of how i could be doing the task rather than the syntax.

    I havent mentioned a textarea - i was/am placing items into a div.

    Yes ok so - in the onSuccess function I will assign this result to a variable, then do a quick check and perform the task there and then.

    Ok cheers slightly tired and was thinking about this in totally the wrong way. Get it before it goes into the div rather than after!

    P.s no i dont have a db field named blah (lol lol)

    Thanks

    *edit (ha ha I can see how bad this looks - I can imagine you had a bit of a heart attack seeing this code)
    Last edited by chidge; 05-14-2009 at 10:05 PM.

  • #10
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    26,576
    Thanks
    80
    Thanked 4,497 Times in 4,461 Posts
    *WHEW*.

    Glad it's not as bad as it looked.

    I dunno where I came up with "textarea" since the code clearly says innerHTML. Blame it on senility.

  • #11
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,151
    Thanks
    203
    Thanked 2,548 Times in 2,526 Posts
    “I am in the prime of my senility” .
    Joel Chandler Harris (American Writer, 1848-1908)

  • #12
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,401
    Thanks
    11
    Thanked 595 Times in 575 Posts
    if you're going to use json in php, it's simpler to use the native json functions, and you can cross domains, which can be one les thing to worry about.


    for example:

    Code:
    $ray = "That's \"JS\" for you!";
    echo "callback(" . json_encode($ray) . ")";
    //shows: callback("That's \"JS\" for you!")
    
    $ray = array( name=>"fred", age=>21);
    echo "callback(" . json_encode($ray) . ")";
    //shows: callback({"name":"fred","age":21})
    to call the php script, use a script tag adder:


    Code:
    function addScript(u){ 
      var scr=document.createElement('script'); 
      scr.src=u;  
     document.getElementsByTagName('head')[0].appendChild(scr); 
    }
    
    function callback(data){ //do something with php info here:
      alert(data);
    }
    
    
    addScript("info.php?") //call php with this command. you can tack on GET params to talk to php...

    using callbacks, you don't need eval, or DOM operations, and the data arrives as a javascript variable(s), of the right type and everything, all ready to go.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/9/03) IE7:0.1, IE8:4.6, IE11:9.1, IE9:3.1, IE10:3.0, FF:17.2, CH:46, SF:11.4, NON-MOUSE:38%

  • Users who have thanked rnd me for this post:

    chidge (05-15-2009)


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •