Jump to content

Equal javascript variable to php echo?


ava_barbilla

Recommended Posts

Hey guys. I have received great support from this forum on my last topic and I needed a little help. I was doing a javascript which automatically refreshes a div after a certain amount of time which looks like this:

 

<div id="demo">Test</div>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
$(document).ready(
function() {
setInterval(function() {
var num = Math.random();
$('#demo').text(num);
}, 3000);
});
</script>
This makes complete sense. The javascript refreshes the div after 3 seconds giving a random number. My question is: How can I equal the variable "num" to a php echo code that would present a random variable as well. I have tried something like this:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
$(document).ready(
function() {
setInterval(function() {
var num = <?php echo(rand() . "<br>")?>; <-- I have tried putting quotes around the php code, removing "php" from "<?php", etc.
$('#demo').text(num);
}, 3000);
});
</script>
In this case scenario, I utilize a random number just as a test. At a further stage, I would replace the php code that echoes a random number by this:

<?php echo do_shortcode( $content ) ?>

 

The reason for this is because I use Wordpress. I would like to equal a javascript variable by echoing a shortcode from the server side. This shortcode contains some data that refreshes with new content and instead of loading the entire page again, I only update the div's that are influenced by the javascript.

 

Many Thanks!!

Link to comment
Share on other sites

I am going to move this to the PHP forum.

 

As you may or may not know, PHP executes before JS does (the browser only outputs what the server returns), so if you are looking to mix the two like this, you will need to render the JS with PHP.

  • Like 1
Link to comment
Share on other sites

It sounds like what you're looking for is an ajax request, where every three seconds you use Javascript to send an ajax request to PHP for another value. Is that what your'e trying to do? If you want to duplicate the first piece of code, a random number every 3 seconds, except you want PHP to generate that random number, then you need to use ajax.

  • Like 1
Link to comment
Share on other sites

Maybe render was a bad term. If you are trying to use echo, and want JS to show values from PHP variables, then you would need to output the JS at the same time as a PHP script run.

 

Or, as JSG suggested, you could use AJAX to request the value from a PHP script instead. That might work better for you in this situation given what you've presented so far.

  • Like 1
Link to comment
Share on other sites

Well I am I bit new to this and have been working my way up in javascript and am starting with php, so these terms are not something I use every day. What I do know is that by rendering I am making sure that javascript executes at the same time as php in order to coordinate two languages (one client-side and the other server-side) to run basically "parallely" which makes sense; I have understood that. Could you provide any demo or link which describes any method of rendering javascript? How and where would I use rendering in my case? Or possibly explain: How I can convert this script into Ajax? Any advice or demo would really help.

 

Regards!!

Link to comment
Share on other sites

What I do know is that by rendering I am making sure that javascript executes at the same time as php

It doesn't, ever. This is the basic process:1. The browser sends a request to the server for a (PHP) page.2. The server starts PHP and sends it the PHP code to execute.3. PHP executes and produces any output (HTML, Javascript, CSS, etc).4. The server sends all output to the browser as the response, then PHP shuts down.5. The browser receives the response and renders the HTML elements, and also executes the Javascript.Note the difference between steps 4 and 5. At the end of step 4, PHP execution ends. During step 5 is when the browser executes Javascript. By the time the browser starts executing Javascript everything on the server is finished, PHP is done. There's no connection between the browser and PHP.What thescientist was talking about is the fact that you can use PHP to output Javascript as well as CSS, which happens in step 3. Normally you use PHP to output HTML elements:
<?phpecho '<div>' . $some_content . '</div>';?>
You could just as easily use PHP to output Javascript (or CSS, for that matter):
<script type="text/javascript">var num = <?php echo mt_rand(1, 100); ?>;alert(num);</script>
Just keep in mind that the PHP code runs on the server before the Javascript runs in the browser. If that mt_rand function returns 53 as the random number, then this is the only thing the browser sees:
<script type="text/javascript">var num = 53;alert(num);</script>
You could refresh the page to execute PHP again in order to generate a new random number, but once PHP is finished that's it, it's not going to keep running in parallel with Javascript.If you need Javascript to interact with PHP while the page is running, without refreshing the entire page, then that's what you use ajax for. You can use Javascript to send an ajax request to the server and have it run a PHP script, have PHP do whatever it does and produce some output like before, and the server will send that output back to Javascript and then you can use it on the page. That's how sites like Facebook, Gmail, etc (even this forum) let you do things on the page without the entire thing refreshing. That's Javascript sending requests to the server in the background.There are some ajax examples here:http://www.w3schools.com/ajax/
  • Like 1
