AJAX - replace javascript in page: ajax won't replace the javascript - php

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.

Related

How can I refresh embedded PHP code from the client side?

Basically, at the click of a button I need to refresh a div that contains embedded PHP. I tried using .html() in jQuery to reload the contents of the div, but it didn't change anything so I'm assuming it's not recalling the PHP (because the PHP should be changed at this point). It's probably just rewriting the HTML that was outputted by the PHP when the page loaded. I also tried appending something to the new HTML load so I could see it was at least refreshing the HTML code, and it was. It looked something like (if "updateObject" is a variable that contains the location of the div):
updateObject.html(updateObject.html() + " random text");
I also fiddled around with the .load() jQuery method, but it seemed to be for external PHP files (and at this point I can't change my embedded PHP to external PHP).
Any thoughts? Thanks!
EDIT: The biggest problem I've had is that, with my limited knowledge of web dev, I need to have the PHP embedded. If I make it a separate file, I'd have a very difficult time finding it because I honestly don't understand how the files get put together through the framework we're using (Drupal). I did try using an external PHP file but I couldn't figure out how to find it. Even if I put it in the same directory as this HTML file, it doesn't seem to be easy to find.
You are to have 2 files:
PHP
This contains the data you want to show.
HTML
This is the one showing the php content.
In PHP you can put whatever you want. But the HTML once is loaded is loaded and the only way to have some more content into it is to make what is called an asynchronous call, which means a call after the page has been loaded.
To do this you are to use jQuery and call the $.post (or $.ajax), using this syntax:
$.post('filename.php', function(dataFromPhp){
//actions to do once the php has been read
})
So in your case you can make a function that reads the php every time the click is done on a div/button/other DOM object; like so:
function updateDivContent(whatDiv){
$.post('filename.php', function(dataFromPhp){
if(dataFromPhp){
$(whatDiv).html(dataFromPhp)
}
})
}
So if you want the div to be refreshed (and reload the php) you are to connect that function to an event and specify the div you want to show the data:
$('#myBtn').click(function(){
updateDivContent('#myDiv');
})
Refer to this documentation for further informations: https://api.jquery.com/jQuery.post/

Placing javascript/jquery functions in a universally accessible page

I am trying to clean up my pages, and one of the major ways that I am doing so is to put JavaScript and JQuery functions into a file called 'scripts.js' that is automatically accessed upon page load.
I've run into a problem with functions that use php to call from the page itself. For example, the following function doesn't work, and in fact 'kills' the script for all pages (so now things that were supposed to be hidden are not, and things are not loading properly). I've narrowed it down to the fact that I use to call a variable. I would really like to be able to keep functions using PHP in this universal file as opposed to clogging up the HTML template pages, any thoughts on either how to make this work, or if not how else I may be able to call the values needed? They are always extracted to the page before rendering if that helps.
function positiveSelect()
{
var size = <?php echo $idea[0]["size"]; ?> * 1;
if (size > 5)
return true;
else
return false;
}
if you can't retrive your data form the DOM itself you can store values with the corresponding object:
<div data-size=20>
and then retrive it with:
$(element).data("size");
or if you have global data you want to store you can create a value "container" in the head of you html document like this:
<script type="text/x-json" class="global-data">{"value1":"1","value2":"2"}</script>
and then read the content of that element and parse it with JSON.parse
If this function is that specific to a certain page, you might want to add a second js script that just gets loaded on that page.
An alternative would be to echo out a js variable in that php page and have your code call that function with that variable as a parameter.
You can give the javascript a ".php" extension and call it in the script in the same exact way:
<script type="javascript" src="path/to/scripts.php"></script>
You could just name the generate scripts file scripts.php or scripts.js.php; then the PHP preprocessor will process the file and the PHP statements will be evaluated.
When mixing php or any server side language with javascript you need to be aware that the php gets executed only once when the javascript file is created on the client side.
This is probably why you are getting unexpected results. As you move from page to page the php snippet in your global scripts.js will not get updated.

Pass data from PHP directly to DOM variable

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".)

Calling a JavaScript function from PHP

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/

Variable from JavaScript to PHP

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

Categories