I have a php script that is a bit of a mess and after a form entry, I need to get an address, and display it on a google map. The html and php is crammed into the same script so I essentially need to call the JavaScript as the PHP is happening. Is there a way to do this?
Thanks,
Alex
You can POST your from to a different frame (or iframe), so your page would not reload. The response of your PHP file which comes back to that frame can contain JavaScript code, which will be executed. Something like:
echo('<script type="text/javascript"> alert("Executed on client side"); </script>');
No, PHP executed by the server and returns the full response to the browser. JavaScript in the page is then executed by the client.
You can't call Javascript functions from PHP. You can set the Javascript to run when the page loads instead.
What you want is something like this:
<script type="text/javascript"></script>
var userAddress = "<?php echo $_POST['address']; ?>";
doSomethingWithAddress(userAddress);
</script>
If that code is on the page which you are POSTing the address to, it would take the address from the user, and write it into a javascript tag. The PHP will get executed first on the server, before building the HTML document. This new document has the variable available to the javascript.
I don't know how you would go about doing that, but this seems like a good place to start looking:
http://code.google.com/intl/en/
Related
I just found out that PHP can be used in Javascript like this:
<script>
function seeTime() {
alert("<?php echo time(); ?>");
}
</script>
<button onclick="seeTime();">Click Me</button>
The above code will popup an alert message with the Unix timestamp every time the button "Click Me" is clicked. But the problem is, the time remains the same everytime you click the button until the page is reloaded.
I know AJAX is the solution but is there any other way I can update the data inside the javascript code/file without using any external php file to fetch data from it with AJAX ?
I know AJAX is the solution but is there any other way I can update the data inside the javascript code/file without using any external php file to fetch data from it with AJAX ?
Yes, just don't use PHP at all:
function seeTime() {
alert(Math.floor(new Date().getTime()/1000));
}
You are getting confused between PHP and JavaScript. PHP is not being "used" in JavaScript. PHP runs on the server and generates the page, which is then sent to the browser.
<?php echo time(); ?> is replaced with the current timestamp, then sent to the browser which runs the JavaScript.
As far as I know it's impossible, PHP code is compiled server-side, so all you return from a php compilation are static value, you must use AJAX to refresh the time value.
You could set the time with JS if you wish.
I'm trying to replace a bit of javascript in my page via AJAX, but for some reason, AJAX wont replace it...
When I use:
alert(document.getElementById('treintracking').innerHTML);
I can clearly see the javascript from the script piece: (this is the opening line of the javascript piece)
<script type="text/javascript" id="treintracking">
For replacing the script I use this:
document.getElementById('treintracking').innerHTML = responseText;
So, why does AJAX not want to replace the javascript?
I've tested, and the php file used to generate the replacement javascript, works fine.
I also took into account that the to-be-replaced javascript already has tags around it, so I removed those in the php file.
But it still wont replace the content...
Also, if it put somefunction() in that javascript, will it then run, or do I have to do something special?
Note: the javascript script is generated in a php file.
SOLUTION:
I am now using this external solution, I don't have a clue how it works, but it works perfectly:
http://www.javascriptkit.com/javatutors/loadjavascriptcss2.shtml
[I took the loading script from the page source, as it wasnt in the article itself...]
Adding JavaScript via innerHTML does not get evaluated.
If you want to add new code, just set the source to a new external JavaScript file.
So instead of using an Ajax call, you just set the src
document.getElementById('treintracking').src = "new/path.php?a=b";
Another solution [that I would avoid at all costs] is eval().
You'll probably have to embed the new javascript inside a function, which may assign new contents to other functions, and then invoke the outer function. Won't be terribly pretty.
I'd like to pass some data from PHP to JavaScript without JSON.
The reason is because I don't want the data been readable by anyone if clicks on view page source.
So, I have a PHP like
print(<script type="text/javascript">a = "aaa";</script>);
In my HTML code this will be
<script type="text/javascript">a = "aaa";</script>
I can remove this in the client side, after loading the variable. By for example with jquery
$('script[type="text/javascript"]').remove();
And after the DOM will not have anymore the script tag, but the variable a.
Later if I type to the console window.a will be aaa.
But i do not want to show the <script type="text/javascript">a = "aaa";</script> in my HTML source code. Is this possible, to pass the PHP variable directly to the DOM?
Thanks for the help.
JavaScript is a client-side language. Whatever you pass to it (by whatever means) will be readable by the end user.
Removing the Script DOM won't help, as "view source" shows the HTML code as it was during download. If that is what you are concerned about, you can fetch the variable via an AJAX once the DOM has been loaded.
(But it still is readable by anyone who can read JavaScript (an re-run the AJAX call), use Firebug or Wireshark. It really only helps against a simple "view source".)
Here is what I'm trying to do...
$("div").prepend("<div id='comment-number'><?php the_comment_number(); ?></div>");
Is there some way to get this to work?
<div class="gallery-item">
<div class="comment-number"><!--?php echo htmlspecialchars(the_comment_number()); ?--></div>
</span>
<span class="gallery-icon">
<img src="http://mysite.com/test/wp-content/uploads/2011/06/fff-150x150.gif">
</span>
</div>
PHP is executed on the server, but JavaScript code (jQuery) is executed later, in the web browser. For that reason, PHP can produce JavaScript code, but JavaScript can't produce PHP code.
The <!--? in your posted output shows that something is filtering our your PHP code. So the problem isn't your PHP code, it's that you're not actually executing PHP code. If it's a .js file, PHP almost certainly can't be included.
If PHP were being evaluated (ex. if this were in a <script> tag in a .php file), this should produce valid JavaScript code that will do what you want:
$("div").prepend("<div id='comment-number'><?php echo htmlspecialchars(the_comment_number()); ?></div>");
1) php is SERVER side scripting
2) javascript is CLIENT side scripting (generally)
so this is what happens:
1) User opens up your page http://example/
2) Your CLIENT sends GET request to http://example/ server
3) Apache (given you run on it) captures the request, based on the server config approaches index.php (index.html, etc). If php is installed, your index.php will be parsed by mod_php module
<<<< this is where SERVER side scripting is activated
4) outcome of the parsing of index.php will be then transferred back to CLIENT
5) CLIENT will digest the outcome received by SERVER
6) If there are javascript calls, those are executed either immediately OR when document is loaded (based on approach)
That's it. Here normal request life ends.
NOW if you want your page to dynamically update some parts of it, here is how you do that:
1) Usually to update your page dynamically, you would use AJAX approach. When AJAX request is created, 2-7 happens again, but this time the caller is your ajax process and information which is received is sent back to that process to decided what to do with it.
Okay, some coding:
1) index.php
<!-- include jquery, etc //-->
<div id="comments"></div>
<script>
function fetch_comments(){
$.get("ajax.php", null, function(data)){
// this is called, when response from SERVER is received
$("#comments").prepend(data);
setTimeout("fetch_comments", 5000); // fetch again in 5 seconds
}
}
$(document).ready({
fetch_comments();
});
</script>
2) ajax.php
<?php
//fetch comments, return them for CLIENT
echo "<p>Comment on " . date("Y-m-d H:i:s") . "<br />Lorem Ipsum</p>";
This should help you understand the whole process. Did not test the code, but should be quite ok.
do a .ajax() query to PHP script that will provide you value of the_comment_number(); and put result to comment-number by $("#comment-number").prepend(result); on success event in ajax query.
Remebmer that PHP script have to have connection to database and pass to it all variables you need (like entity id, article id, page etc.). You can do it by GET or POST.
Request is sended by browser so session/cookies will be the same unless you changed it in current request.
PHP is executed on the server side so you cannot call it from javascript
You can try something like this which will render once the page loads
$("div").prepend("<div id='comment-number'>"+ <?php the_comment_number(); ?> +"</div>");
Couldn't you just add the value directly to the template instead of using javascriot? eg:
<div class="gallery-item">
<div class="comment-number"><?php echo (the_comment_number());?></div>
...
</div>
Also you have a </span> tag with out matching <span> tag in your example.
As already told, you can't produce or call php code from javascript directly(you need to make an ajax call or form submit). You need to make ajax call using jquery to fetch the comment number and then update it into div.
However, you may want to look at this library - http://www.phplivex.com/ .It may help you in doing things your way. It allows you to call user defined php functions in javascript using AJAX internally.
Reading through this disccussion and from what i understand you want to acheive.. You gotta figure how your page is served. If it is an .php file that is serving the content, then you wont need Javascript at all and could get your function call to work by adding the function between the div as so..
<div class="comment-number"><?php echo htmlspecialchars(the_comment_number()); ?></div>
Assuming you don't have access to the .php or if its a .html/htm page that serves the content then your only bet would be to use ajax. That is make an ajax call to a php file(on the same domain) that makes your function call and echos the comment no. The Ajax will retrieve the echo'd comment no. which you can append/prepend to the desired
Here is the code:
$('#sousmenu a').click (function (){
startSlideshow(<?php echo json_encode(glob("photos-" .$_GET["folder"]. "/*.jpg"));?>);
return false;
});
The question is I like the HREF to change and get caught by PHP, now it doesn't do anything, but writing the ?folder=portraits works.
Here is the page.
**** Simpler *****
Maybe I am not clear, it happens sometimes!
I want the link href to be send to this PHP function,
<?php echo json_encode(glob("photos-" .(i what the href link). "/*.jpg"));?>
so clicking on the link animaux will send animaux to the glob() PHP function and will get all the .jpg files in the photos-animaux folder.
Clicking on the portraits will send the photo-portraits, etc.
If you want to modify the URL and have the added/changed variable picked by PHP interpreter you have to reload your page. Just altering the URL doesn't do anything because JS is executed after PHP processing.
If your site is on http://example.com and you wish a myparam with value test to be passed to PHP you should add something like this in your JS:
document.location = 'http://example.com?myparam=test';
This will reload your page adding a new param which can be accessed in PHP by simply using $_GET['myparam'] variable.
You may also want to consider using AJAX to dynamically changing the contents of your page without having to refresh the whole page, but that's a little bit more complicated.
Look at the source in your browser.
Php is server-side, and that means you need to use ajax or reload whole page to get a response.
There is a nice ajax part of tutorial on jquery website, after reading it you should be able to do what you want: http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery#Rate_me:_Using_Ajax