• 0

Using jQuery+Ajax to update MySQL


Question

As the title suggests, i'm trying to update a database entry using jQuery and Ajax to accomplish this, however, the task won't be submitted through a form, checkbox or anything like that, but through a link.

How would I go about updating my DB through a link click?

For the record, the link doesn't actually have to go anywhere, it would just be a "press to update" sort of deal.

Link to comment
https://www.neowin.net/forum/topic/949086-using-jqueryajax-to-update-mysql/
Share on other sites

10 answers to this question

Recommended Posts

  • 0

This is a real simple example of using jquery and php.

<?php
  if (isset($_POST['action'])) {
    $link = mysql_connect(...);
    mysql_query("...", $link);
    mysql_close($link);
  }
?>
<html>
  <head>
    <script type="text/javascript">
      function performAjaxSubmission() {
        $.ajax({
          url: 'file.php',
          method: 'POST',
          data: {
            action: 'save',
            arg1: 'val1',
            arg2: 'val2'
          },
          success: function() {
            alert("success!");
          }
        });
        return false; // <--- important, prevents the link's href (hash in this example) from executing.
      }

      jQuery(document).ready(function() {
        $("#linkToClick").click(performAjaxSubmission);
      });
    </script>
  </head>
  <body>
    <a href="#" id="linkToClick">Click here</a>
  </body>
</html>

  • 0

Yes. I tend to do it like so:

<?php
  if (isset($_POST['action'])) {
    $link = mysql_connect(...);
    mysql_query("...", $link);
    mysql_close($link);
  }
?>
<html>
  <head>
    <script type="text/javascript">
      function performAjaxSubmission() {
        $.ajax({
          url: 'file.php',
          method: 'POST',
          data: {
            action: 'save',
            field: $(this).attr("db_field"), 
            val: $(this).attr("db_value")
          },
          success: function() {
            alert("success!");
          }
        });
        return false; // <--- important, prevents the link's href (hash in this example) from executing.
      }

      jQuery(document).ready(function() {
        $(".linkToClick").click(performAjaxSubmission);
      });
    </script>
  </head>
  <body>
    <a href="#" class="linkToClick" db_field="field1" db_value="value1">Click here</a>
    <a href="#" class="linkToClick" db_field="field2" db_value="value2">Click here</a>
    <a href="#" class="linkToClick" db_field="field3" db_value="value3">Click here</a>
  </body>
</html>

If you need me to explain how any of this works, just let me know.

  • 0

Just to make sure I got the database info correct, this should work, right?

<?php
  if (isset($_POST['action'])) {
  	$field = $_POST['db_field'];
  	$value = $_POST['db_value'];
    $link = mysql_connect("localhost", "admin", "admin");
    mysql_query("UPDATE example SET $field='$value' WHERE username='yourusernamehere'", $link);
    mysql_close($link);
  }
?>
<html>
  <head>
    <script type="text/javascript">
      function performAjaxSubmission() {
        $.ajax({
          url: 'file.php',
          method: 'POST',
          data: {
            action: 'save',
            field: $(this).attr("db_field"), 
            val: $(this).attr("db_value")
          },
          success: function() {
            alert("success!");
          }
        });
        return false; // <--- important, prevents the link's href (hash in this example) from executing.
      }

      jQuery(document).ready(function() {
        $(".linkToClick").click(performAjaxSubmission);
      });
    </script>
  </head>
  <body>
    <a href="#" class="linkToClick" db_field="field1" db_value="value1">Click here</a>
    <a href="#" class="linkToClick" db_field="field2" db_value="value2">Click here</a>
    <a href="#" class="linkToClick" db_field="field3" db_value="value3">Click here</a>
  </body>
</html>

  • 0
  On 28/10/2010 at 15:38, Andrew Lyle said:

Just to make sure I got the database info correct, this should work, right?

<?php
  if (isset($_POST['action'])) {
  	$field = $_POST['db_field'];
  	$value = $_POST['db_value'];
    $link = mysql_connect("localhost", "admin", "admin");
    mysql_query("UPDATE example SET $field='$value' WHERE username='yourusernamehere'", $link);
    mysql_close($link);
  }
