Jump to content

[PHP & MySQL] Update Website Data Dynamically?

Muramasa
Go to solution Solved by burnttoastnice,

you need ajax my friend.

 

W3School have tutorials, http://www.w3schools.com/ajax/.

 

Adding to his answer, jQuery (a Javascript library) has an Ajax function which is pretty straightforward as well as the code being much shorter and much neater compared to the original Javascript function.

 

Below is a simple modified jQuery ajax example I got from sitepoint:

 

$.ajax({      url: 'http://google.com',      success: function(data) { //See Note#1         alert(data);      },      error: function() { //see Note#2         alert("Whoops, Error");      }});

 

Note#1: If the request is a success, the function would be called with 'data' holding the entire response of the webpage. For Google (the request in the example) it would return all the code on that page.

 

Note #2: If there is an error, it will carry out this function. There are extra variables that can be put into either function to catch various elements of the HTTP response, such as the code (e.g. 404 not found, or 403 forbidden)

Alright so currently I have created a PHP script that displays records from a MySQL database as 3 columns but I want the data echo'd by the PHP script (Inside div elements) to update dynamically as the database gets new data.

 

The PHP Script:

<?php    // Connection script:    include 'connect.php';    //Query    $sql1 = "SELECT * FROM item";    $result = $conn->query($sql1);?><!DOCTYPE html><html><head>    <link rel="stylesheet" type="text/css" href="style.css">    <title>Record Display</title></head><body>    <div id="item-wrapper">        <?php            $item_num = 0;            // total number of records            $num_records = mysqli_fetch_row($result);            while ($item = mysqli_fetch_assoc($result)){        	if ($item_num % 3 == 0){        	    ?><div class="left_column"><?php        	}                // If its the second column of 3 write the div middle_column class                else if ($item_num % 3 == 1){        	    ?><div class="middle_column"><?php        	}                // If its the second column of 3 write the div right_column class                else if ($item_num % 3 == 2){        	    ?><div class="right_column"><?php        	}    		?><div class="item"><?php		echo $item['displayName'];		?></div></div> <?php                $item_num ++;            }        ?>    </div></body></html>

So my question is what would be the best method for implementing this?

 

Thanks.

My Rig:   | Intel i7 5960x @ Stock(For Now)     |     Asus X99-E WS     |     EVGA GTX 780 Superclocked ACX In 2-Way SLI     |


|  32GB Kingston Predator DDR4     |     Corsair AX1200     |     TJ07     |

Link to comment
Share on other sites

Link to post
Share on other sites

you need ajax my friend.

 

W3School have tutorials, http://www.w3schools.com/ajax/.

 

Adding to his answer, jQuery (a Javascript library) has an Ajax function which is pretty straightforward as well as the code being much shorter and much neater compared to the original Javascript function.

 

Below is a simple modified jQuery ajax example I got from sitepoint:

 

$.ajax({      url: 'http://google.com',      success: function(data) { //See Note#1         alert(data);      },      error: function() { //see Note#2         alert("Whoops, Error");      }});

 

Note#1: If the request is a success, the function would be called with 'data' holding the entire response of the webpage. For Google (the request in the example) it would return all the code on that page.

 

Note #2: If there is an error, it will carry out this function. There are extra variables that can be put into either function to catch various elements of the HTTP response, such as the code (e.g. 404 not found, or 403 forbidden)

Speedtests

WiFi - 7ms, 22Mb down, 10Mb up

Ethernet - 6ms, 47.5Mb down, 9.7Mb up

 

Rigs

Spoiler

 Type            Desktop

 OS              Windows 10 Pro

 CPU             i5-4430S

 RAM             8GB CORSAIR XMS3 (2x4gb)

 Cooler          LC Power LC-CC-97 65W

 Motherboard     ASUS H81M-PLUS

 GPU             GeForce GTX 1060

 Storage         120GB Sandisk SSD (boot), 750GB Seagate 2.5" (storage), 500GB Seagate 2.5" SSHD (cache)

 

Spoiler

Type            Server

OS              Ubuntu 14.04 LTS

CPU             Core 2 Duo E6320

RAM             2GB Non-ECC

Motherboard     ASUS P5VD2-MX SE

Storage         RAID 1: 250GB WD Blue and Seagate Barracuda

Uses            Webserver, NAS, Mediaserver, Database Server

 

Quotes of Fame

On 8/27/2015 at 10:09 AM, Drixen said:

Linus is light years ahead a lot of other YouTubers, he isn't just an average YouTuber.. he's legitimately, legit.

On 10/11/2015 at 11:36 AM, Geralt said:

When something is worth doing, it's worth overdoing.

On 6/22/2016 at 10:05 AM, trag1c said:

It's completely blown out of proportion. Also if you're the least bit worried about data gathering then you should go live in a cave a 1000Km from the nearest establishment simply because every device and every entity gathers information these days. In the current era privacy is just fallacy and nothing more.

 

Link to comment
Share on other sites

Link to post
Share on other sites

snip

 

I really appreciate the example and I have my php script updating the data periodically so thanks!

 

If you are familiar with the topic and it's ok with you, I have another question.

 

My other goal was to have an initially hidden div element appear when a user clicks on one of the div elements I am generating with the php script. The purpose of this now visible div element would be to send the data from the element we clicked to a new php script.

 

I know how to do all of this, but one problem is I need to make a query in this new script but the data that we echo from the first php script is not unique data. So my question is how can I attach extra data to the div elements so I can also pass that to the new php script to I can make a query but also not have this visible?

My Rig:   | Intel i7 5960x @ Stock(For Now)     |     Asus X99-E WS     |     EVGA GTX 780 Superclocked ACX In 2-Way SLI     |


|  32GB Kingston Predator DDR4     |     Corsair AX1200     |     TJ07     |

Link to comment
Share on other sites

Link to post
Share on other sites

I really appreciate the example and I have my php script updating the data periodically so thanks!

 

If you are familiar with the topic and it's ok with you, I have another question.

 

My other goal was to have an initially hidden div element appear when a user clicks on one of the div elements I am generating with the php script. The purpose of this now visible div element would be to send the data from the element we clicked to a new php script.

 

I know how to do all of this, but one problem is I need to make a query in this new script but the data that we echo from the first php script is not unique data. So my question is how can I attach extra data to the div elements so I can also pass that to the new php script to I can make a query but also not have this visible?

 

That was a little hard to understand, but what I got was that you're trying to make something happen when a user clicks something inside a div that you generate. I currently do something similar on one of my projects, by having the button call a Javascript function when it's clicked.

 

For example, I may create a live notification window, that I would like to update periodically.

function notifications_update() {    $.ajax({        type: "GET",        url: "notifications.php",        cache: false,        success: function(result){            $("#output_div").html(result); //Note #1            setTimeout(function(){notifications_update();},5000); //Note #2        },        error: function(XMLHttpRequest, textStatus, errorThrown) {            $("#output_div").html("Error, click <a onClick='notifications_update();'>here</a> to try again");//Note #3        }    });}

Note #1: This will return the result of the request in a div with the id 'output_div'

Note #2: If the request was a success, it will then set a timer for the notifications to refresh again in 5 seconds, shown as 5000 milliseconds.

Note #3: This happens when there is an error. The div that has the notifications will clear and it will show an error message stating that they can click a button to refresh. Clicking that refresh button will then call the notifications_update() script again. I think this is similar to what you are attempting to achieve.

 

Let's say you wanted to actually have the notification do something when it's clicked.

function trigger_action(variable) { //Note #4    $.ajax({        type: "GET",        url: "notifications.php?data="+variable, //Note #5        cache: false,        success: function(result){            $("#output_div").html(result); //Note #6        },        error: function(XMLHttpRequest, textStatus, errorThrown) {            $("#output_div").html("Action could not be completed");        }    });}

Note #4: This javascript function takes a variable, so if you made a button in HTML to call this script, you'd do something like:

<a onClick="trigger_action('<? echo $unique_identifier; ?>');">Action Button</a>

which would send something such as the notification ID to the javascript function.

Note #5: The notification ID which we previously sent is now used by the javascript function to request the rest of information about the notification

Note #6: The user is snown the information ^_^

 

I hope this is what you were looking for. I'll try to answer your questions if I can ^_^

Speedtests

WiFi - 7ms, 22Mb down, 10Mb up

Ethernet - 6ms, 47.5Mb down, 9.7Mb up

 

Rigs

Spoiler

 Type            Desktop

 OS              Windows 10 Pro

 CPU             i5-4430S

 RAM             8GB CORSAIR XMS3 (2x4gb)

 Cooler          LC Power LC-CC-97 65W

 Motherboard     ASUS H81M-PLUS

 GPU             GeForce GTX 1060

 Storage         120GB Sandisk SSD (boot), 750GB Seagate 2.5" (storage), 500GB Seagate 2.5" SSHD (cache)

 

Spoiler

Type            Server

OS              Ubuntu 14.04 LTS

CPU             Core 2 Duo E6320

RAM             2GB Non-ECC

Motherboard     ASUS P5VD2-MX SE

Storage         RAID 1: 250GB WD Blue and Seagate Barracuda

Uses            Webserver, NAS, Mediaserver, Database Server

 

Quotes of Fame

On 8/27/2015 at 10:09 AM, Drixen said:

Linus is light years ahead a lot of other YouTubers, he isn't just an average YouTuber.. he's legitimately, legit.

On 10/11/2015 at 11:36 AM, Geralt said:

When something is worth doing, it's worth overdoing.

On 6/22/2016 at 10:05 AM, trag1c said:

It's completely blown out of proportion. Also if you're the least bit worried about data gathering then you should go live in a cave a 1000Km from the nearest establishment simply because every device and every entity gathers information these days. In the current era privacy is just fallacy and nothing more.

 

Link to comment
Share on other sites

Link to post
Share on other sites

snip

Wow I really appreciate the detailed examples, thanks so much!

 

It was this that I was having trouble with for some reason:

<a onClick="trigger_action('<? echo $unique_identifier; ?>');">Action Button</a>

And it was how I would "attach" unique data when all of the displayed data inst unique (Display name and amount) but I didn't even think to give the divs I was already generating an id of the items rawId which is a unique value.

 

Thanks again for the ajax code snippets! 

My Rig:   | Intel i7 5960x @ Stock(For Now)     |     Asus X99-E WS     |     EVGA GTX 780 Superclocked ACX In 2-Way SLI     |


|  32GB Kingston Predator DDR4     |     Corsair AX1200     |     TJ07     |

Link to comment
Share on other sites

Link to post
Share on other sites

Wow I really appreciate the detailed examples, thanks so much!

 

It was this that I was having trouble with for some reason:

<a onClick="trigger_action('<? echo $unique_identifier; ?>');">Action Button</a>

And it was how I would "attach" unique data when all of the displayed data inst unique (Display name and amount) but I didn't even think to give the divs I was already generating an id of the items rawId which is a unique value.

 

Thanks again for the ajax code snippets! 

 

No problem ^_^

 

As for the unique data, the easiest would be the ID of each row. You'd then just need to echo the row ID into the javascript function.

If an id field isn't there already, you may need to create one. But when you are adding new rows to the mySql table, don't forget to increment the value so it stays unique.

<a onClick="trigger_action('<? echo $item['id']; ?>');">Action Button</a>

Speedtests

WiFi - 7ms, 22Mb down, 10Mb up

Ethernet - 6ms, 47.5Mb down, 9.7Mb up

 

Rigs

Spoiler

 Type            Desktop

 OS              Windows 10 Pro

 CPU             i5-4430S

 RAM             8GB CORSAIR XMS3 (2x4gb)

 Cooler          LC Power LC-CC-97 65W

 Motherboard     ASUS H81M-PLUS

 GPU             GeForce GTX 1060

 Storage         120GB Sandisk SSD (boot), 750GB Seagate 2.5" (storage), 500GB Seagate 2.5" SSHD (cache)

 

Spoiler

Type            Server

OS              Ubuntu 14.04 LTS

CPU             Core 2 Duo E6320

RAM             2GB Non-ECC

Motherboard     ASUS P5VD2-MX SE

Storage         RAID 1: 250GB WD Blue and Seagate Barracuda

Uses            Webserver, NAS, Mediaserver, Database Server

 

Quotes of Fame

On 8/27/2015 at 10:09 AM, Drixen said:

Linus is light years ahead a lot of other YouTubers, he isn't just an average YouTuber.. he's legitimately, legit.

On 10/11/2015 at 11:36 AM, Geralt said:

When something is worth doing, it's worth overdoing.

On 6/22/2016 at 10:05 AM, trag1c said:

It's completely blown out of proportion. Also if you're the least bit worried about data gathering then you should go live in a cave a 1000Km from the nearest establishment simply because every device and every entity gathers information these days. In the current era privacy is just fallacy and nothing more.

 

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×