Link to comment
Share on other sites

Wow great explanation. Thanks once again. I have been researching since yesterday on how to make an Ajax request and came up with this:

 

function ajax_post(){
// Create our XMLHttpRequest object
var xmlhttp = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
// Set content type header information for sending url encoded variables in the request
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var return_data = xmlhttp.responseText;
document.getElementById("demo").innerHTML = return_data;
}
}
xmlhttp.open("POST", url, true);
xmlhttp.send(); // Actually execute the request
document.getElementById("demo").innerHTML = "processing...";
}
I saved this script as a file under: http://localhost:8888/.../javascript/test.js <-- I have tested other scripts saved at this location and they work perfectly fine. My php file contains the following data (it is named "test.php"):
<?php
echo(rand(10,100));
?>
After I make the request to the php file which should display a random number according to the php code, my html looks like this:
<div style="display:none;">
<body onload="ajax_post()"> <------ Here you can see that I have called the function which executes the AJAX Request after the page has loaded.
<script type="text/javascript" src="http://localhost:8888/.../javascript/test.js"></script>
</body>
</div>
<div id="demo"></div>

 

I keep refreshing the page and nothing appears. Does it have to do with my php code? Perhaps my Ajax request is wrongly structured? In terms of Ajax request, I have tried "GET" and "POST" as well and still nothing happens. As you know I am new at Ajax and the might syntax my not make sense... Thank you for the great support.

 

Regards!!

Link to comment
Share on other sites

Are you getting any Javascript errors in the console?

 

Check to see whether the program is actually completing the request by logging data from inside the readystatechange handler:

xmlhttp.onreadystatechange = function() {    console.log(xmlhttp.readyState, xmlhttp.status);    if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {        var return_data = xmlhttp.responseText;        console.log(return_data);        document.getElementById("demo").innerHTML = return_data;    }}

On this forum, wrap your code between [CODE] and [/code] tags so that we can see it properly.

  • Like 1
Link to comment
Share on other sites

Thanks Foxy Mod. I have logged the data and still nothing appears. Does it have to do with this maybe:

 

 

xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

 

