Simple Ajax - Request data from a web server

Ellie Jane

Veteran
Veteran
Joined
Mar 17, 2012
Messages
747
Reaction score
1,474
First Language
English (UK)
Primarily Uses
RMMV
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:

Kane Hart

Elmlor.com
Veteran
Joined
Jun 27, 2014
Messages
656
Reaction score
166
First Language
English
Very amazing :) This is the first step for MV for the future :)
 

pangeranyakuza

Villager
Member
Joined
Feb 11, 2013
Messages
12
Reaction score
0
First Language
Indonesia
Primarily Uses
What might be the script yours could do some sort of auto update?
 

gameusguyus

Veteran
Veteran
Joined
Oct 25, 2015
Messages
69
Reaction score
175
First Language
English
What might be the script yours could do some sort of auto update?
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.
 

yongilcool

Veteran
Veteran
Joined
Nov 7, 2014
Messages
60
Reaction score
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!
 

Iavra

Veteran
Veteran
Joined
Apr 9, 2015
Messages
1,797
Reaction score
862
First Language
German
Primarily Uses
Technically here we aren't using the x part
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.
 

dienben

Warper
Member
Joined
May 31, 2016
Messages
1
Reaction score
0
First Language
French
Primarily Uses


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
 

hp4000

Veteran
Veteran
Joined
Aug 3, 2017
Messages
165
Reaction score
93
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...
 

hp4000

Veteran
Veteran
Joined
Aug 3, 2017
Messages
165
Reaction score
93
First Language
English
Primarily Uses
N/A
Just bumping to see if any example has been made
 

hp4000

Veteran
Veteran
Joined
Aug 3, 2017
Messages
165
Reaction score
93
First Language
English
Primarily Uses
N/A
Thank you so much!
 

Canini

Veteran
Veteran
Joined
Mar 29, 2016
Messages
1,022
Reaction score
684
First Language
Swedish
Primarily Uses
RMVXA
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.
 

Ellie Jane

Veteran
Veteran
Joined
Mar 17, 2012
Messages
747
Reaction score
1,474
First Language
English (UK)
Primarily Uses
RMMV
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.
 

hp4000

Veteran
Veteran
Joined
Aug 3, 2017
Messages
165
Reaction score
93
First Language
English
Primarily Uses
N/A
*see posts below!*
 
Last edited:

hp4000

Veteran
Veteran
Joined
Aug 3, 2017
Messages
165
Reaction score
93
First Language
English
Primarily Uses
N/A
*see posts below!*
 
Last edited:

hp4000

Veteran
Veteran
Joined
Aug 3, 2017
Messages
165
Reaction score
93
First Language
English
Primarily Uses
N/A
*see posts below!*
 
Last edited:

hp4000

Veteran
Veteran
Joined
Aug 3, 2017
Messages
165
Reaction score
93
First Language
English
Primarily Uses
N/A
Yay! Got everything working now!
Thanks for the plug in!
 

tasyo

Villager
Member
Joined
May 12, 2018
Messages
13
Reaction score
3
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
 

Attachments

tasyo

Villager
Member
Joined
May 12, 2018
Messages
13
Reaction score
3
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.
 

Users Who Are Viewing This Thread (Users: 0, Guests: 1)

Latest Threads

Latest Posts

Latest Profile Posts

X[ oh gawd.... I dropped my super expensive laptop on my hard tile floor! It still comes on and all, but now Im worried its gunna start screwing up in the near future.... I hope not, cant afford to replace stuff like that. :(
I wrote a nice animated preloading system for mv+mz today. It only supports graphic assets atm, should it support audio too? See it in action in my recent minigame @
I posted my first commercial game on the forums, and now waiting for approval.
fingers crossed.
TMW the air quality is so bad, your hair changes color every time you wash it. :LZYyuck:
Finished two animations today. :kaojoy:

Forum statistics

Threads
103,002
Messages
996,645
Members
134,484
Latest member
Gesonel
Top