• 0

[jQuery] Updating MySQL table with link click


Question

Basically I've been trying for 3 hours to make the table update with a click of a link using jQuery. The link ID is up and the link points to nowhere because I don't want the url changing. I'm wondering if anybody can assist me with how to make the column in the table update (+1 each click).

Thanks,

S2

23 answers to this question

Recommended Posts

  • 0

Ah sorry, I misread your post.

To do that without the page reloading when the link is clicked, you'll need to make an AJAX call to a script on the server which will then alter the table.

So, your javascript would do something like this when your link is clicked;

$.ajax({
   type: "GET",
   url: "the-script.php"
 });

and then the script on the server would do something like

// connect to database
//...

$query = "YOUR SQL QUERY TO UPDATE THE TABLE";
$res = mysql_query($query);

  • 0

Seems you're quite unclear on how most of the technologies you'll need to achieve this even work.

Also you're not giving nearly enough information to the potential people willing to help you.

Your question gives away that you're new at this, and this implies lots of baby steps and holding your hand for whoever wants to help you...

Seriously, sit down and write an extensive description of your database, your html, your javascript skills, AND the exact thing you're trying to achieve, so that someone can guide you using knowledge that you already have.

Here's how something like what you're describing usually works:

1. Browser renders HTML elements, Javascript attaches event listeners for the click events of the desired elements

2. User clicks the element, the listener Javascript function gets executed by the Browser

3. In the function you should achieve an asynchronous call(I see you sort of want to not refresh the page at all?) to the Server, where your only chance of manipulating your database lies

4. your piece of code at your server does the work related to the updating of the database, depending on the data passed by the Browser, and potentially coming back with a result status code

5. potentially, you update the HTML in the Browser depending on the response code/message, for the User to see

I hope this helps

  • 0
  On 15/04/2011 at 13:24, XakepaBG said:
..., sit down and write an extensive description of your database, your html, your javascript skills, AND the exact thing you're trying to achieve, so that someone can guide you using knowledge that you already have.

;)

  • 0

I know I'm not giving the best explanations but I'm sure you can gather what I am after.

I'll explain it here: I have a link that when I press it I want it to update a column in the MySQL table based on the ID of the "post". I don't want the URL to change and it needs to refresh back to the normal page.

Please give me any help you can offer, it's all I really ask.

  • 0

OK, you should be able to figure what this quick example I made for you does. :)

Actually, Neowin's code highlighter/formatting is pretty rubbish. Here's a pastie link: http://pastie.org/1800656

