I have a jquery file in which i have the following code:
var QUESTIONS = ["Q11", "Q22", "Q33", "Q44", "Q55"];
var ANSWERS = [["Si", "No"], ["Si", "No"], ["Si", "No"], ["Si", "No"], ["Si", "No"]];
Now i want to load the questions and answers from the PHP.
Trolling ahead!
If you want to load javascript into the PHP Userspace, you will need to lex and parse it, then read it into your own PHP userspace.
Or, you could simply, just copy the content over to PHP and use it normally!
You have three choices here.
In the .PHP
file that generates your web-page, directly write the text for your JavaScript arrays as if they were HTML or plain-text.
Use an XMLHttpRequest
object to call a separate a .PHP
page that returns an XML response containing your entries. (You could also have it return JSON instead of XML.)
Have your PHP return JSON to a <script>
tag, which gets automatically parsed and executed on the client. (usually as a single global variable.)
dataServer.php
$response = array();
$response['questions'] = array("Q11", "Q22", "Q33", "Q44", "Q55");
$response['answers'] = array(array("Si", "No"), array("Si", "No"), array("Si", "No"), array("Si", "No"), array("Si", "No"));
print json_encode($response);
dataClient.js
$.ajax({
url: "dataServer.php",
dataType: "json",
type: "GET",
success: function(data, stat, xhr) {
alert(data.questions.toSource());
alert(data.answers.toSource());
}
});