Long story short I am using javascript and php to add / remove questions to a database (think notecards to study with). It all works except I can't get the table on my page to refresh whenever I hit the add question button which uses a XHR to add the data. I can refresh the page manually and see the updated table with my information, but want to use ajax to refresh the table on-screen right after I submit the new question (or delete it) seamlessly. I would rather not have to redraw the entire page, just the table and the info. I understand how to use the XHR and refresh the mysql...but how can I tell the browser to reload a table in a specific div on the page - and only that specific table - with the additional or removed info?
I can NOT use Jquery or other frameworks, just plain old JS, PHP, and html.
I have been searching, and just can't get that "ah-ha" moment yet, can't anybody help me out and push me in the right direction? Generalities, Dom commands to look up or research would be a great help, I don't need character by character coding done by the collective.
thank you, :-)
All you need to do is get it with a method such as document.getElementById or document.querySelector. Then you could change the element however you would need to.
var element = document.querySelector('#elToChange');
element.innerHTML = //something from the server
element.remove(); //for deleting
//If you delete remember to do the following so that you don't have a memory leak.
delete element;
I'd look at innerHTML you can place your table inside a div or whatever, and use innerHTML to regenerate the contents of that div.
Related
ok folks,
I have created a PHP page that is querying a database, and through a whileloop, displays the contents of that database table with a REMOVE and PUSH button. The REMOVE button removes it from the database entirely, and the PUSH button pushes that entry into another database and sets a variable that the entry has been pushed.
What I'm running into is that I can't quite get the page to refresh, in turn running an new query of the first database and displaying only those entries that have not been removed or pushed.
I can only get the query to run correctly if I manually refresh the page, whether it be F5 or control+r (command+r).
What is the proper way to refresh the page so that the query will run again on page load?
If you want to reload the page using Javascript, try this:
window.location.reload(true);
You can also see this answer:
How to reload a page using JavaScript?
there are two ways
If putting extra load on db is not a problem, use jquery methods likes $.get()
$.get('url',{},function(data){
//load results in appropriate div;
});
If you don't want to put any extra load on database just hide the row when it is removed or pushed.
$('.remove').click(function{
$(this).css('display','none');
});
similarly make it for pushed
Do you have some extreme caching setup on your web hosting solution?
If maintaining nice-looking URLs on this page is a non-issue you could always set a timestamp in PHP and append it to the string.
I'm not big on PHP but a javascript example would look something like this.
ts = new Date();
urltorefresh += '?timestamp=' + ts.getTime();
location.href = urltorefresh;
This would make sure the page is absolutely not in the browser cache since this specific URL have never been requested before.
Okay I'm not really sure how to approach this. I have a user-generated post board where people post, it drops down onto a list of a bunch of posts. When you click on the ID number of the post it will bring you to a separate page with just that post and the comments on the post. I want it so when you hover over the href it drops down something that tells the user there are x amount of comments on this post. This way people know if there is comments without switching pages and also being able to be able to click the href still and go to the postid page.
I assume some ajax/jquery/javascript would be used to accomplish this but since I'm fairly new to ajax and jquery I'm not certain how this would be done. Thank you!
For a hover effect, it would be better if that information was already stored on the page and just hidden. Then when the user does hover, you can just un-hide it and have it positioned where you want, and then hide it again when their mouse leaves the area. Using AJAX requests for this purpose would waste away a lot of HTTP requests for such a tiny amount of information.
Really, you could do the hover effect using pure CSS if you wanted too (I would).
Since a hover happens fairly often, I wouldn't use it as the default event to fire an AJAX-request. This would increase the HTTP-traffic enormous. See if you can fetch this information when the page is build (and put it in then) or use something else like a "preview"-button for the event.
Anyways, this would be the basic workflow if you want/need to use AJAX:
Write a PHP-script (or any other language you use) which fetches the number of comments (and what else you want to display) from the database (or where your data is stored).
This script should then be called via AJAX (with $.ajax() from jQuery for example). As the expected return-type you would then use json.
The script which fetches your data would then create an object, use PHP's json_encode()-function to encode this object to JSON and echo it out.
This JSON-object will then be available in the success-method of the ajax()-method from jQuery. Then, you can access its members (e.g. the comment-count).
Iam new to PHP . I wanted to make a forum where users can ask questions.I am using ajax to auto refresh the page.But it creates some problems...
Firstly, if I make that particular div ,where most recent question will be displayed,refresh only the latest question is displayed .
let me clear it with an ex :
User A opens the forum
He gets questions qlatest,q1,q2,q3 . Where div containg qlatest refreshes every 1 sec
User B posts a question qlatest2
qlatest is replaced by qlatest2 !
Now should I make whole div conatining all the questions make refresh?
If I understand correctly you want to create something like the Twitter feed where the latest item is displayed on top of each other.
The reason that the entire DIV refreshes is because you are rewriting the entire inner HTML of that DIV. To avoid this, use .appendChild() and program your PHP callback file to only pull the latest record from the database.
http://www.ezineasp.net/post/Javascript-Append-Div-Contents.aspx
JQuery also has some very useful functions adding children. I suggest using a Javascript library if you are new to AJAX calls.
You have to:
Add some data source that returns last asked question.
Invoke that data source on a constant interval and load returned question into the div..
The simplest to explain is the following solution:
Write JavaScript code that uses JS builtin function setInterval() to load eg. script last_question.php into the div. You can do it eg. using jQuery load() function, which can look eg. like this (assuming your div has ID of "last_question"):
jQuery('#last_question').load('last_question.php');
Of course it can be optimized. To do so, read about:
Long polling
JSON format
jQuery.requestJSON() jQuery function
Maybe some effects to make the question change smoother (like slide out and slide in)
So I am trying to have a dynamic tabs kind of thing using both php and javascript. To make it much easier to understand, remember the two choices on facebook (Recent news and most recent) or something like that, when you click on one of them it just changes the content that you see in the middle without updating the page. i know how to delete the content in a div for example, but after deleting the content in the div (innerHTML = "") I want to populate it with the option chosen from the database.
So let's say I have an option (all) and an option (only this)
The default is all so when I run the page, I will just get all. However, if I click on only this, it will clear the div "my header" and will replace the content with the latest content from the database (database) and display it.
For that I need both php and javascript, is there a sample or an easy way to do this before i start digging around.
((Sorry if is not clear but the facebook example should be clear enough))
Whatyou are looking for a is AJAX/PHP approach.
Clicking on the tab
The current content gets removed. This is possible because it has a unique "id" attribute in the HTML code
The server is asked for the new content. This is the AJAX request that will be triggered after/while/... the content is removed.
The server sends back the code. This can be HTML, JSON, XML or similar.
You script recieves the answer, may "do" something with it (like some parsing or similar)
The content will be placed on the page (again, this is possible due to an unique "id"
This is basically the way it is done.
Check out the different JavaScript frameworks. They all come with nice AJAX support:
jQuery
MooTools
dojo
Prototype
And of course, SO is also a nice place to look at: https://stackoverflow.com/questions/tagged/ajax+php
What you're talking about is ajax.
I would suggest a javascript library to help leverage this, like jquery.
It can be as cool as
$.post('serverScript.php',
function(data) {
$('#idOfDivToUpdate').html(data); //shove script data into div
},'html' );
tutorial.
Further to my question yesterday (here), I am working on a webpage that has a section that shows 'live' order details.
The top half of my webpage has Spry Tabbed Panels. One of the panels contains an include call to a separate php page that I have created (getOpenOrders.php). This contains an SQL query to obtain all open orders and then puts the details into a table.
As a result, the table of open orders is shown in the Spry panel. What steps do I now need to take to have this refresh every 15 seconds?
Do you really want to call the database every 15 seconds for each user? isn't that an overload?
I'm not saying that your database will be overloaded, but, thats how you shouldn't do things!
Edited
you should show an image, or the link to that page in order to gt an appropriate answer, because it all depends in what are you doing in the table.
because I don't know, I will give you an answer on what probably is happening.
Because you said that you're new to the ajax world, let's make things simple, and not to complicate on the you should return a JSON object and use it to re populate your table. :)
So we will start with 2 buttons (Previous and Next) so the user can move the data that is showing (you probably don't want to give him/her 100 lines to see right?)
let's say that you have 2 pages, a showData.php and getTable.php, in the showData.php you will need to load jQuery (wonderful for this) and add a little code, but where the table is to be placed, just add a div tag with an id="myTable" because we will get the data from the getTable.php file.
getTable.php file has to output only the table html code with all the data in, without no html, body, etc... the idea is to add inside the div called myTable all the code generated by getTable.php
Let's imagine that getTable.php gets a page variable in the queryString, that will tell what page you should show (to use LIMIT in your MySQL or PostgreSQL database)
You can use jQuery plugin called datatables witch is one of my choices, check his example and how small code you need to write! just using jQuery and Datatables plugin.
The first description follows the jQuery.Load() to load the getTable.php and add as a child of the div and wold do this for the previous and next buttons, passing a querystring with the page that the user requested. It's to simple and you can see the website for that, if you prefer to use the DataTables plugin, then just follow their examples :)
if you, after all this need help, drop me a line.
<META HTTP-EQUIV=Refresh CONTENT="15; URL=<?php print $PHP_SELF ?>">
This should be in between the head tags.
-or-
header('Refresh: 15');
This should be before the head tag and directly after the html tag.
As said by balexandre, a different method should be used. One that does not require a database hit every 15 seconds for every single user that is connected to the site. But, there is your answer anyways.
Although, balexandre makes a very good point, if you do decide that you need a refresh, you could simply do something like this in your JavaScript:
window.onload = function( )
{
setTimeout( 'window.location.refresh( )', 1500 );
}
(I've not tested the above code, so syntax may need to be tweaked a little, but you get the idea)