<?php
if('POST' === $_SERVER['REQUEST_METHOD']){
  printf(
    "You sent me the number %d, at %s.",
    empty($_POST['number']) ? 0 : $_POST['number'] ,
    date('r')
  );
  exit;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">;html xmlns="http://www.w3.org/1999/xhtml">lt;head>
				<meta http-equiv="content-type" content="text/html; charset=utf-8" />
				<link rel="stylesheet" type="text/css" media="screen" href="http://yui.yahooapis.com/3.3.0/build/cssreset/reset-min.css" />
				<link rel="stylesheet" type="text/css" media="screen" href="http://yui.yahooapis.com/3.3.0/build/cssbase/base-min.css" />
				<link rel="stylesheet" type="text/css" media="screen" href="http://yui.yahooapis.com/3.3.0/build/cssfonts/fonts-min.css" />
				<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>
				<style type="text/css">
				</style>
				<title>
						Demo
				</title>
		</head>
		<body>

      <?php foreach(range(1, 15) as $number): ?>
        <span class="clickable"><?php echo $number; ?></span>
      <?php endforeach; ?>

      <div id="response"></div>

      <script type="text/javascript">
        //<![CDATA[
        $(document).ready(function(){
          $('span.clickable').each(function(){
            $(this).click(function(){
                $.ajax({
                  type: 'POST',
                  url: './index.php',
                  data: 'number=' + $(this).html(),
                  success: function(response){
                    $('#response').html(response);
                  }
                });
            });
          });
        });
        //]]>
      </script>

		</body>
</html>

  • 0
  On 16/04/2011 at 13:22, Shazer2 said:

Anyone? Could someone else give me a hand with this. I don't really know what URL to give the link, because I wanted it updated without the page URL having to change, but do the same as the form submission but update the MySQL table. Ideas?

XakepaBG made some good points; You really need to provide more information - what form submission are you talking about?

My previous post outlined what you need to do to update the database without reloading the page.

There's varying opinions on what you should use for the href attribute for javascript-only links. href='#' is popular, but will require the onclick (or jquery bound) event to return false or run preventDefault() on the event object so that the browser doesn't try navigating to # (which won't reload the page, but will scroll it. Another approach is to use href='javascript:void(0)'. You won't have to use javascript in your click handler to cancel the event's default behaviour using this approach - so it's probably better than the # approach.

The best approach is to have the link actually go to a valid URL but have javascript override that behaviour to provide a better user experience. This way, users without javascript enabled can still click the link to make the database change (but the browser will have to (re)load a page) and users with javascript enabled get the enhanced experience of being able to do exactly the same thing but without the browser reloading the page.

Using my previous code as an example and this HTML;

<a id='link' href="the-script.php">Click me</a>

$('#link').click(function(){
    // Make the call to the script that performs the database update asynchronously (ie, by not reloading the page)
    $.ajax({
        type: "GET",
        url: "the-script.php"
    });
    return false; // Prevent the browser from navigating to the-script.php
});

Edit: Regarding AnthonySterling's solution; you will need to write the code that updates the database yourself. We're not psychic, we have no idea what changes you want to be made in the database. Put an SQL query that does what you want in the if statement at the top. Similarly, you'll need to generate the actual links with correct post IDs.

  • 0

Thanks for that code, Mouldy Punk. I believe we ARE getting places, but what I need to do is send the ID of the "post" so a part of it can be updated in the table. How can I send the ID as a value to the the-script.php to be used to update in the DB.

Not sure how to go about this, I'm calling this jQuery in a mysql_fetch_array loop too, because that's how I pull the "post" data from the database.

  • 0

Without seeing your existing code, it'll be tricky for us to give you more help really. You'll need to somehow make the post ID accessible to the click event of each link.

For example, if you had a series of links (one for each post) that went along the lines of;

<a href='#' onclick="javascript:clickHandler(1); return false;">Click me</a>

where the parameter of clickHandler is different for each link (it's the post ID)

The you could have the javascript function that'll post that post id to the PHP script on the server;

function clickHandler(post_id){
     $.ajax({
                  type: 'POST',
                  url: 'the-script.php',
                  data: 'post_id=' + post_id
      });
}

Then the PHP script on the server would take that post id and do a mysql query using it;

&lt;?php
$post_id = $_POST['post_id'];
// connect to db
mysql_query('do something with $post_id');
// etc.
?&gt;

  • 0

Alright, I'm getting a better idea of what I need to do, but I can't seem to get it to execute the clickHandler function. Here is my code, see if you can help me from there.

&lt;?php
            $sql = mysql_query("SELECT * FROM `posts` ORDER BY up DESC") or die(mysql_error());
            while ($posts = mysql_fetch_array($sql)) {
                echo "&lt;b&gt;".$posts['user']."&lt;/b&gt; (&lt;a href=\"inc/up.php\" id=\"up\" onclick=\"javascript:clickHandler(1); return false;\"&gt;&lt;img src=\"inc/images/up.png\"></a>.$posts['up']." &lt;img src=\"inc/images/down.png\">.$posts['down'].")&lt;br /&gt;&lt;br /&gt;";
                echo "&lt;i&gt;\"".$posts['np']."\"&lt;/i&gt;&lt;hr /&gt;";

                echo "
                function clickHandler(post_id){
                    $.ajax({
                        type: 'POST',
                        url: 'inc/up.php',
                        data: 'post_id=' + post_id
                    });
                }
                &lt;/script&gt;";
            }
            ?&gt;

  • 0
  On 16/04/2011 at 06:29, Shazer2 said:

Xakepa, I'm obviously a beginner at this. I didn't ask for you to spoonfeed me, don't treat me like that. I learn off examples. From what Mouldy Punk showed me I think I can achieve this, I'll try me best and make an edit if I can get it.

Lol, you post a thread showing your complete ignorance of the subject and when somebody tries to help you get bitchy. :rolleyes:

  • 0

jQuery and PHP code to pull posts from database, display a a link to put +1 onto it.

$sql = mysql_query("SELECT * FROM `posts` ORDER BY up DESC") or die(mysql_error());
            while ($posts = mysql_fetch_array($sql)) {
                echo "&lt;b&gt;".$posts['user']."&lt;/b&gt; (&lt;a href=\"inc/up.php\" id=\"up\" onclick=\"javascript:clickHandler(1); return false;\"&gt;&lt;img src=\"inc/images/up.png\"></a>.$posts['up']." &lt;img src=\"inc/images/down.png\">.$posts['down'].")&lt;br /&gt;&lt;br /&gt;";
                echo "&lt;i&gt;\"".$posts['np']."\"&lt;/i&gt;&lt;hr /&gt;";

                echo "
                &lt;script type=\"text/javascript\"&gt;
                $('#up').click(function() {
                    $.ajax({
                        type: 'POST',
                        url: 'inc/up.php',
                        data: 'id=' + ".$posts['id']."
                    });
                });
                &lt;/script&gt;";
            }
