• 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">
		<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\"&gt;&lt;/a&gt; - ".$posts['up']." &lt;img src=\"inc/images/down.png\"&gt; - ".$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\"&gt;&lt;/a&gt; - ".$posts['up']." &lt;img src=\"inc/images/down.png\"&gt; - ".$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"&gt;
&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
  &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\"&gt;&lt;/a&gt; - ".$posts['up']." &lt;img src=\"inc/images/down.png\"&gt; - ".$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

    • I'm wondering if they are doing this as a "backup" in case CISA ceases to exist. It almost did recently due to funding and it's future is shaky. CISA - https://www.cisa.gov/known-exploited-vulnerabilities-catalog Example "CVE-2023-39780" https://www.cve.org/CVERecord?id=CVE-2023-39780 ASUS RT-AX55 Routers OS Command Injection Vulnerability
    • Over regulation is bad. That's why the EU is behind the US. But, it's a good thing the EU stepped in, in this case.
    • Thanks to the EU, Windows 11 is now a little more tolerable.
    • Microsoft will finally stop shoving Edge down your throat, on one condition by David Uzondu Avid Windows users must be familiar with the dirty tactics Microsoft employs to push its Edge browser. It's a song as old as time; remember when Internet Explorer was primarily used as a tool to download Chrome or Firefox because it was the only thing available? Shortly after IE died, Edge inherited that legacy, becoming the browser you often had to use just to get the browser you actually wanted. Even Microsoft knows this: For years, we have endured the relentless pop-ups after updates, third parties being blocked from changing the default browser on Windows 11, banners appearing when you dare visit a competitor's download page, a fake "how to uninstall Edge" guide, and links within Windows apps that just had to open in Edge, regardless of your set preferences. Microsoft has announced it is dialing back some of this aggressive behavior, promising a reprieve from the constant Edge bombardment. But (and it's a pretty big but) this only applies if you're in the EEA. This shift isn't Microsoft suddenly having a profound change of heart and deciding to respect user choice out of the goodness of its heart. No, this is all thanks to the Digital Markets Act, a major EU rule that targets big online platforms, what they call "gatekeepers", because these companies have a huge impact on how the digital market works. So, what is actually changing for users in the EEA? For starters, Microsoft Edge will not prompt you to set it as the default browser unless you actually open it directly, like by clicking its icon on the taskbar. This specific change started rolling out with Edge version 137.0.3296.52. Other Microsoft apps will also stop bugging you to reinstall Edge if you dared to remove it, with updates for this rolling out in June to Windows 10 and 11. And speaking of default browsers, this is where a significant improvement lies. Previously, hitting "Set default" for your browser in Windows was half baked, only grabbing basic web links like http and https and HTML files. Now, if you're in the EEA, setting your default browser will also cover more obscure link types like ftp and "read," plus a wider array of web-related file formats such as .mht, .svg, .xml, and even .pdf files, provided your chosen browser says it can handle them. The Bing app and those Windows Widgets, which previously had a nasty habit of ignoring your browser choice, will also start opening web links in your default browser. Hallelujah. Users in the EEA will also gain the ability to uninstall the Microsoft Store entirely later this year, though apps previously installed from it will still receive updates. Windows Search is also getting an upgrade in the EEA. Right now, searching from the taskbar mostly just sends you to Bing, no matter what browser you use. But for users in the EEA, other apps will be able to plug into Windows Search and show web results too. If an app registers as a web search provider, it'll start working as soon as you install it. You'll also be able to see results from multiple providers in the search interface, not just Bing. The usual scoping tabs will still be there if you want to filter things, but the default view will be more varied. And yes, you'll even be able to reorder the providers in Settings. These changes are already in Windows Insider builds and are expected to roll out to Windows 10 and 11 in early June.
  • Recent Achievements

    • One Year In
      WaynesWorld earned a badge
      One Year In
    • First Post
      chriskinney317 earned a badge
      First Post
    • Week One Done
      Nullun earned a badge
      Week One Done
    • First Post
      sultangris earned a badge
      First Post
    • Reacting Well
      sultangris earned a badge
      Reacting Well
  • Popular Contributors

    1. 1
      +primortal
      172
    2. 2
      ATLien_0
      125
    3. 3
      snowy owl
      123
    4. 4
      Xenon
      118
    5. 5
      +Edouard
      92
  • Tell a friend

    Love Neowin? Tell a friend!