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.
Page 1 of 2 12 LastLast
Results 1 to 15 of 16
  1. #1
    New Coder
    Join Date
    Dec 2010
    Posts
    21
    Thanks
    0
    Thanked 1 Time in 1 Post

    Javascript variable to php with AJAX

    Hello,

    I have a javascript function to roll a dice.
    What I want to do now is send this number you've just rolled to PHP.
    I think I've got the AJAX correct, but I'm not sure what to type in my PHP script in order to actually get the variable.
    I've got the AJAX from a thread were someone had a similar problem and modified it a bit to fit mine.
    Obviously I don't want to refresh the page.

    Javascript
    Code:
    function diceImage(img){
    	document.getElementById("dice").src = img;
    	getDiceNumber(); // This calls the AJAX function
    }
    
    function rollDice(){
    	var diceNumber;
    	var img;
    	
    	diceNumber = 0;
    	while(diceNumber < 1 || diceNumber > 6){
    		diceNumber = Math.floor(Math.random()*7);
    	}
    	diceImage("images/dice/" + diceNumber + ".png");
    }
    AJAX
    Code:
    if (window.XMLHttpRequest){
    	// Code for IE7+, Firefox, Chrome, Opera and Safari
    	xmlhttp = new XMLHttpRequest();
    }
    else{
    	// Code for IE6 and IE5
    	xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    
    xmlHttp = GetXmlHttpObject();
    
    var url;
    // URL of the page this script is called on
    url = "index.php";
    
    // This function will send the diceNumber generated by the rollDice() function to PHP
    function getDiceNumber(){
    	url = url+"?dice="+diceNumber;
    	xmlHttp.open("GET",url,true);
    	xmlHttp.send(null);
    }
    PHP
    Code:
    <?php
    
    @require_once('config.php');
    @require('users/check_login.php');
    
    ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <link href="style.css" rel="stylesheet" type="text/css" />
    <script src="js/ajax.js"></script>
    <script src="js/functions.js"></script>
    <title><?php echo $title; ?></title>
    </head>
    <body>
    <img src="images/dice/roll.png" id="dice" onclick="rollDice()" />
    </body>
    </html>

  • #2
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,355
    Thanks
    11
    Thanked 558 Times in 551 Posts
    Quote Originally Posted by dbrekelmans View Post
    AJAX
    [CODE]if (window.XMLHttpRequest){
    // Code for IE7+, Firefox, Chrome, Opera and Safari
    xmlhttp = new XMLHttpRequest();
    }
    else{
    // Code for IE6 and IE5
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlHttp = GetXmlHttpObject();
    No, this is wrong. You don't have a function GetXmlHttpObject() here. Instead you are directly assigning the object. So you can just discard this last line.

    Quote Originally Posted by dbrekelmans View Post
    // URL of the page this script is called on
    url = "index.php";
    No, this should be the URL you want to send the dice number to. Inside this PHP file you can then access the dice number using $_GET['dice']. Everything you output on that page would be returned to the callback ... WAIT: you did not specify the callback:
    Code:
    function getDiceNumber(){
    	url = url+"?dice="+diceNumber;
    	xmlHttp.open("GET",url,true);
            xmlHttp.onreadystatechange = mycallback;
    	xmlHttp.send(null);
    }
    
    function mycallback() {
       if(xmlHttp.readyState==4) {
          if(xmlHttp.status==200) {
             alert('This is the output of the script:'+xmlHttp.responseText);
          }
       }
    }

  • #3
    New Coder
    Join Date
    Dec 2010
    Posts
    21
    Thanks
    0
    Thanked 1 Time in 1 Post
    Thanks for your help, but it still doesnt work.
    Right now PHP says undefined index which means that the $_GET['dice'] isn't defined.
    I've tried checking if the $_GET['dice'] is set before echoing it, but it seems that it is never set, not even after you've rolled the dice.

    The scripts:

    AJAX
    Code:
    if (window.XMLHttpRequest){
    	// Code for IE7+, Firefox, Chrome, Opera and Safari
    	xmlhttp = new XMLHttpRequest();
    }
    else{
    	// Code for IE6 and IE5
    	xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    
    var url;
    // URL of the page the variable is sent to
    url = "index.php";
    
    // This function will send the diceNumber generated by the rollDice() function to PHP
    function getDiceNumber(){
    	url = url+"?diceNumber="+diceNumber;
    	xmlHttp.open("GET", url, true);
    	xmlHttp.onreadystatechange = mycallback;
    	xmlHttp.send(null);
    }
    
    function mycallback() {
       if(xmlHttp.readyState==4) {
          if(xmlHttp.status==200) {
             alert('This is the output of the script:'+xmlHttp.responseText);
          }
       }
    }
    PHP
    PHP Code:
        <img src="images/dice/roll.png" id="dice" onclick="rollDice()" />
        <?php
        $diceNumber 
    $_GET['diceNumber'];
        echo 
    $diceNumber;
        
    ?>

  • #4
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,355
    Thanks
    11
    Thanked 558 Times in 551 Posts
    Am I correct that you want to use "index.php" for the complete page and for sending the result of the ajax request? Why do you want to do that?

    Generally you should have the index.php to show you everything which should be on the page on first load. Then you have one or many different php to handle specific ajax requests and only output the result of that specific request.

  • #5
    New Coder
    Join Date
    Dec 2010
    Posts
    21
    Thanks
    0
    Thanked 1 Time in 1 Post
    Actually what I'm trying to do is have everything on index.php.
    You roll the dice on index.php and AJAX sends the number you've rolled back to index.php (without a page reload).
    I hope that's possible..
    I thought AJAX was here so we didn't need page reloads for everything.

  • #6
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,355
    Thanks
    11
    Thanked 558 Times in 551 Posts
    Exactly. But what do you get if you take the same index.php for the page load and for the ajax calls? You will reload the full index.php with each ajax call (even if you don't reload the page). And then you have to take excessive means to filter the output of the index.php to get only what you need from the ajax response (because you only want to show the specific part that changed).

    It would be much better to have an additional php (let's call it dice.php) that only takes the dicenumber from the ajax call and only outputs the single change that you want to display in the callback of the ajax call. This would result in much less loading overhead.

  • #7
    New Coder
    Join Date
    Dec 2010
    Posts
    21
    Thanks
    0
    Thanked 1 Time in 1 Post
    So actually the page you send this variable to will need to reload?
    Can I just include this dice.php into my index.php or will that cause trouble?
    Thanks for helping

  • #8
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,355
    Thanks
    11
    Thanked 558 Times in 551 Posts
    It's a good idea to include dice.php into index.php if you need its functionality and output there. No need to code it twice

  • #9
    New Coder
    Join Date
    Dec 2010
    Posts
    21
    Thanks
    0
    Thanked 1 Time in 1 Post
    Thanks for all the help, I will try this after work.

  • #10
    New Coder
    Join Date
    Dec 2010
    Posts
    21
    Thanks
    0
    Thanked 1 Time in 1 Post
    For some reason it's still not working.
    I'm using dice.php for this:
    PHP Code:
    if(isset($_GET['diceNumber'])){
    $diceNumber $_GET['diceNumer'];
    echo 
    $diceNumber;

    And I've included it into my index.php
    Any idea why it's not working?

  • #11
    Kor
    Kor is offline
    Red Devil Mod Kor's Avatar
    Join Date
    Apr 2003
    Location
    Bucharest, ROMANIA
    Posts
    8,478
    Thanks
    58
    Thanked 379 Times in 375 Posts
    If you have included the php code in the same page (index.php) AJAX would not be of any help. PHP is a static language, so that, if you don't reload the document, there will be no $_GET[] variable to be display. Simply because that piece of PHP code runs only once: first time when you load the document. When there is no query to get.

    On the other hand: What do you mean by "send a JavaScript variable to PHP"? PHP is a server-side language. You can not "send" a variable from a client-side language to a server-side language within the same document, within the same session.

    Can you describe a little bit your aim? What do you want to do with that variable? To send it to a DB? Or what? If you want to display it on the same document, why don't you use simple javascript for that. Neither Ajax, nor PHP is needed.
    Last edited by Kor; 01-12-2011 at 01:32 PM.
    KOR
    Offshore programming
    -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*

  • #12
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,355
    Thanks
    11
    Thanked 558 Times in 551 Posts
    First of all, there is a typo
    PHP Code:
    $diceNumber $_GET['diceNumber']; 
    instead of
    PHP Code:
    $diceNumber $_GET['diceNumer']; 
    and second to that I agree with Kor. Why do you want to include dice.php into index.php at all? dice.php is only useful for the ajax request as it expects the diceNumber parameter coming from this request. It will not be available on page load (unless you add it to the URL like "http://www.domain.com/index.php?diceNumber=2")

  • #13
    New Coder
    Join Date
    Dec 2010
    Posts
    21
    Thanks
    0
    Thanked 1 Time in 1 Post
    We need to make a game in PHP for school, so the majority of our code needs to be in PHP.
    The thing is, (correct me if I'm wrong) onclick events can only call javascript functions.
    I know I can do this entire game in javascript, but the goal is to make it in PHP, so that's why.

    I want to have javascript generate a dice number when an image is clicked, then send that dice number to PHP and have a PHP function to have a character walk that amount of spaces.

    Would you know another way to do this?
    I guess I can't call a PHP function in javascript either.

  • #14
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,355
    Thanks
    11
    Thanked 558 Times in 551 Posts
    But we already gave you everything you need to achieve this

    - The index.php shows the initial state of the page before any dices have been rolled (so there is no need to include dice.php here ... because no dices have been rolled)
    - By rolling the dices you will get the diceNumber
    - You take the diceNumber and send an Ajax request to the dice.php script which will output an image according to the diceNumber (at least that is what I understood from your previous posts)
    - The callback of the Ajax request will embed this image into the currently shown output of the index.php (actually the DOM based on the index.php) so it will be visible on the page immediately (without reloading index.php of course)

    So ... tell me again ... why do you want to include dice.php into index.php after reading this? I just want to understand.

  • #15
    New Coder
    Join Date
    Dec 2010
    Posts
    21
    Thanks
    0
    Thanked 1 Time in 1 Post
    I thought that was necessary to view the ouput, but after reading your post I realised that the callback function in AJAX already does that.


  •  
    Page 1 of 2 12 LastLast

    Posting Permissions

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