?&gt;

up.php that processes the click:

include("connect.php");

$id = $_POST['id'];
$id = mysql_real_escape_string($id);

mysql_query("UPDATE `posts` SET up += 1 WHERE id='$id'") or die(mysql_error());

Just updating so I could gather more help, it still isn't posting an ID so if you know why, please help.

  • 0

Upload this somewhere, in a folder of its own and name it index.php. Once it's live, have a play around with it, if you have any specific questions, let me know.

&lt;?php
function records(){
  return array(
    array(
      'title' =&gt; 'PHP is cool',
      'id'    =&gt; 1,
      'votes' =&gt; rand(1, 10)
    ),
    array(
      'title' =&gt; 'jQuery is cool',
      'id'    =&gt; 2,
      'votes' =&gt; rand(1, 10)
    ),
    array(
      'title' =&gt; 'AJAX is cool',
      'id'    =&gt; 3,
      'votes' =&gt; rand(1, 10)
    ),
  );
}

if('POST' === $_SERVER['REQUEST_METHOD']){

  list($direction, $id) = explode('-', $_POST['data']);

  $filter = array(
    'up'    =&gt; 'up = up + 1',
    'down'  =&gt; 'down = down + 1'
  );

  if(array_key_exists($direction, $filter)){
    $sql = sprintf(
      "UPDATE table SET %s WHERE id = %d LIMIT 1;",
      $filter[$direction],
      $id
    );

    echo $sql;
    exit;
  }

}
?&gt;
&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">;html xmlns="http://www.w3.org/1999/xhtml">lt;head&gt;
    &lt;meta http-equiv="content-type" content="text/html; charset=utf-8" /&gt;
    &lt;link rel="stylesheet" type="text/css" media="screen" href="http://yui.yahooapis.com/3.3.0/build/cssreset/reset-min.css" /&gt;
    &lt;link rel="stylesheet" type="text/css" media="screen" href="http://yui.yahooapis.com/3.3.0/build/cssbase/base-min.css" /&gt;
    &lt;link rel="stylesheet" type="text/css" media="screen" href="http://yui.yahooapis.com/3.3.0/build/cssfonts/fonts-min.css" /&gt;
    &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"&gt;&lt;/script&gt;
    &lt;style type="text/css"&gt;
      td.votable{
        text-align: center;
        cursor: pointer;
      }
    &lt;/style&gt;
    &lt;title&gt;
      Demo
    &lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;

    &lt;table&gt;
      &lt;thead&gt;
        &lt;tr&gt;
          &lt;th&gt;Title&lt;/th&gt;
          &lt;th&gt;Votes&lt;/th&gt;
          &lt;th&gt;Vote Up&lt;/th&gt;
          &lt;th&gt;Vote Down&lt;/th&gt;
        &lt;/tr&gt;
      &lt;/thead&gt;
      &lt;tbody&gt;
      &lt;?php foreach(records() as $record): ?&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;?php echo $record['title']; ?&gt;&lt;/td&gt;
          &lt;td&gt;&lt;?php echo $record['votes']; ?&gt;&lt;/td&gt;
          &lt;td class="votable" id="up-&lt;?php echo $record['id']; ?&gt;"&gt;Up&lt;/td&gt;
          &lt;td class="votable" id="down-&lt;?php echo $record['id']; ?&gt;"&gt;Down&lt;/td&gt;
        &lt;/tr&gt;
      &lt;?php endforeach; ?&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;

    &lt;script type="text/javascript"&gt;
    //&lt;![CDATA[
      $(document).ready(function(){
        $('td.votable').each(function(){
          $(this).click(function(){
            $.ajax({
              type: 'POST',
              url: './index.php',
              data: 'data=' + $(this).attr('id'),
              success: function(response){
                alert(response);
              }
            });
          });
        });
      });
    //]]&gt;
    &lt;/script&gt;

  &lt;/body&gt;
