Ajax problem not displaying data using multiple javascript calls - php

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.

Related

AJAX / PHP voting system: Content not updating on first click

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.

How to execute mysql_fetch_row() upon a button click

I am tying to put some user data from the database using php.
The database contains so many record and i am displaying it using mysql_fetch_row() and this gives me the fields of first row.
Now the problem is a have two buttons namely next and previous. And when a click next the fields in the next row has to be obtained the they should be inserted into page without loading the page once again. I am facing problem with this.
I am using php for server side programming and html, css for client side programming.
I think that no one will give you the answer. Too many to write. You need to read about ajax (this is the technology that will allow you to do some action without page reloading).
You need to write javascript(you can use some library like jquery) function which will open some php page with the data that you want and then update your site.
Here you have some nice tutorial:
http://www.w3schools.com/jquery/jquery_ajax_intro.asp

Refresh a DIV with AJAX that requires MySQL queries + PHP

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.

View live updates from MySQL database?

I want to create a page where people can insert some text, hit enter, and the text be stored in a MySQL database. I can do this, but I want to be able to load a page, enter a password, and see a list of all the info in said database, then whenever something is added to the database, it's added to the list on the page, without me needing to refresh the page or setup some javascript code to refresh the page every five seconds.
I believe Satya has it correct in suggesting that you use Ajax in order to refresh the data without refreshing the page. You can have it request updated information from a php script which queries your database for the data you wish to display, and then sets the elements on your page accordingly.
this is probably the best way for you to implement ajax calls using javascript
http://api.jquery.com/jQuery.ajax/
Or you an simly do it with the help of setInterval() function. You can call an html code in a div using
$('#id').html("<htmlcode></htmlcode>");
Example : http://jsfiddle.net/ipsjolly/995PJ/6/

Can't post data to self because of design

i have a website that uses a number of containers (div's). In this scenario, we have three boxes down the left side and one bigger box on the right of these boxes. The bigger box on the right is the only thing that changes when a link is pressed, this is done with Javascript.
SO i have the index which is the main layout of the website and i also have the "pages" of the site, so when a link is pressed the main box (on the right) loads the new data.
On one of my pages i want to collect data and then run it through a PHP script that is in the head of the file, but when i click the button i realise it refreshes the whole page and it doesn't run the script on the page with the form.
Anyone had a problem like this, or know of something i could do to work around it?
I'm not really sure what code would be useful for helping me but if you need something just ask.
Thanks for the help
Since you are loading all your content via JS already, you could just POST the form data via AJAX to a PHP script to process, then read the output and either provide an error message or remove the form from the page and show your success message.
How to approach your AJAX call is dependant on what you've used as a basis for the rest of your JS.
Personally I like to use the JQuery library, as it makes AJAX calls (and much more) very simple.
How about you make the page design able to do it. Have the backend be able to spit out the state of the page when it posted.
Or use Ajax to post the data back and set the new state like you do already.

Categories