What I have done was to combining the Ajax request from W3Schools and from this link (http://www.developphp.com/video/JavaScript/Ajax-Post-to-PHP-File-XMLHttpRequest-Object-Return-Data-Tutorial):

 

my_parse_file.php

 

 

<?php echo 'Thank you '. $_POST['firstname'] . ' ' . $_POST['lastname'] . ', says the PHP file'; ?>

 

And the html example looks like follows:

 

 

<html><head><script>function ajax_post(){    // Create our XMLHttpRequest object    var hr = new XMLHttpRequest();    // Create some variables we need to send to our PHP file    var url = "my_parse_file.php";    var fn = document.getElementById("first_name").value;    var ln = document.getElementById("last_name").value;    var vars = "firstname="+fn+"&lastname="+ln;    hr.open("POST", url, true);    // Set content type header information for sending url encoded variables in the request    hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");    // Access the onreadystatechange event for the XMLHttpRequest object    hr.onreadystatechange = function() {    if(hr.readyState == 4 && hr.status == 200) {    var return_data = hr.responseText;document.getElementById("status").innerHTML = return_data;    }    }    // Send the data to PHP now... and wait for response to update the status div    hr.send(vars); // Actually execute the request    document.getElementById("status").innerHTML = "processing...";}</script></head><body><h2>Ajax Post to PHP and Get Return Data</h2>First Name: <input id="first_name" name="first_name" type="text">  <br><br>Last Name: <input id="last_name" name="last_name" type="text"> <br><br><input name="myBtn" type="submit" value="Submit Data" onclick="ajax_post();"> <br><br><div id="status"></div></body></html>

As both examples deal with input forms, I thought to apply the same idea but instead of returning perhaps a "suggestion" for the first and last name like W3Schools stated, simply getting the php code from an external file. As I mentioned earlier, this may have to do with the header. What I may have also thought was that in the previous examples you can see that the variables are sent

hr.send(vars);
given that earlier
 var vars = "firstname="+fn+"&lastname="+ln;
, but I do not know if this is really relevant. The idea of all this is to make an easy Ajax request which just picks some php code and places it on my html. Do I have to change something in the php? Something in the Ajax call? Does this work for you Foxy Mod?

Best!!

Link to comment
Share on other sites

If absolutely nothing is appearing in the console that means the request isn't being sent.

 

One thing that might be interfering is that your <input> element is a submit button. If you have an actual form in your code with a real submit button then the event handler should go right on the <form> element instead of the button:

<form method="POST" onsubmit="ajax_post(); return false">

If there is no <form> then change your <input> to type="button".

Link to comment
Share on other sites

Sorry I forgot to say, the above code was just an example. My actual script is:

 

function ajax_post(){    // Create our XMLHttpRequest object    var xmlhttp = new XMLHttpRequest();    // Create some variables we need to send to our PHP file    var url = "http://localhost:888...-files/test.php";    // Set content type header information for sending url encoded variables in the request    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");    // Access the onreadystatechange event for the XMLHttpRequest object    xmlhttp.onreadystatechange = function() {   if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {   var return_data = xmlhttp.responseText;document.getElementById("demo").innerHTML = return_data;   }    }    xmlhttp.open("POST", url, true);    xmlhttp.send(); // Actually execute the request    document.getElementById("demo").innerHTML = "processing...";}

 

I do not use an input form. Just as I depicted previously, instead of having a button, I load the function using:

 

<div style="display:none;"><body onload="ajax_post()">     <------ Here you can see that I have called the function which executes the AJAX Request after the page has loaded.<script type="text/javascript" src="http://localhost:888...ascript/test.js"></script></body></div><div id="demo"></div>
Link to comment
Share on other sites

I think you need to fix your HTML. The <body> element cannot be inside any other element except the <html> element. Pass your code through the HTML validator.

 

Since the <div id="demo"> is outside the <body> element, it doesn't exist when the body has loaded.

  • Like 1
Link to comment
Share on other sites

I have put the body tag inside a div with other scripts and it works perfectly fine. I checked it just in case and just displayed the body tag by its own with the div id="demo inside" and nothing appears. If nothing appears could it not be the Ajax request? I mean, does it make sense to you or is there something missing? How would you organize or structure the Ajax request in terms of getting the php code and placing it in html? If it is not too much work for you of course.

 

Many Thanks!!

Link to comment
Share on other sites

The <body> element should be the parent of all other elements except the <head>. Your HTML neesd to be valid if you want Javascript and CSS to work properly. To know if your HTML is valid, pass your code through the validator: http://validator.w3.org/

 

This is how a website structure should be:

<!DOCTYPE html><html>    <head>        <title>AJAX request</title>        <script type="text/javascript" src="http://localhost:8888/.../test.js"></script>    </head>    <body onload="ajax_post()">        <div id="demo"></div>    </body></html>

The <!DOCTYPE> declaration tells the browser what language and version the page is using. The <html> element is the root of the entire website. The <head> element contains information about the page. The <body> element contains the content of the page.

  • Like 1
Link to comment
Share on other sites

Wow I have tried that as well and it still does not work. I have been working with html and never had a problem with the structure. It must be the Ajax request or not? Sorry to ask you again, how would you structure the Ajax request? Simply speaking, a way to use javascript in order to make an Ajax request which will execute some php code stored in an external file and return the result in a div. My external php file looks like this:

 

 

<?phpecho(rand(10,100));?>

 

This script works fine and presents a random number every time the page is refreshed, so I can assume that my php is working fine

<script type="text/javascript">var num = <?php echo mt_rand(1, 100); ?>;alert(num);</script>
Link to comment
Share on other sites

That code should work.

 

Keep the HTML as I showed it, the HTML is fine. Check your Javascript.

 

Open the Javascript console in your browser's developer tools to check for errors. Check the Network tab in the developer tools to see the AJAX request and the response from the server.

  • Like 1
Link to comment
Share on other sites

Aaaaaah you were right. I have learned something new. Look at this:

 

Uncaught InvalidStateError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED.

 

This console error showed up. If I delete the 'setRequestHeader' this shows up:

 

What could be causing the error?

Link to comment
Share on other sites

First of all, it means that setRequestHeader() has to be called after .open()

 

Are you loading this page on your localhost or are you just double-clicking it in your filesystem? AJAX on your desktop can't read PHP on localhost. Make sure your HTML page is also being executed on localhost.

 

If that's not the mistake, then the port number of your HTML page and of the PHP file you're trying to request are probably different. Either remove the port number from the URL or make sure they're both the same.

Link to comment
Share on other sites

Yes, I am using a localhost and installed Wordpress. Both the php file and the script file are stored under "wp-content" folder. Javascript and Ajax is executed not by double-clicking it on the desktop, but directly from my Wordpress site as if it were live. Once I place setRequestHeader() after .open(), the error is removes and I have to say the file could not be opened because the link was incorrect. Now I have inserted the correct path to my php file, my console is clear and still nothing appears. :facepalm:

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...