?>
<html>
  <head>
    <script type="text/javascript">
      function performAjaxSubmission() {
        $.ajax({
          url: 'file.php',
          method: 'POST',
          data: {
            action: 'save',
            field: $(this).attr("db_field"), 
            val: $(this).attr("db_value")
          },
          success: function() {
            alert("success!");
          }
        });
        return false; // <--- important, prevents the link's href (hash in this example) from executing.
      }

      jQuery(document).ready(function() {
        $(".linkToClick").click(performAjaxSubmission);
      });
    </script>
  </head>
  <body>
    <a href="#" class="linkToClick" db_field="field1" db_value="value1">Click here</a>
    <a href="#" class="linkToClick" db_field="field2" db_value="value2">Click here</a>
    <a href="#" class="linkToClick" db_field="field3" db_value="value3">Click here</a>
  </body>
</html>

Looks like that should work fine :)

  • 0

<?php
  if (isset($_POST['action'])) {
  	$field = $_POST['db_field'];
  	$value = $_POST['db_value'];
    $link = mysql_connect("localhost", "admin", "admin");
mysql_select_db("database", $link);
    mysql_query("UPDATE example SET $field='$value' WHERE username='yourusernamehere'", $link);
    mysql_close($link);
  }
?>
<html>
  <head>
    <script type="text/javascript">
      function performAjaxSubmission() {
        $.ajax({
          url: 'file.php',
          method: 'POST',
          data: {
            action: 'save',
            field: $(this).attr("db_field"), 
            val: $(this).attr("db_value")
          },
          success: function() {
            alert("success!");
          }
        });
        return false; // <--- important, prevents the link's href (hash in this example) from executing.
      }

      jQuery(document).ready(function() {
        $(".linkToClick").click(performAjaxSubmission);
      });
    </script>
  </head>
  <body>
    <a href="#" class="linkToClick" db_field="field1" db_value="value1">Click here</a>
    <a href="#" class="linkToClick" db_field="field2" db_value="value2">Click here</a>
    <a href="#" class="linkToClick" db_field="field3" db_value="value3">Click here</a>
  </body>
</html>

just for record purposes, you need to add

mysql_select_db("database", $link);

to make this work :p

  • 0

Hi Andrew. If you allow me to suggest one more thing:

It is that you should look into parameterized queries whenever you have time to get some info on it. They've been around quite some time but I RARELY hear any developer talk about them. It seems only good developers know about it since it might be a little different than what we're used to for querying databases.