&lt;/html&gt;

http://pastie.org/1803131

I've uploaded the script above to my server here: http://dev.anthonysterling.com/neowin/

It won't be there indefinitely though. :)

  • 0
  On 17/04/2011 at 00:14, Shazer2 said:

jQuery and PHP code to pull posts from database, display a a link to put +1 onto it.

$sql = mysql_query("SELECT * FROM `posts` ORDER BY up DESC") or die(mysql_error());
            while ($posts = mysql_fetch_array($sql)) {
                echo "&lt;b&gt;".$posts['user']."&lt;/b&gt; (&lt;a href=\"inc/up.php\" id=\"up\" onclick=\"javascript:clickHandler(1); return false;\"&gt;&lt;img src=\"inc/images/up.png\"></a>.$posts['up']." &lt;img src=\"inc/images/down.png\">.$posts['down'].")&lt;br /&gt;&lt;br /&gt;";
                echo "&lt;i&gt;\"".$posts['np']."\"&lt;/i&gt;&lt;hr /&gt;";

                echo "
                &lt;script type=\"text/javascript\"&gt;
                $('#up').click(function() {
                    $.ajax({
                        type: 'POST',
                        url: 'inc/up.php',
                        data: 'id=' + ".$posts['id']."
                    });
                });
                &lt;/script&gt;";
            }
?&gt;

up.php that processes the click:

include("connect.php");

$id = $_POST['id'];
$id = mysql_real_escape_string($id);

mysql_query("UPDATE `posts` SET up += 1 WHERE id='$id'") or die(mysql_error());

Just updating so I could gather more help, it still isn't posting an ID so if you know why, please help.

The reason why I was using the onclick attribute instead of using a jquery selector's click event is because you'd need a unique ID for every link. You've got <a id='up'> being generated multiple times in a while loop. HTML ids should be unique on a page, there should be no duplicates. Look at the final output (view source in your browser), the code you generate makes no sense - there's multiple $('#up').click() binds and multiple <a id='up'> elements - the browser has no way of telling which click function goes with which <a> element.

The method I mentioned previously would mean that the javascript function is output just once. Each of the onclick javascript calls give that single function different parameters (post IDs) making it send the right post ID. It is much simpler to use vanilla javascript, like I mentioned, to set up the function call than try and bind multiple event listeners using jQuery.

  • 0
  On 17/04/2011 at 08:55, AnthonySterling said:

Upload this somewhere, in a folder of its own and name it index.php. Once it's live, have a play around with it, if you have any specific questions, let me know.


http://pastie.org/1803131

I've uploaded the script above to my server here: http://dev.anthonysterling.com/neowin/

It won't be there indefinitely though. :)

