0

No, this is not like the other questions:

I need to have a php variable in a client-side javascript file. I tried using ajax, but due to the application being Node.JS I cannot properly find the link to the php file on client side.

I'm making a draw my thing game and since its a small project I have the words in a phpfile. If I put them in javascript clients could use 'inspect element' to find all the answers, php doesn't allow them to.

Basically a word is given to one client that he has to draw, the other client guess that word. The 'server' should select a word that only the (drawing) client can see.

TL;DR: Get php variable in javascript within a node.js application. (Serverside or clientside doesn't matter)

Code so far

(Client) Word.js

$.ajax({
                url: 'util.php',
                type: 'POST',
                dataType: 'json',
                success: function(result){
                    console.log(result['word']);
                },
                error: function(){
                    console.log("Error retrieving word.");
                }
            });

Util.php

$words = array("", ""); shuffle($words);
   $selectedWord = $words[0];

   $rtn = array('word' => $selectedWord);
   echo($rtn);
1
  • There is a suggested edit on your question from the user Dub_. In case both accounts are yours, you can merge them like described here. Otherwise, login with the account this post got created with, to edit it without going through review and get rejected for "conflicts with author's intent". Additionally, if you add more information to the question, do it in a way that the original code/question remains valid. Commented Mar 22, 2016 at 16:50

1 Answer 1

2

Where you have...

echo($rtn);

... you want ...

echo json_encode($rtn);

Otherwise what your script outputs is just the word "Array".

Sign up to request clarification or add additional context in comments.

2 Comments

Yea, its a 404. can't locate the php file.
The only resolution is to use the correct path to the file. You wouldn't get a 404 error for any sort of server-side issue; it specifically means the file cannot be found.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.