I'm writing a program that will generate random numbers on both JavaScript and PHP pages and display them on the JavaScript/Html page.
So far I have both pages successfully generating the numbers, but I don't know how to reach out from the JavaScript page to the external PHP page to retrieve the number and store it into a JS variable.
Here's what I have so far.
JavaScript:
function roll()
{
var rollOne; //= Math.floor((Math.random() * 6) + 1);
var rollTwo;
var request = new XMLHttpRequest();
request.open("GET", "filename.php", true);
request.send();
}
I know the JS random is commented out, that's not important right now.
PHP:
<?php
sleep(5);
$random =(rand(1,6));
echo $random;
?>
So how do I take $random from the php document, send it over to the JavaScript page, and store it into a variable to access later?
I'm sure a similar question has been asked thousands of times before on this site, but from what I have searched I haven't found anything that made sense to me.
The Mozilla docs on AJAX explain it well. Before calling .open and .send, set up a function for XMLHttpRequest to run when the response comes back from the server:
request.onreadystatechange = function() {
if (request.readyState === XMLHttpRequest.DONE) {
// The request is complete
if (request.status === 200) {
// Server responded with HTTP status code 200 (OK)
// Here's your server's random value
random = request.responseText;
} else {
alert('There was a problem with the request.');
}
}
}
You can access the responseText value of the returned data. In other words, the data that you echo from php can be accessed in your javascript using responseText and stored in a variable.
Related
I am in need of a little help with a small bit of my code that is essential to my application. I am making a small clicker game, and I want users to be able to save and load data via PHP to my server. I do not want to use Local Storage to make it harder for anyone to edit their economy and "cheat". When the user clicks on a save button I have, it fires my vue method which initializes the saving. I have had no problem getting the data into a JSON format, however I cannot get PHP to read this data via POST. I have checked for network headers, and it shows that stuff is being sent, it seems that PHP just isn't catching it. I'll include the code for the JS part and PHP part below. The PHP is only set to echo if the array_key_exists right now, as after getting this sorted out I will easily be able to handle the rest. Any help would be greatly appreciated!
I have tried to follow this, which has not worked so far Send JSON data from Javascript to PHP?
JS
saloOut: function() {
var saveData = {
saveMoney: this.money,
saveCrystals: this.crystals,
};
saveData = "saveData=" + (JSON.stringify(saveData));
var sendData = new XMLHttpRequest();
sendData.open("POST", "salo.php", true);
sendData.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
sendData.send(saveData);
console.log(saveData);
}
PHP
<?php
if (array_key_exists("saveData", $_POST)) {
echo "<p>SALO Ready!</p>";
}
?>
Decode the JSON string at the PHP end before accessing values, like this:
<?php
if(isset($_POST['saveData'])){
$result = json_decode($_POST['saveData'], true);
// use $result['saveMoney'] and $result['saveCrystals'] accordingly
}
?>
Update# 1:
As OP commented below, I expect that it will print "SALO Ready" but it is instead doing nothing
That's because you are not using responseText property of XMLHttpRequest object to see the text received from the server. Use below snippet to see the response text.
saloOut: function() {
var saveData = {
saveMoney: this.money,
saveCrystals: this.crystals,
};
saveData = "saveData=" + (JSON.stringify(saveData));
var sendData = new XMLHttpRequest();
sendData.open("POST", "salo.php", true);
sendData.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
sendData.send(saveData);
sendData.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
}
};
}
Reference: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseText
I'm a complete and utter AJAX noob and have been sitting with the same problem for the last 5 hours.
My script code
<script language='javascript'>
function upvote(id ,username)
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
}
};
xmlhttp.open("GET", "vote.php?id=" +id+"&username=" +username, true);
xmlhttp.send();
}
</script>
My onclick link,
<a href='javascript:void(0)' onclick='upvote($id,$username)'></a>
$_GET is used to retrieve parameters sent via the URL of the page. For example
../vote.php?id=3&username=anor
My php file works perfect when i tried that.
I don't think there's anything wrong with the PHP anyway. For some reason however, xmlhttp.send(params) is still not sending the required variables to the vote.php file. I tried post AJAX request but it didn't work either.
edit them
If php file
$id = '1';
$username = 'suman';
echo '';
?>
If this is part of your PHP code
onclick='upvote($id, $username)'
it won't work. It should be
onclick='upvote($id, "$username")'
instead. Let's see the example that you posted: $id=3 and $username=anor. This would result in
onclick='upvote(3, anor)'
As long as there is no Javascript variable with the name anor, this would be equivalent to
onclick='upvote(3, undefined)'
Do you get that?
PS: The upvote function itself seems to be fine
Note: I am aware that json/jquery appears to be the preferred way of doing things at the moment. Nevertheless, I am using just plain old ajax without json/jquery.
I have set my website up so that there are no php calls in the index page. Instead, I load scripts which handle most link clicks via ajax calls back to the server. Theoretically, the server returns the response text, and then the javascript on readystatechange function (set to ajax_response()) inserts the response text directly into the div container with id="innercontent".
Here is the code for my main javascript file:
function ajax()
{
try{ var request = new XMLHttpRequest()}
catch(e1){
try{ request = new ActiveXObject("Msxml2.XMLHTTP") }
catch(e2){
try{ request = new ActiveXObject("Microsoft.XMLHTTP") }
catch(e3){ request = false }
}
} return request
}
function ajax_response()
{
if(this.readyState == 4){
if(this.status == 200){
if(this.responseText != null){
document.getElementById('innercontent').innerHTML = this.responseText
} else alert("Ajax error: No data received")
} else alert("Ajax error: " + this.statusText)
}
}
function fetch_document(opcode)
{
params = "opcode=" + opcode
request = new ajax();
request.open("POST", "/site-php/fetch_document.php", true)
// request.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
// request.setRequestHeader("Content-length", params.length)
request.setRequestHeader("Connection", "close")
request.onreadystatechange = ajax_response()
request.send(params)
}
function fetch_comic(series, page_number)
{
params = "series=" + series + "&page_number=" + page_number
request = new ajax();
request.open("POST", "/site-php/fetch_comic.php", true)
// request.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
// request.setRequestHeader("Content-length", params.length)
request.setRequestHeader("Connection", "close")
request.onreadystatechange = ajax_response()
request.send(params)
}
There doesn't appear to be any syntax errors in the javascript, so I thought maybe that the problem was on the server side. But no errors are logged in /var/log/error_log.
Here is the code for my php functions:
<?php
require_once "kolodruid.php";
require_once "login.php";
if(isset($_POST['series']) && isset($_POST['page_number'])){
$series = $_POST['series'];
$page_number = $_POST['page_number'];
}
$mysql_db = mysql_connect($mysql_host, $mysql_user, $mysql_pass);
mysql_select_db("webcomics");
mysql_close($mysql_db);
$fd = $docroot . "test.html";
$msg = file_get_contents($fd);
echo $msg;
?>
Note that the actual functionality of this function is to fetch webcomic information from a database. In the process of trying to figure out what has gone wrong, however, I ended up simplifying the function to try to see if just a simple echo statement would work.
also:
<?php
require_once "kolodruid.php";
$opcode = $_POST['opcode'];
switch($opcode){
case "ABOUT":
echo file_get_contents("about.html");
break;
default:
echo file_get_contents("whoops.html");
break;
}
?>
When I look at the firefox console network tab, clicking on the links "webcomic" generates green lights all the way. I check to see if the parameters tab has any data, and it does. The response tab, however, doesn't contain anything.
I've checked that all the files are reachable and in places that the server has access to. I also took out the setrequestheader() functions in the javascript, as it seems that was causing a fatal error. I then re-enabld the close connection setrequestheader() to see if maybe I actually still had to set that one manually. It seems that it didn't generate a fatal error, so I didn't comment it back out.
I've checked the php code for syntax errors, and also checked the javascript code for syntax errors. Both come out clean. I've restarted my server several times (it's localhost), and have also restarted my mysql database server out of desperation.
At this point, the whole enterprise had devolved into just making minor edits in the desperate hope that SOMETHING gives a clue as to what is going on. I have changed the asynchronous calls to synchronous calls to see if that maybe was the problem, but to no avail. (Thus, I rechanged them back to asynchronous calls).
I feel like it's something really stupid and/or obvious, but I've been pouring over the code for hours, and am afraid I can't see the forest for the trees by now. Please help!
Thank you for reading this. I'm aware that Javascript questions are pretty common, but I've been reading question and answer sites for hours, too. D:
In case it matters, I'm using Apache version 2.4.6
Thank you for you help!
It turned out to be something mind-blowingly obvious after all. I was calling the function ajax_response() and assigning the value to onreadystatechange. Removing the parenthesis after ajax_response produced the desired behavior.
I've done created a webpage, set up appache2 on ubuntu server so I can view this page over the internet. I've installed php5 and MySQL and would like to access information in the database on the webpage that I've created.
Right now, I've got a file test.php that accesses the database and puts some of the information into variables. I've scripted using javascript something that will change the webpage content at the click of a button.
Now, the webpage crashes whenever the button is pushed as it says the variables are undefined or null references. Fair enough, but my question is how does one access variables on a .php file through the webpage? Can a browser use information in the .php file if I script it into the page?
I was told that the php file would be parsed automatically. I'm guessing that server side this page is being accessed but I can use it through web browser.
Edit:
//check connection
if (mysqli_connect_errno()){
echo "failed to connect to MySQL: " . mysqli_connect_error();
}
$grab = mysqli_query($con, "SELECT * FROM table");
$row = mysqli_fetch_array($grab);
$name = $row["name"];
$color = $row["color"];
$price = $row["price"];
$n1 = $name[0];
$c1 = $color[0];
$p1 = $price[0];
?>
Ok so I changed the php file to this, so now all it is doing is defining variables. I installed a couple of MySQL mods and no problems now.
next issue is how do I get use php variables in javascript
function load(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "test.php", true);
xmlhttp.send();
xmlhttp.onreadystatecahnge = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("itemNameLink1").innerHTML = "<?php echo $n1;?>;
}
}
}
So onload this ajax function should run and change itemNameLink1 to the php variable $n1, only it doesn't and I just get an empty string. Everything should be set up right but using the php variable seems impossible. would it be any easier with the jquery get command, I'm guessing that unless I sort this out I'm gonna struggle.
I'm also assuming a few things, I've checked error logs and the php file is active assuming I've connected right it should be accessing the database. I'm very new so I do not know how to test this.
I'm also assuming that when php file is in the server webpage file directory. that it is automatically working. again very new to setting up a server so using ubuntu server and being familiar with all the commands that I need to use or how apache2 operates is difficult for me.
PHP Is executed on the server, your client receives the result as a plain text/html document.
Your browser runs the javascript when it received the plain document, so you can't access PHP vars directly with javascript.
But you could set javascript variables when the page is generated on the server like this
<?php $myPhpVar = 'Hello World'; ?>
<script>
//This line would result in var test = "Hello World"; when send to client
var test = "<?=$myPhpVar?>";
alert(test);
</script>
Furthermore you can execute requests to your server with javascript (so you can read the result from test2.php as example, and use that somewhere on your page). http://en.wikipedia.org/wiki/Ajax_(programming)
Pure javascript: http://en.wikipedia.org/wiki/XMLHttpRequest
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
var DONE = this.DONE || 4;
if (this.readyState === DONE){
alert(this.readyState);
}
};
var action = 'doSomethingOnServer';
request.open('GET', 'test2.php?action=' + action, true);
request.send(null);
Jquery: http://api.jquery.com/jquery.ajax/
<script>
var action = 'doSomethingOnServer';
$.ajax({
url: "test2.php?action=" + action,
}).done(function(result) {
alert(result);
});
<script>
For testing if your php works on your server create a file info.php (or something). and add this to the file
<?php phpinfo(); ?>
If you access that page you should get a page with a lot of information about your php configuration.
I'm not sure how you did install your php, but on a development machine you can change a few things in your php.ini that makes life easier
display_startup_errors = 1
display_errors = 1
error_reporting = E_ALL
See http://php.net/manual/en/errorfunc.configuration.php#ini.error-reporting when you change your php.ini don't forget to restart your apache
JSON Example:
data.php
<?php
$db_result = array(array('name' => 'record1'), array('name' => 'record2'));
echo json_encode($db_result);
?>
index.php
<script>
$.ajax({url: 'data.php', dataType: 'json'}).done(function(result) {
//result = an object from your database (in this case an array with objects with the property name)
alert(result);
alert(result[0].name);
}
</script>
I am a beginner in both Ajax and MongoDB. I was hoping to visualize some of the data in my MongoDB using a web browser (which, for the moment, is running on the same host). For this, I thought it might be possible to get the data using XMLHttpRequests. I am running MongoDB with the --rest option and I checked that when I load hxxp://localhost:28017/test_db/ss_test/
on Firefox, I get the proper reply (a JSON document with the data in the ss_test collection of the test_db database). So far, so good.
I then wrote the following JavaScript function which I connected to the "onclick" of a button:
function makeRequest()
{
var myrequest = new XMLHttpRequest();
myrequest.onreadystatechange = function()
{
alert("status=" + myrequest.status + " readyState=" + myrequest.readyState)
if (myrequest.status == 200 && myrequest.readyState == 4)
{
// ...do something with the response
}
}
myrequest.open("GET", "http://localhost:28017/test_db/ss_test/", true);
myrequest.send();
}
So, when I load the html file on Firefox, open the console and click on my button, I see that the http request is indeed made, the status code is "HTTP/1.0 200 OK" and a response with Content-Length: 219257 is delivered, which looks great. However, the XMLHttpRequest object does not report the status=200. The alerts that pop up report a constant status of 0 as the readyState progressively becomes 1, 2 and 4 and my if statement is never true.
Could anyone please tell me what I am doing wrong? In the beginning I thought it was because my html was loaded on the browser by the file protocol or that I was seeing some same-origin policy related issue, but then I put the html file on a web server on localhost and loaded it from there and nothing changed. Thank you very much for any replies!
you need to create a function to handle the request.
http://www.ibm.com/developerworks/web/library/wa-ajaxintro2/
http://www.ibm.com/developerworks/library/wa-ajaxintro3/
function makeRequest()
{
var myrequest = new XMLHttpRequest();
myrequest.onreadystatechange = create_this_function()
{
}
myrequest.open("GET", "http://localhost:28017/test_db/ss_test/", true);
myrequest.send();
}
#
function create_this_function()
{
alert("status=" + myrequest.status + " readyState=" + myrequest.readyState)
if (myrequest.status == 200 && myrequest.readyState == 4)
{
// ...do something with the response
}
}