Simple Ajax - Request data from a web server

Discussion in 'JS Plugin Releases (RMMV)' started by Amy Pond, Nov 1, 2015.

  1. Amy Pond

    Amy Pond Veteran Veteran

    Messages:
    667
    Likes Received:
    1,359
    First Language:
    English (UK)
    Plugin Name: Simple Ajax

    Version: 1

    Author: Amy Pond @ www.hbgames.org

    Introduction

    As RPG Maker MV games use JavaScript, one simple way to talk to a server is via the web, using Ajax. Technically here we aren't using the x part unless we format the responded text using XML, but the principle is the same.

    This plugin is one simple function that returns a text variable from a web server using some entered variables.

    How to Use

    Create a PHP file on your web server which returns a text response (using echo() for example). Use GET variables to generate the response based on data sent to it.

    There is an example PHP file in the Help part of the plugin.

    Install the plugin, and type in the location of your PHP file, for example: http://www.rpgmakerweb.com/files/ajax.php (not a real file).

    As an example of its usage:

    var mytext = ajaxRequest("variable=1&othervariable=2");

    On the server we check for $_GET['variable'] and $_GET['othervariable'].

    We clean the variables before using (this is very important - please read up on cleaning user sent data in PHP).

    Then we do something with these variables and send back some data. Say we echo("hello"), then:

    var mytext = ajaxRequest("variable=1&othervariable=2"); // mytext = "hello"

    Code:
    //=============================================================================
    // Ajax.js
    //=============================================================================/*:
    * @plugindesc A simple AJAX interface.
    * @author Amy Pond @ www.HBGames.org. Created for Afar - the MMORPG
    *
    * @param URL
    * @desc The URL to your actions php file.
    * @default N/A
    *
    * @help To use this plugin you need a web server that can run PHP.
    * On this server, host a PHP file.
    * This file should check for GET variables, clean them (IMPORTANT),
    * and return back a message using echo(). The function is called
    * by ajaxRequest(parameters) where parameters takes the form:
    *
    * var1=data&var2=data&var3=data
    *
    * For example, I may wish to request the result of the equation 2+3.
    * In game I call the function: ajaxRequest("action=add&number1=2&number2=3");
    *
    * Server side, using $_GET and cleaning it to an integer for security,
    * I take these variables, add them together, and return the result:
    *
    * <?php *   //action.php
    *   switch($_GET['action'])
    *   {
    *     case 'add': *       number1 = (int)$_GET['number1'];
    *       number2 = (int)$_GET['number2'];
    *       result = number1 + number2;
    *       echo result;
    *       break;
    *     case 'login':
    *       // code goes here
    *       break; *   } * ?>
    *
    */
    
    ajaxRequest = function(args) { 
    var retrievedData = ""; 
    var parameters = PluginManager.parameters('Ajax'); 
    var get_params = args; 
    // create a new Ajax request 
    var xhttp = new XMLHttpRequest(); 
    // This function is performed when a message is returned from the Ajax request 
    xhttp.onreadystatechange = function() {   
    if (xhttp.readyState == 4 && xhttp.status == 200) {     
    // set var retrievedData to the returned text    
    retrievedData = xhttp.responseText;    }  } 
    // open the xhttp connection and send it 
    // this function is sync not async, such that the game will wait for the 
    // response. Change false to true and the code will run while the game
    // does other things, so you don't have to pause for non-important things
    // where the player doesn't need a response to continue, such as merely
    // updating the online players list.  xhttp.open("GET", parameters['URL'] + "?" + get_params, false);  xhttp.send();
    // return the retrieved text  return retrievedData;};

    Credits/thanks

    By Amy Pond of www.hbgames.org and originally created for the game Afar.

    Thanks to w3schools.

    Terms of Use

    Free for use in any game with no credit necessary. If you like you can provide a link to HBGames.org or this thread but this is not necessary. Available for commercial games for free.

    Please note that this script used incorrectly creates a vulnerable web server. If you do not clean your GET variables then you ARE open to hacking quite easily. No liability is accepted for any damage caused by use of this function. Use is at your own risk and I urge you to look into PHP security, in particular, cleaning data sent from a user. For integers this can be as simple as turning them into integer variables by (int)var, though for text you will need prewritten functions, or to make your own using preg_replace.
     
    Last edited: Jan 29, 2018
    #1
    CleanWater, Anchovy, Canini and 5 others like this.
  2. Kane Hart

    Kane Hart Elmlor.com Veteran

    Messages:
    656
    Likes Received:
    166
    Location:
    Barrie, Ontario, Canada
    First Language:
    English
    Very amazing :) This is the first step for MV for the future :)
     
    #2
  3. pangeranyakuza

    pangeranyakuza Villager Member

    Messages:
    12
    Likes Received:
    0
    First Language:
    Indonesia
    What might be the script yours could do some sort of auto update?
     
    #3
  4. gameusguyus

    gameusguyus Veteran Veteran

    Messages:
    69
    Likes Received:
    175
    First Language:
    English
    Cloud based saving/loading. A step in the right direction for online capabilities e.g. turn based chess game using PHP/MySQL to keep track of pieces/moves. Could also use it to check for updates on the game.
     
    #4
  5. yongilcool

    yongilcool Veteran Veteran

    Messages:
    60
    Likes Received:
    10
    First Language:
    English
    sorry this is a non-online external question:  but what if i want to get a number from a text file in my current project folder(not online) and put it into a variable in the game?

    like,   I'll put a text file with just a number 10 and no other content at all and load this in the game and save this 10 into a variable[1]?

    if you have answers how to do this pls share thank you very much!
     
    #5
  6. Iavra

    Iavra Veteran Veteran

    Messages:
    1,797
    Likes Received:
    856
    First Language:
    German
    And the A part ^^ Since you aren't using XML, you might scratch the other a, too :D
    To all users: Please remember, that using synchronous Ajax will cause the game to freeze, until it receives an answer. For local files, this won't take long, but for web requests it will be noticable, depending on the server and internet connection.


    If you are using asynchronous Ajax (changing the "false" to "true" or removing it entirely), the function likely won't return anything usable, since the request might still be running. Since the function also doesn't take a callback, your response would be lost.
     
    #6
  7. dienben

    dienben Warper Member

    Messages:
    1
    Likes Received:
    0
    First Language:
    French


    Hi,


    Thanks for your code. I've got a basic question, if I modify the script by implementing an asynchronous call, and a call back function, should I be able to receive my answer or RPG Maker MV will not 'wait' in background?


    Is there a way to set up a time out for synchronous call? Because if the server is down, the game will be blocked, will not?


    Regards,


    Benoit
     
    #7
  8. hp4000

    hp4000 Veteran Veteran

    Messages:
    133
    Likes Received:
    69
    First Language:
    English
    Primarily Uses:
    N/A
    This is great! Do you have an example RPG Maker MV project (with a php file i can upload online to test it with) using this script. I'm having trouble getting started...
     
    #8
  9. hp4000

    hp4000 Veteran Veteran

    Messages:
    133
    Likes Received:
    69
    First Language:
    English
    Primarily Uses:
    N/A
    Just bumping to see if any example has been made
     
    #9
  10. Amy Pond

    Amy Pond Veteran Veteran

    Messages:
    667
    Likes Received:
    1,359
    First Language:
    English (UK)
    Sorry, I will make an example when I get home.
     
    #10
    Canini and hp4000 like this.
  11. hp4000

    hp4000 Veteran Veteran

    Messages:
    133
    Likes Received:
    69
    First Language:
    English
    Primarily Uses:
    N/A
    Thank you so much!
     
    #11
  12. Canini

    Canini Veteran Veteran

    Messages:
    980
    Likes Received:
    651
    First Language:
    Swedish
    If this returns an answer without changing anything else in the game, this would be great to make small changes/updates to the game without actually putting out a new version.
     
    #12
    hp4000 likes this.
  13. Amy Pond

    Amy Pond Veteran Veteran

    Messages:
    667
    Likes Received:
    1,359
    First Language:
    English (UK)
    Hmm, I realised I put an example script in the header of the plugin above. A demo wouldn't be much else than putting that in a text file.

    The forum seems to have also broke all the line breaks in my plugin above.

    Code:
    <?php
    
    //action.php
    switch($_GET['action'])
    {
      case 'add': 
         number1 = (int)$_GET['number1'];
        number2 = (int)$_GET['number2'];
          result = number1 + number2;
           echo result;
          break;     case 'login':
         // code goes here
         break; 
       } 
    ?>
    So basically to retrieve a variable sent with the plugin I use $_GET. These variables MUST BE SANITISED. (int) conversion sanitises by turning it into an integer, but for any text more must be done; I'm not going to explain that part because I could tell you wrong and I am not responsible for any SQL injection or other such attacks as a result of using this plugin without proper sanitisation.

    So what we do is send something using the game. For example:

    returned_string = ajaxRequest("action=add&number1=2&number2=3");

    In the above function call I have called the action called "add" with the variables "number1" and "number2" with some data assigned to them.

    In my PHP file I have retrieved these variables using $_GET. So number1 and number2, two variables, are sent to the server to be read and used in the function.

    To return something, I use echo. Best to build up a string and then echo that at the end of processing.

    So I could echo "YES THIS IS WORKING".

    Back in my game returned_string would be set to this value. So I can do an if statement or other conditional to test if returned_string == "YES THIS IS WORKING".

    Using that you can actually build some pretty complex systems. Set up a PHP database. Integrate with other PHP systems.

    I use phpbb which amongst other things also allows me to sanitise using the request_var function. I use that for login and register as well as handling user accounts.

    I hope the above makes sense.
     
    #13
    hp4000 likes this.
  14. hp4000

    hp4000 Veteran Veteran

    Messages:
    133
    Likes Received:
    69
    First Language:
    English
    Primarily Uses:
    N/A
    *see posts below!*
     
    Last edited: Feb 11, 2018
    #14
  15. hp4000

    hp4000 Veteran Veteran

    Messages:
    133
    Likes Received:
    69
    First Language:
    English
    Primarily Uses:
    N/A
    *see posts below!*
     
    Last edited: Feb 11, 2018
    #15
  16. hp4000

    hp4000 Veteran Veteran

    Messages:
    133
    Likes Received:
    69
    First Language:
    English
    Primarily Uses:
    N/A
    *see posts below!*
     
    Last edited: Feb 11, 2018
    #16
  17. hp4000

    hp4000 Veteran Veteran

    Messages:
    133
    Likes Received:
    69
    First Language:
    English
    Primarily Uses:
    N/A
    #17
  18. hp4000

    hp4000 Veteran Veteran

    Messages:
    133
    Likes Received:
    69
    First Language:
    English
    Primarily Uses:
    N/A
    Yay! Got everything working now!
    Thanks for the plug in!
     
    #18
  19. tasyo

    tasyo Villager Member

    Messages:
    13
    Likes Received:
    2
    First Language:
    Filipino
    Primarily Uses:
    N/A
    hi Amy,

    This is my 6th day when i purchased RPG MAKER MV. Now I'm studying on it.

    I tried your plugin, but whenever i call the function this is always showing see image below.

    this is my code to call the function in the script event (i just want to get the value inside ajax variable and show it in message popup).

    var returned_string = ajaxRequest("action=add&number1=2&number2=3");
    if (returned_string == "5" ){
    $gameMessage.add(returned_string);
    }

    Attached also the plugin.

    Please if you can advise where is my mistake thank you.

    upload_2018-5-16_17-22-56.png


    upload_2018-5-16_17-16-51.png
     

    Attached Files:

    #19
  20. tasyo

    tasyo Villager Member

    Messages:
    13
    Likes Received:
    2
    First Language:
    Filipino
    Primarily Uses:
    N/A
    Hi Amy or Anybody can help (Admin),

    Any solution to my above problem please?, I'm sure calling functions is easy for everybody who is veteran here but for me with still little experience is hard for the start.
     
    #20

Share This Page