TESTING ENVIRONMENT: Windows 8 using the tool XAMMP. PHP and Mysql are up to date.
MY KNOWLEDGE: Starter.
QUESTION: I can't get the updated content immediately after the first click, only after the second, which can become pretty nasty considering I have two kind of buttons for my little voting system. Yes, I said a lot not alot : )
What is the cause for this predicament and how can I fix this?
WHAT I TRIED: Checked my developer tools network analysis and I get a status 200 with the correct value for every click. When using my firefox DOM inspector view I saw something unusual: upon the first click only #votes is marked in orange probably denoting that it has been affected. However, only on the second attempt on the same button both divs, #votes and #progress, get marked orange in addition with the updated values. So I expect it does on second click but not on the first one. Then I refreshed my page and tried something else. I clicked on "bad" and this time the second click landed on "good" with bad updating the value in the DOM. It seems as if the entire process is split and does not happen simultaneously which is why I speculate that:
Click 1: Sends data to php.
Click 2: Gets the data from php and displays it on the DOM.
The PHP code itself in conjunction with my database and HTML (if set to submit) works perfectly fine so I dont assume there is anything wrong on the server side. Connection to the database is set. My sessions work perfectly. No errors.
My console shows 0 javascript errors.
Test 1 : I commented out my entire php code and set up a testing variable with a simple string and changed the values in my code below accordingly. To my suprise, on clicking it immediately took the data and display the content of my testing variable.
Test 2 :: I removed the php codes from the two div tags which you will see below. They act as placeholders that show the current value before any AJAX happens. I removed those and I get an update on first click as the container was first empty. Although, on second click and toggling between good and bad happened to be a mess again.
Test 2 :: Placing jquery and my AJAX script in the head of the document did not do the job either (just to be on the safe side). Prior it was before the </body> tag
I access the returned json object through my callback parameter named data which then inserts html and css via jquery into the respective div containers.
Converted the jquery below to pure javascript but no positive change could be observed.
JAVASCRIPT / AJAX
function vote(type) {
$.get('php/core/voting_system_function.php', {vote:type}, function(data) {
$('#votes').html(data.votes_sum);
$('#progress').css('width', data.progress);
}, 'json');
}
HTML
The buttons onclick event feeds the data on to the parameter within my vote functions which then sends it to {vote:type} and then to my php file. This allows me to do several checks to see if the click was either 'good' or 'bad' and substract or add data accordingly in my database.
#votes and #progress
<div id="quality_meter">
<div id="progress" style="width:<?php echo $progress ?>"></div>
</div>
<div id='votes'><?php echo $votes_sum ?></div>
The connection to the database is correct and readable through a require.
The script works assuming the user actually logged in as they cant access the page otherwise. As you can see I am making use of two session variables.
As you can see, I am making checks to see which button has been clicked and query accordingly.
The last bit of the code returns a json object through an associative array with the data stored by the variables you see there which is votes_sum and progress. I use json_encode to return the json representation of my value.
When you say you're not getting the response until the second click, do you mean the "votes_sum" in the votes div isn't updating with the latest votes?
The reason for this is that you calculate the $votes_sum value before you call the voting_system() function which is what updates the votes count, then after voting_system() you move the $votes_sum - unchanged - to the $output array.
Related
I am currently working on a website that is coded primarily with PHP/MySQL and HTML5 as a means to learn the code and become better. I used to work for a forum that used AJAX to reload the latest posts as if the user had just refreshed the webpage, except it just changed the content dynamically without a full reload.
My webpage: http://vgrnews.com
My specific situation is as follows: The homepage loads the four latest announcements and (soon to be) comments from the MySQL DB and displays them soonest -> latest. It is inside of a div called maincontent.
What I want to do: Have the announcements show up dynamically with AJAX regardless of the user refreshing or not. It would probably poll the server roughly every 5-10 seconds.
I don't plan to keep the homepage refreshing like that, but once I add more content it would be good to know how to refresh a div at regular intervals. I have read up on AJAX, but I don't quite understand all of the logistics, they just give you the code and expect you to pick it up. It is hard to morph the code to be applicable for my website if I don't understand it.
Sorry for the long read and thanks for all the replies!
function reload_content() {
$('#latest_post').load('ajax/get_latest.php');
}
window.setInterval(reload_content, 10000);
I will clarify on Alexander's answer for you. What the load() function is doing is performing an AJAX request to the given URL, and then setting the HTML of the selected div(s) to be the returned content. This means that your server should return proper HTML (and only the HTML you want in that div).
You can see http://api.jquery.com/load/ for more information on load().
If you plan on having your server return an JSON (or XML) representation of the information, you will have to use a jQuery get() (http://api.jquery.com/get/), and then process the returned data with a callback.
Note that both get() and load() are simply implicit applications of the jQuery ajax() method (http://api.jquery.com/jQuery.ajax/)
EDIT:
The setTimeout is just making the browser call the function ever x milliseconds. This is what will have it check every x seconds.
I have an AJAX POST which runs a php script which updates MySQL. The page is part of a Joomla site. Its part of a series of POSTS which return HTML to div's in the page. It all works well but I currently use a simple echo statement to say "Record Updated !" etc. But I have little control over where this message goes - and I don't know how to remove it when the user moves to another record - I'd like the message to disappear. I've just realised that HTML created by Ajax is "on the fly" - i.e you don't see it when you view source. So it's not possible to use Javascript and the DOM to change it.
What I think I want to do is run a Javascript function within the php - but this doesn't work either !
Any help here appreciated - or an alternative approach to give a database update confirmation message which can then be removed when the user moves to handle another record.
echo statements in php are not shown to the user when you use ajax unless you use the php output in your ajax success function yourself.
So you just need to remove the part of the javascript that adds the ajax return data to the dom / screen (in case of an alert).
As to an alternative solution, you could use a statically fixed status bar that shows up on an update and slides away after a few seconds. I don't know if you are using a javascript library, but using jQuery that would be very easy to implement.
This is more of curiosity that anything, but I can think of several places (mainly in admin sections) where this could be useful. I know the title is confusing so this is what I mean:
Say you have a form that posts to example_cb.php. example_cb.php is a very large callback page that generates multiple thumbnails of an image, puts them in their respective directories, adds them to a database, etc. You already have the form posting by jquery with a function like this
$.post('example_cb.php', $(this).serialize(), function(data) {
// Success
}, 'json');
Before posting it updates a div to say "processing" of something. Then after it successfully completes the div fades out. However you want the div to show what is happening on the server side. i.e. Converting 200X200 thumb > Converting 350x350 thumb > Adding Records to Database > etc.
How can you accomplish this?
I know it's a loaded question, but I'm confident there are people on here smart enough to figure it out. If you need more info please comment :)
You could do something like -
Write each 'event' update to a database table
Write a page that retrieves the last n events from table
Use something like 'load' to call page update an onscreen div
with the updated progress.
Use 'setTimeout` to keep updating.
This could be accomplished most easily with using the push method, but I'm not too familiar with ajax push or comet technology, so I'll give you a pull solution.
Basically you need to create the initial ajax request to start the processing. Then, you need to have another request running in a tight loop that checks against a php page for the current status. For example, on the php page doing the processing, you can update a _SESSION key that stores the current processing information (like "Converting 200X200 thumb") at each step. Another php page will exist purely to print that information and you can retrieve it with the JS running in a loop.
pusher like services may be used for bi-directional communication.
I'm putting it down for reference, though this would be overkill for such a simple scenerio.
I'm writing an app that uses ajax to retrieve data from a mysql db using php. Because of the nature of the app, the user clicks an href link that has an "onclick" event used to call the javascript/ajax. I'm retrieving the data from mysql, then calling a separate php function which creates a small html table with the necessary data in it. The new table gets passed back to the responseText and is displayed inside a div tag. The tables only have around 10-20 rows of data in them. This functionality is working fine and displays the data in html form exactly as it needs to be on the page.
The problem is this. the HREF "onclick" event needs to run multiple scripts one right after the other. The first script updates the "existing" data and inside the "update_existing" function is a call to refresh a section of the page with the updated HTML from the responseText. Then when that is done a "display_html" function is called which also updates a different section of the page with it's newly created HTML table. The event looks like this:
Update
This string gets built dynamically using php with parameters supplied, but for this example I simply took the parameters out so it didn't get confusing.
The "update_existion() function actually calls the display_html() function which updates a section of the page as needed. I need to update a different section of the page on the same click of the mouse right after the update, which is why I'm calling the display_html() again, right after it. The problem is only the last call is being updated on my screen. In other words, the 2nd function call "display_html()" executes and displays the refreshed data just fine, but the previous call to update_existing() runs and updates the database properly, but doesn't display on the screen unless I press the browsers "refresh" button, which of course displays the new data exactly how I want it to, but I don't want the users to have to press the "refresh" button. I tried adding multiple "display_html() calls one right after the other, separating all of them with the semicolon and learned that only the very last function call actually refreshed the div element on the html page with the table information, although all the previous display_html() calls worked, they couldn't be seen on the page without a refresh of the browser.
Is this a problem with javascript, or the ajax call, or is this a limitation in the DOM that only allows one element to be updated at a time. The ajax call is asynchroneous, but I've tried both, only async works period. This is the same in both Firefox and Internet Explorer
Any ideas what's going on and how to get around it so I can run these multiple scripts?
I'd recomment you to use jQuery javascript library. It has some funcions, like live() that can "wait" for that table to appear on the browser and apply the remaining functions on it.
Also, it's a great set of functions that will certainly help you out reducing the ammount of code you write, making it more human-readable.
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)