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/
Related
I've looked at a lot of StackOverflow answers but can't find an answer that is working. This seems like it should be so simple.
I have a PHP single page web app. It has a nav bar that loads pages as includes. Clicking the nav bar invokes a jQuery function to load a different include and inject a class into a div. This works in the nav.
In one of the includes, I have an HTML link:
<div class="page-content">
<a class='btn-primary'>See Examples</a>
</div>
This is the jQuery I want it to execute:
$(".btn-primary").click(function() {
alert('you clicked me');
$('.page').attr('class', 'page examples');
// REPLACE THE CURRENT INCLUDE
$('.page-content').load('includes/page-examples.php');
window.scrollTo(0, 0);
});
But the link does not execute the function. Changing it to a div does not work. Clicking will not even execute the alert.
I've tried to put the link in php echo or php print, but it makes no difference. I've checked all my naming and there isn't a typo.
What is the best way to make it work?
----- EDIT -----
The jQuery is being called from a js file called from the index.php head tag, and is in the DOM ready statement. It looks like the DOM is ready before the include with the link loads. If I remove the link's js from the js file and put it in the include with the link, then the link works, but this will create a problem as other internal links are added to the site in other includes.
What is the best way to fix ?
It sounds like your javascript click binding $(".btn-primary").click(...); is executed on DOM-ready.
But at that time the .btn-primary is not yet in the DOM as it only gets inserted into the DOM after you include it (if I understood it right).
Therefore the binding never happens and after your first include gets loaded the click binding code is never executed again and therefore the .btn-primary element has no onClick event.
You need to run your javascript snippet after that .btn-primary element gets inserted in the DOM, eg. like this:
$('.page-content').load('includes/first-include.php', function(){
$(".btn-primary").click(function() {
whatever...
});
});
First step
Check if you are importing jQuery library (it seems obvious, but we
can forget to import the library sometimes or the library URL is wrong
and the browser cannot recognize it as well). And remember you need import jQuery before the function you wrote.
Second step
If you need to inject a class into some element using jQuery, the easiest way to do this is:
Instead...
$('.page').attr('class', 'page examples');
Change to...
$('.page').addClass('examples');
In this example above, you can omit the 'page' and let only 'examples', because the class ".page" is already there.
Another thing, this will only work if the element with ".page" class already exists in your HTML.
Third step:
Add a callback to .load function and see if it worked properly:
$('.page-content').load('includes/page-examples.php', function(){
alert("Nice, my content was loaded!");
// You can put this action here, so it will execute after the content is loaded
window.scrollTo(0, 0);
});
I’m trying to store the content of a div to a variable.
Example:
<div class="anything">
<p>We don't know the content of this div</p>
</div>
I want to search for <div class="anything"> and store everything between opening and the end tag.
We also want to avoid using absolute pathnames, so that it only searches the current HTML/PHP file for this div where the code is present.
Is this possible with PHP, or is this only possible with JavaScript ?
PHP is not that intelligent. He doesn't even know what he says.
PHP is a server-side language. It has absolutely NO clue about what the DOM (ie. what is displayed in your browser's window) is when it delivers a page. Yeah I know, PHP rendered the DOM, so how could it not know what's in there?
Simply put, let's say that PHP doesn't have a memory of what he renders. He just knows that at one particular moment, he is delivering strings of characters, but that's all. He kind of doesn't get the big picture. The big picture goes to the client and is called the DOM. The server (PHP) forgets it immediately as he's rendering it.
Like a red fish.
To do that, you need JavaScript (which is on the client's computer, and therefore has complete access to the rendered DOM), or if you want PHP to do this, you have to retrieve an full-rendered page first.
So the only way to do what you want to do in PHP is to get your page printed, and only then you can retrieve it with an http request and parse it with, in your case, a library such as simpleHtmlDom.
Quick example on how to parse a rendered page with simpleHtmlDom:
Let's say you know that your page will be available at http://mypage.com/mypage.php
$html = file_get_html('http://mypage.com/mypage.php');
foreach($html->find('div.anything') as $element)
echo $element->src . '<br>';
you probably need a combination of those.
In your Javascript:
var content = document.getElementsByClassName("anything")[0].innerHTML();
document.getElementByID('formfield').value(content);
document.getElementByID('hiddenForm').submit();
In your HTML/PHP File:
<form id="hiddenForm" action="path/to/your/script">
<input type="hidden" name="formfield" value="" />
</form>
In the script you defined in the form action:
if(!empty($_POST)){
$content = $_POST['formfield'];
// DO something with the content;
}
Alternatively you could send the data via AJAX but I guess you are new to this stuff so you should start slowly :)
Cheers!
steve
You could use JS to take the .innerHTML from the elements you wan and store them in .value of some input fields of a form and then use a submit button to run the PHP form handling as normal. Use .readOnly to make the input fields uneditle.
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.
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.
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