I've learned them just recently and I can't live without them now. It's so much cleaner and they have way too many advantages for you not to use them. You wouldn't need to waste extra space (neater code!) or waste CPU cycles on sanitizing code plus sanitizing code is prone to human error (it's only as good as your manual sanitation of the code). Not to mention that parameterized queries are faster as well. A parameterized query would look something like this:

$user_id = $_POST['uid'];

$stmt = Database :: prepare ( 'SELECT user_id FROM table1 WHERE user_id = :user_id_ ;' ) ;

$stmt -> bindParam( ':user_id_', $user_id, PDO::PARAM_INT);

$stmt -> execute ( ) ;

$user_id_info = $stmt -> fetch ( PDO::FETCH_ASSOC );

$stmt -> closeCursor ( ) ;

echo $user_id_info;

Where Database :: is a class to manage the PDO (PHP Data Object) which can be found here. http://www.php.net/manual/en/class.pdo.php

I'll post the database class I use if you're interested because I won't post it otherwise. If you want to learn more about it let me know if you have any questions.

As Jeff Atwood from codinghorror.com said: Give me parameterized SQL, or give me death

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

    • No registered users viewing this page.
  • Posts

    • What? Every single app I've installed from the Microsoft Store comes from its intended developer and works perfectly fine. What apps do you install?
    • Microsoft Store is such a weird place filled with so much absolute garbage and with reputable apps that somehow come from questionable sources. Like, the app name is known, the images back it up but the publisher is just some weird name that's not mentioned for the apps we know.
    • NTLite 2025.06.10459 is out.
    • Wireshark 4.4.7 by Razvan Serea  Wireshark is a network packet analyzer. A network packet analyzer will try to capture network packets and tries to display that packet data as detailed as possible. You could think of a network packet analyzer as a measuring device used to examine what's going on inside a network cable, just like a voltmeter is used by an electrician to examine what's going on inside an electric cable (but at a higher level, of course). In the past, such tools were either very expensive, proprietary, or both. However, with the advent of Wireshark, all that has changed. Wireshark is perhaps one of the best open source packet analyzers available today. Deep inspection of hundreds of protocols, with more being added all the time Live capture and offline analysis Standard three-pane packet browser Multi-platform: Runs on Windows, Linux, OS X, Solaris, FreeBSD, NetBSD, and many others Captured network data can be browsed via a GUI, or via the TTY-mode TShark utility The most powerful display filters in the industry Rich VoIP analysis Read/write many different capture file formats Capture files compressed with gzip can be decompressed on the fly Live data can be read from Ethernet, IEEE 802.11, PPP/HDLC, ATM, Bluetooth, USB, Token Ring, Frame Relay, FDDI, and others (depending on your platfrom) Decryption support for many protocols, including IPsec, ISAKMP, Kerberos, SNMPv3, SSL/TLS, WEP, and WPA/WPA2 Coloring rules can be applied to the packet list for quick, intuitive analysis Output can be exported to XML, PostScript®, CSV, or plain text Wireshark 4.4.7 changelog: The following vulnerabilities have been fixed wnpa-sec-2025-02 Dissection engine crash. Issue 20509. CVE-2025-5601. The following bugs have been fixed Wireshark does not correctly decode LIN "go to sleep" in TECMP and CMP. Issue 20463. Dissector bug, Protocol CIGI. Issue 20496. Green power packets are not dissected when proto_version == ZBEE_VERSION_GREEN_POWER. Issue 20497. Packet diagrams misalign or drop bitfields. Issue 20507. Corruption when setting heuristic dissector table UI name from Lua. Issue 20523. LDAP dissector incorrectly displays filters with singleton "&" Issue 20527. WebSocket per-message compression extentions: fail to decompress server messages (from the 2nd) due to parameter handling. Issue 20531. The LL_PERIODIC_SYNC_WR_IND packet is not properly dissected (packet-btle.c) Issue 20554. Updated Protocol Support AT, BT LE LL, CIGI, genl, LDAP, LIN, Logcat Text, net_dm, netfilter, nvme, SSH, TCPCL, TLS, WebSocket, ZigBee, and ZigBee ZCL Download: Wireshark 4.4.7 | 83.2 MB (Open Source) Download: Portable Wireshark 4.4.7 | ARM64 Installer View: Wireshark Website | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Snapchat finally has a watchOS app, a decade after the Apple Watch launched by David Uzondu Snap has announced that Snapchat is finally hopping onto Apple Watch, something many users have probably been waiting for. This new app lets you easily preview an incoming message right on your wrist and then fire back a reply without ever needing to grab your iPhone. For those quick responses, you have options: you can tap out a message on the keyboard, use Scribble to draw letters, dictate your reply, or just send a fitting emoji. Snap says it's trying to make Snapchat easier to use on all the different devices people have in their lives. It's already seen people using Snapchat on tablets and the web, so bringing it to wearables like the Apple Watch feels like the next natural move. That marks a big change from back in 2015 when the Apple Watch first launched. At the time, Snap took a more cautious "wait and see" approach, wanting to see if people actually used smartwatches before building an app. New app launches are not always perfect. It is still early days for the watchOS app, as some users on Reddit have reported the app being stuck on the loading screen. Hopefully, Snap will address these initial teething problems quickly. This expansion to Apple Watch comes after the company abandoned its widely criticized three-tab app redesign following a notable drop in its North American daily active users and significant negative feedback. That redesign, introduced back in September 2024, was meant to simplify things but ended up frustrating many, leading Snap to reverse course after about seven months and work on a refined five-tab layout. Meanwhile, Android smartwatch users with Wear OS are still in a different boat, as there is no official, dedicated Snapchat app for that platform yet. They can typically only receive notifications, and attempts to sideload the full Android app often result in a clunky experience.
  • Recent Achievements

    • Week One Done
      CHUNWEI earned a badge
      Week One Done
    • One Year In
      survivor303 earned a badge
      One Year In
    • Week One Done
      jbatch earned a badge
      Week One Done
    • First Post
      Yianis earned a badge
      First Post
    • Rookie
      GTRoberts went up a rank
      Rookie
  • Popular Contributors

    1. 1
      +primortal
      419
    2. 2
      +FloatingFatMan
      182
    3. 3
      snowy owl
      181
    4. 4
      ATLien_0
      174
    5. 5
      Xenon
      138
  • Tell a friend

    Love Neowin? Tell a friend!