Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Passing Twine variables to PHP

Hello,

I've done some research on this, but everything I find doesn't seem to function properly. I'm trying to pass variables collected in twine to PHP so that I can print them as a txt file. I have worked out the PHP stuff, so that's not the issue, but when I try to pass twine variables via AJAX, I get an undefined error.

I'm using Twine v. 2.0.10 with SugarCube 1.0.32.

I'm collecting variables with the following:
Name: <<textbox "$name" "">>
Email: <<textbox "$email" "">>

Under story Javascript I have defined the sendAjax function:
//requires jquery
function sendAjax() {
$.ajax({
type: "POST",
url: "receive-ajax.php" ,
data: { name: state.active.variables.name, email: state.active.variables.email },
success : function() {

}
});
}

Then I use the following in a passage to trigger the function:
<a id="cancel" href="#" onclick="sendAjax()">Send Ajax</a>

When I triger sendAjax, I get the following error:
"Error: ReferenceError: sendAjax is not defined."

What am I doing wrong? Any help you can provide would be greatly appreciated.






Comments

  • note: I am going to assume that your story HTML file and the receive-ajax.php file are hosted on the same domain, that the Javascript in your sendAjax function is correct, and that your receive-ajax.php file works correctly.

    Your problem is one of Variable Scope, you created the Javascript function in one scope (the Story Javascript area) and you are trying to access that https://msdn.microsoft.com/en-us/library/bzt2dkta(v=vs.94).aspx in a different scope (a HTML elements onclick handler in a passage).

    For your solution to work you would need to make the function Global, and the most common way people do this is by adding it to the global window object.
    window.sendAjax = function() {
    	//Stuff goes here.
    };
    
    ... although you should first check to see if that method already exists on the window object before creating it, and maybe think about using a namespace.
  • You're brilliant! Thank you so much. It works perfectly.
  • Hey vicgeb!

    You said you have worked out the .php-stuff. Could you give us a little hint on how you went on with that?
    I am currently in need of triggering a php script at the end of certain passages, any help would be greatly appreciated.

    thanks in advance,

    richVIE (twine2/harlowe)
Sign In or Register to comment.