Pass data from Construct 3 through Javascript for PHP

  • Hi,

    I developed for Construct 2 a small 'script' that will tell if the site where the game is running (post with iframe) is or is not a partner (is partner if have our pub-id in thier ads.txt page).

    How?

    The game will send to a PHP page the domain where it's running. On that PHP page, we have a script that goes to domain.com/ads.txt page, and test if our pub-id is there, returning 0 if it is, or 1 if it's not there. In Construct 2, if it's 0 we will show Google ADS, and if it's 1 we will show banner ads.

    The Problem?

    I can't do the same in Construct 3. For a reason the script will not work properly and it get stuck "$.POST".

    CONSTRUCT 2

    In the Browser function, I have:

    "var url = document.referrer;
    var found;
    $.post('https://www.mydomain.com/upload/get_content.php', {posturl:url}, function(data){
    found = data.indexOf(0);
    c2_callFunction('pub_id', [found]);
    });"
    

    In the 'pub_id' function I have a simple event that assign a variable to the value of 'found'.

    PHP

    In the 'https://www.mydomain.com/upload/get_content.php' file I have:

    <?php
    $pubid1 ='mypubid';
    $url = $_POST['posturl']; //URL get from Construct 2
    
    -----
    Here I test if the domain get through Construct 2 is or is not a partner.
    If it is, I will have: $data['response'] = 0; 
    If it's not, I will have: $data['response'] = 1;
    -----
    
    echo $data['response'];
    ?>
    

    This script it's running perfectly on over 30 games. But, If I try to make it in Construct 3, I can't. It won't work. It will not enter here: "$.post('https://www.mydomain.com/upload/get_content.php', {posturl:url}, function(data){....".

    Construct 3

    The difference between C2 and C3 script is that in Construct 3 I use 'c3_callFunction' insted of 'c2_callFunction', and in the Construct 3 'pub_id' function I add parameters and after that I use them.

    Somebody had this type of issue?

    Cheers! :)

  • Your JS code uses $, which is jQuery. Construct 2 uses jQuery, but Construct 3 does not, since it's no longer necessary. Assuming the CORS configuration etc. is correct, you just need to swap that for fetch.

    BTW it's helpful to post any error messages that appear, since that should have had some kind of error involving the fact $ is undefined.

  • There's a few things here, but I think the key thing is that $.post is a jquery function, jquery is no longer included in Construct so unless your including it yourself it won't work.

    I'm a little unsure about some of the edges here, but if I was trying to implement this now I would use:

    const url = "https://www.mydomain.com/upload/get_content.php";
    const data = { posturl:document.referrer };
    
    const res = await fetch(url, {
     method: 'POST',
     body: JSON.stringify(data),
     headers:{
     'Content-Type': 'application/json'
     }
    });
    
    const data = res.text();
    runtime.callFunction("pub_id", data);
    

    As in inline script in the event sheet. It uses the "fetch" API, which is native instead of being an external library.

  • Ashley

    Ok, I got that. So no jQuery anymore. I will try to use fetch, but I'm not familiar with it. I'm out of the city for the moment, but when I come back to my laptop, I will try to switch to 'fetch'.

    About the errors, I don't get any. Thanks for heads-up.

    Nepeo

    Thank you. After I will get home I will try your idea too.

    Have a great day! :)

  • Nepeo

    It seems that I have an error at 'fetch', "Unexpected token".

  • Ah yeah the piece of code I gave you expects to be used in an event sheet script block. If your not using it like that you will need to place it into an async function so that the "await" operator works.

  • Nepeo

    I use it in an event sheet script block, but I don't know why it's not working. If I delete 'away' operator, I don't get any errors, but the script will not work properly.

    I don't get any data, just 'Promise' or 'undefined'.

  • Is it showing you this error in the editor? I forgot there's a bug in the current beta that the script validator doesn't know that script blocks are async contexts.

    "fetch" returns a "promise" object, there's 2 ways of using a promise. Async/await is the newer, and easier to write way. But there's an older version which uses callbacks. The older format will be accepted by the script validator without any problems. Try this instead:

    	const url = "https://www.mydomain.com/upload/get_content.php";
    	const data = { posturl:document.referrer };
    
    	fetch(url, {
     		method: 'POST',
     		body: JSON.stringify(data),
     		headers:{
     			'Content-Type': 'application/json'
     		}
    	})
    	.then(res => res.text())
    	.then(data => runtime.callFunction("pub_id", data));
    
    
  • Try Construct 3

    Develop games in your browser. Powerful, performant & highly capable.

    Try Now Construct 3 users don't see these ads
  • Nepeo

    No, the script runs ok, but I don't get any data in.

    The problem is that I can't get any data through:

    .then(res => res.text())
    .then(data => runtime.callFunction("cauta_pub_id", data))
    

    Here is the script in Construct 3:

    Image: i.postimg.cc/Ghr3Z4Nq/code.png

    Sort explanation:

    • 'mod_reclama' = ad_mode ( I set 1 if it's partner - and display google ADS, 2 if it's not - I display banners)
    • 'executa' = is just for test - to see if it's stuck, how many times he tried to send data, and so on. Is incrementing with 1 until he send any data to function. When is some data send, it becomes 99.
    • 'partner' = is the variable that store the data send by your script; is 0 or 1 - by default it's -1.

    I extract the application test, upload to my server, and it's not working. The PHP part is 100% correct because I use it in the Construct 2 games.

    If you have nerves, the page where I need to send the URL where is the game running is in the image too. I'm trying to find a solution for more then 5 days. :))

    PS: If it helps you, I can provide the PHP script too.

  • silbedbg

    I saw that you know Javascript, and from what I understand you make games in Construct using scripts. Is there a chance to look at my problem? I'm try for some days to solve it, and I'm out of ideas.

    If you could, that would be great! :D

  • sorry, I do not know.

  • StefanN If you could provide a project, then I'm happy to test for you. I know relatively little about PHP. I've used it before and generally found it frustrating to be honest, but I can help with the JS parts.

  • Nepeo

    Sure. Here is the Construct 3 test project and PHP script: gofile.io

    For testing, you can use: zuzu.games/upload/our/get-content_NEW.php - the script is working properly, because it is used in my old Construct 2 projects. That page receive an URL, and search in the URL's example.com/ads.txt, testing if there is or not our Google Publisher ID.

    What else could I provide for you?

  • If you take a look at the developer tools you will see the request is failing because you haven't set any cors headers for your PHP script, and preview.construct.net is a different domain to yours.

    Also that script is firing a network request every tick, you probably want to do it less often than that...

  • I'm curious. Why not get your CORS header in the PHP file correct, get the referrer in the PHP script and just do this?

    + System: On start of layout

    -> AJAX: Request "http://www.zuzu.games/upload/our/get-content_NEW.php" (tag "partner")

    + AJAX: On "partner" completed

    -> Text: Set text to AJAX.LastData

    Seems like a lot of effort you're going through just to get a 1 or a 0 from a php file.

    Oh, and to solve your JQuery issue, I cheat. I just use this plugin:

    construct.net/en/make-games/addons/162/jquery-plugin

    That way, I don't have to mess with converting $'s.

    And here's an example I use for my CORS headers.

    //This attempts to grab the URL of the requesting domain (origin) using different methods.
    $http_origin = NULL;
    if (array_key_exists('HTTP_ORIGIN', $_SERVER)) {
     $http_origin = $_SERVER['HTTP_ORIGIN'];
    }
    else if (array_key_exists('HTTP_REFERER', $_SERVER)) {
     $http_origin = $_SERVER['HTTP_REFERER'];
    } else {
     $http_origin = $_SERVER['REMOTE_ADDR'];
    }
    
    //This is for testing. If no origin is found it displays a dump of the $_SERVER var to help
    //you figure out why. Once working correctly you can change the die() to provide a response showing
    //that the origin is invalid.
    if (!isset($http_origin)){
     var_dump($_SERVER);
     die("No Origin Server Error");
    }
    
    //This is also for testing purposes. It creates a small text file to list all of the incoming origins.
    //Once you verify the origins are correct, you can delete these lines.
    $myfile = fopen("origin.txt", "w") or die("Unable to open file!");
    $txt = $http_origin;
    fwrite($myfile, $txt);
    fclose($myfile);
    
    //And here's where I validate the origin against known good origins. In this case, the C3 preview
    //domain and my personal domain. You could validate this like you do in your script by comparing
    //the origin with a list from another URL. If the origin is correct, it sends the header saying
    //the origin has permission to use this script and that it can POST.
    if ($http_origin == "https://preview.construct.net" || $http_origin == "https://www.twistedvoid.com") {
     header("Access-Control-Allow-Origin: $http_origin");
     header('Access-Control-Allow-Methods: "POST"');
    }

    And thinking about it, you could just use this as your test of valid partners. If they are a partner, the Ajax request would send back no errors and the On "partner" completed request would succeed. If they aren't a partner, then you could test for the Ajax.OnError("partner") and it would be true.

Jump to:
Active Users
There are 1 visitors browsing this topic (0 users and 1 guests)