• 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

    • That would have been a so much better UX that what it is right now. I know that after a few moment of trying/failing to recognize you in the dark it goes back to PIN selection. But if the light sensor would detect the dark light, showing the PIN field while continuing for a brief moment to register your face would work better.
    • Oh ! This is why... Like some of you, i used Windows Hello since the Surface Pro 4. It worked really well for so long on many devices and still use it everyday with my desktop and laptop. I couldn't understand why it wasn't working as well as before in the dark. Why is Microsoft (as a company) in its UX decisions so anti-consumer right now ? -_-"
    • Zen Browser 1.13.2b is out.
    • KDE Plasma 6.4 launches, bringing better window management, improved KRunner, and more by David Uzondu It's finally here. After several weeks of development, KDE Plasma 6.4 has been rolled out, delivering a ton of significant refinements across the entire UX, from how you manage windows to how you see notifications. The biggest deal for power users is probably the increased flexibility in window management. Plasma 6.4 now allows you to set a completely different tiling layout for each virtual desktop. You can have a simple 50/50 split screen on one desktop for writing, and on another, have a complex grid with two apps snapped to the sides and two others floating in the middle. On the visual side, the default Breeze Dark theme got a little darker for better contrast, and when a password box pops up, the rest of the screen dims to help you focus. There is also a new Animations page in System Settings, which groups all the purely visual effects in one place so you can find them easily. The file transfer notification now shows a speed graph, giving you a much better idea of how a download is progressing. The system will even pop up a notice if you try talking into a muted microphone, and you can install system updates right from the notification that tells you they are ready. When you are in a full-screen application like a game or watching a movie, Plasma automatically enters a Do Not Disturb mode, holding back notifications until you are done. Plasma 6.3, which was released last February, brought several features, including a "Help" category to the launcher after getting rid of the "Settings" one. Now, Plasma 6.4 gives the application launcher a green New! tag next to recently installed apps to help you find them. KRunner and Spectacle, two of the most powerful utilities in Plasma, also received some serious attention. KRunner now lets you visualize colors just by typing in their hex code or even CSS names like "MintCream" or the ridiculous "PapayaWhip." The tool will then show you what that color looks like and give you its code in other formats. Spectacle, the screenshot tool, has been completely overhauled. Pressing the Print Screen key now immediately puts you in selection mode, letting you grab a region or the whole screen much faster before jumping straight into the annotation tools. Screen recordings made in the WebM format or on screens with fractional scaling have also seen a massive quality boost. The Bluetooth widget is getting smarter with better device recognition and easier pairing (we touched on this last month). People with nice monitors will appreciate the new HDR calibration wizard in the display settings. Plasma can also now handle Extended Dynamic Range and the P010 video format, improving power efficiency with HDR content. Digital artists were not left out either. Configuring the buttons on a stylus is "much more intuitive," and you can easily reset your tablet's calibration if you mess it up. Finally, there is a lot of work under the hood. The System Monitor can now show GPU usage for Intel and AMD hardware on a per-process basis and has a new Sensors page for nerds who want to see raw temperature data. When you drag and drop files on the same disk, you can now set it to always move them instead of asking what to do every time. The browser integration feature now supports the Flatpak versions of Firefox and Chromium-based browsers. All of this is built on top of support for a slew of new Wayland protocols, like "FIFO", "toplevel tag," and more. For more information, you can check out the official announcement post, as well as the full changelog.
    • Zoom Workplace 6.5.0.6118 by Razvan Serea Zoom Workplace for Windows is a reliable video conferencing tool that makes it easy to connect and collaborate. With features like messaging, file sharing, and app integrations, it’s designed to streamline teamwork. You’ll get high-quality audio and video, strong security with end-to-end encryption, and an intuitive interface—all of which help remote teams and businesses stay productive and connected. Zoom Workplace key features: High-Definition Video & Audio: Provides clear, reliable communication for virtual meetings. End-to-End Encryption: Ensures secure communication with strong data protection. Multi-Factor Authentication: Adds an extra layer of security for user accounts. Integration with Productivity Apps: Supports seamless integration with Microsoft Office, Google Workspace, and more. File Sharing: Easily share files during meetings for efficient collaboration. Real-Time Messaging: Enables team chat for ongoing communication. Collaborative Whiteboarding: Allows teams to brainstorm and collaborate visually. Webinar Support: Host large webinars with interactive features. Administrative Controls: Manage user permissions, meeting settings, and security features. Cloud Storage: Automatically stores meetings and files in the cloud for easy access. Cross-Platform Support: Available on Windows, macOS, and mobile devices. Meeting features: Virtual Backgrounds: Customize your background for meetings to maintain privacy or enhance professionalism. Touch Up My Appearance: Automatically smoothens skin tone for a more polished video appearance. Breakout Rooms: Divide meetings into smaller sessions for group discussions or workshops. Live Transcription: Automatically generate real-time captions during meetings for accessibility. Zoom Apps: Integrate third-party applications directly into Zoom for enhanced functionality. Meeting Reactions: Participants can use emojis for quick, non-verbal feedback during meetings. Polling: Conduct live polls during meetings to gather instant feedback from participants. Attention Tracking: Monitors participant attention during meetings to ensure engagement. Closed Captioning: Enable manual or automatic captions for a more inclusive experience. Webinar Replay: Record and share webinars with analytics for audience engagement. Download: Zoom 64-bit | Zoom 32-bit (Free, paid upgrade available) Links: Zoom Website | Zoom ARM64 | Zoom Installers | Release Notes Get alerted to all of our Software updates on Twitter at @NeowinSoftware
  • 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
      699
    2. 2
      ATLien_0
      273
    3. 3
      Michael Scrip
      214
    4. 4
      +FloatingFatMan
      186
    5. 5
      Steven P.
      145
  • Tell a friend

    Love Neowin? Tell a friend!