That's really handy. Thanks a lot.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Guilty is used as a regular English term here, not the legal term
    • AnyDesk 9.5.6 by Razvan Serea AnyDesk is a fast remote desktop system and enables users to access their data, images, videos and applications from anywhere and at any time, and also to share it with others. AnyDesk is the first remote desktop software that doesn't require you to think about what you can do. CAD, video editing or simply working comfortably with an office suite for hours are just a few examples. AnyDesk is designed for modern multi-core CPUs. Most of AnyDesk's image processing is done con­currently. This way, AnyDesk can utilize up to 90% of modern CPUs. AnyDesk works across multiple platforms and operating systems: Windows, Linux, Free BSD, Mac OS, iOS and Android. Just five megabytes - downloaded in a glimpse, sent via email, or fired up from your USB drive, AnyDesk will turn any desktop into your desktop in se­conds. No administrative privileges or installation needed. AnyDesk 9.5.6 changelog: Features Implemented Discovery section in AnyDesk One Implemented multi-selection in Monitoring list views using Shift-Click Implemented URL handler for navigation Bugfixes Fixed crash when initialization of gles failed Fixed crash due to uncaught exceptions when registering internal services Fixed crash due to uncaught exceptions when registering internal services Fixed crash when adding device to favourites Fixed crash when starting Screen Recording Fixed bug that lead to showing incorrect Alerts in Monitoring when viewing specific devices Fixed bug that lead to interpreting right clicks as left clicks Fixed handling of double and triple clicks for middle and right mouse buttons Other changes Redesigned the authors' section in About AnyDesk panel Improved initialization of rendering components so that it is only done when needed Removed some false positive warning traces Download: AnyDesk 9.5.6 | macOS ~14.0 MB (Free for private use, paid upgrade available) Links: AnyDesk Home Page | Other platforms | Release History | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • President Trump says TikTok deadline will ‘probably' be extended again by Sagar Naresh Bhavsar It appears that the Trump administration is quite keen on allowing TikTok to continue its operations in the U.S. The platform was briefly banned in the U.S. on January 19 for 14 hours. But as soon as Donald Trump assumed office as the 47th President of the U.S. on January 20, he signed an executive order to give a reprieve of 75 days to TikTok. During this period, TikTok had to separate itself from its Chinese parent, ByteDance, and find a U.S. buyer. Several U.S. companies, including Microsoft, Oracle, Perplexity AI, and Amazon, reportedly showed interest in buying the U.S. assets of TikTok. While President Trump hinted that a deal could soon come through, nothing materialised. As the 75-day deadline was about to expire on April 5, Trump signed another executive order on April 4, granting TikTok another 75-day extension. Now, with the second deadline nearing its end on June 19, it seems like President Trump is still unwilling to let TikTok shut down in the U.S. According to Reuters, U.S. President Trump has said that he would likely offer another extension to ByteDance-owned short video platform TikTok to divest its U.S. assets. Answering reporters on Air Force One on Tuesday, when asked about extending the deadline, Trump said; If announced, it will be for the third time, TikTok gets a lifeline to continue its operations in the U.S. While there is no clarity on how many extensions the company might receive, it's evident that President Trump wants TikTok to find a solution for its U.S. assets. Interestingly, he wanted to ban TikTok during his first Presidential term. However, things changed as Meta banned him from its platforms after the January 6, 2024, Capitol Attack. Trump then joined TikTok and appreciated the platform to help him reach a young audience. For now, TikTok's fate still hangs in the balance. Let us know in the comments below what you think about this development. Image by rafapress via Depositphotos
  • Recent Achievements

    • Week One Done
      Rhydderch earned a badge
      Week One Done
    • Experienced
      dismuter went up a rank
      Experienced
    • One Month Later
      mevinyavin earned a badge
      One Month Later
    • Week One Done
      rozermack875 earned a badge
      Week One Done
    • Week One Done
      oneworldtechnologies earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      698
    2. 2
      ATLien_0
      272
    3. 3
      Michael Scrip
      214
    4. 4
      +FloatingFatMan
      186
    5. 5
      Steven P.
      145
  • Tell a friend

    Love Neowin? Tell a friend!