• 0

[jQuery] Submitting a form


Question

I am trying to make something where you can post, and with jQuery it submits (no refresh or parsing via another page) and inserts the data into the DB. The code I am using for the jQuery is in my <head> and this is the code:

&lt;script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"&gt;&lt;/script&gt;
    &lt;script type="text/javascript" &gt;
    $(function() {
        $(".submit").click(function() {
            var np = $("#np").val();
            $.ajax({
                type: "POST",
                url: "inc/ajax.php",
                data: np,
                success: function(){
                    $('.success').fadeIn(200).show();
                    $('.error').fadeOut(200).hide();
                }
            });
        }
        return false;
    });
    &lt;/script&gt;

I then have the following in ajax.php and I am 100% certain it's in the correct directory.

&lt;?php

/**
 * @author Shannon
 * @copyright 2011
 */
session_start();
include ("connect.php");

$user = $_SESSION['username'];
$np = $_POST['np'];
$np = mysql_real_escape_string($np);   

mysql_query("INSERT INTO `posts` (user, np) VALUES ('$user', '$np')") or die(mysql_error());  
?&gt;

That is all correct too, but it just doesn't seem to insert into the database. If anyone has an idea why, please post a reply.

Link to comment
https://www.neowin.net/forum/topic/990268-jquery-submitting-a-form/
Share on other sites

17 answers to this question

Recommended Posts

  • 0

Let's do some basic debugging techniques to see what's going on.

First, in your JavaScript, make liberal use of console.log('something'); to see what's actually being sent (check the output in your browser's console of choice, be it Firebug/Web Inspector etc.) Ensure that your np variable contains what you think it contains. And ensure that the Ajax request runs, completes and doesn't error out (again, Firebug/Web Inspector).

Once you're happy your JavaScript is behaving itself, do the same with PHP - output variables to a log file if you like, check to see the status of any database connections.

Use a process of elimination to work out exactly where the problem is occurring by ensuring each step is completing successfully.

  • 0

Rob, this is the first time using JavaScript so I don't know ANY functions. This was merely copied off a site to see if I could get it to work. Obviously I couldn't so I resulted here asking for assistance. I don't know the problem and don't really know what to do to find out. I'm pretty efficient in PHP however, just not JS.

Anymore help you can give?

  • 0

I'm running it as a PHP file (still works) but:

&lt;?php
session_start();
include("inc/connect.php");
?&gt;
&lt;html&gt;
&lt;head&gt;
    &lt;title&gt;Home&lt;/title&gt;
    &lt;link rel="stylesheet" href="inc/style.css" type="text/css" /&gt;
    &lt;script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"&gt;&lt;/script&gt;
    &lt;script type="text/javascript" &gt;
    $(function() {
        $(".submit").click(function() {
            var np = $("#np").val();
            $.ajax({
                type: "POST",
                url: "inc/ajax.php",
                data: np,
                success: function(){
                    $('.success').fadeIn(200).show();
                    $('.error').fadeOut(200).hide();
                }
            });
        }
        return false;
    });
    &lt;/script&gt;

&lt;/head&gt;
&lt;body&gt;
    &lt;div align="center"&gt;
        &lt;div class="header"&gt;
            &lt;div class="logo"&gt;
                &lt;a href="index.php"&gt;&lt;img src="inc/logo.png" alt="Logo" /&gt;&lt;/a&gt;&lt;br /&gt;
            &lt;/div&gt;

            &lt;?php
            $user = $_SESSION['username'];

            if (!$user) {
                header("location:login.php");
            }
            ?&gt;

            &lt;div class="useri"&gt;&lt;br /&gt;

            &lt;?php echo "Logged in as: &lt;a href='#'&gt;".$user."&lt;/a&gt;&lt;br /&gt;"; ?&gt;

            &lt;a href="logout.php"&gt;Logout&lt;/a&gt;
            &lt;/div&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;hr /&gt;

            &lt;div class="newsbox"&gt;
                    &lt;u&gt;&lt;b&gt;News&lt;/b&gt;&lt;/u&gt;&lt;hr /&gt;
                    &lt;?php
                    $sql = mysql_query("SELECT * FROM `feed`") or die(mysql_error());
                    while ($rnews = mysql_fetch_array($sql)) {
                        echo $rnews['news']."&lt;br /&gt;&lt;br /&gt;";
                    }
                    ?&gt;
            &lt;/div&gt;

            &lt;div class="updatebox"&gt;
            &lt;u&gt;&lt;b&gt;Updates&lt;/b&gt;&lt;/u&gt;&lt;hr /&gt;
            &lt;?php
            $sql = mysql_query("SELECT * FROM `feed`") or die(mysql_error());
            while ($rupdate = mysql_fetch_array($sql)) {
                echo $rupdate['update']."&lt;br /&gt;&lt;br /&gt;";
            }
            ?&gt;
            &lt;/div&gt;

            &lt;div class="newspost"&gt;
            &lt;form id="submit" name="submit" method="POST"&gt; 
            &lt;input name="np" type="text" id="np" style="margin-left: 1px; margin-right: 1px; width: 99%;" /&gt;
            &lt;input name="sub" type="submit" id="sub" style="float: right;" value="Post!" /&gt;
            &lt;/form&gt;
            &lt;br /&gt;&lt;/div&gt;&lt;br /&gt;

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

  • 0

First problem I can see is this line:

$(".submit").click(function() {

This means 'run this function when an element with a class of 'submit' is clicked'.

Fastforward to your HTML, and you'll see your Submit button doesn't have a class of 'submit' at all! So our JavaScript function is never being called, and no Ajax request is made. What your button does have, however, is an ID of 'sub'...

Replace that line with this, and try again:

$("#sub").click(function() {

  • 0

You're also missing the closing bracket for the click event declaration.

&lt;script type="text/javascript"&gt;
   $(function() {
      $("#sub").click(function() {
         var np = $("#np").val();
         $.ajax({
            type: "POST",
            url: "inc/ajax.php",
            data: np,
            success: function(){
               $('.success').fadeIn(200).show();
               $('.error').fadeOut(200).hide();
            }
         });
         return false;
      });
   });
&lt;/script&gt;

  • 0

We are making progress. It now opens up a new entry in the database but isn't sending any of the data to the database. It leaves both fields (np, user) empty. Another problem, it doesn't auto refresh after it is posted or submitted.

What I want it to do is when it posts it, clear the textbox and have a little message underneath saying success.

  • 0

Now your problem is that your PHP is expecting data in a variable called np, but your JavaScript is just sending the value of a textbox that happens to be called np as well. So if we change this one line to this:

data: {np:np},

You can see we're now saying 'send the value we've put into local variable np to the server, labelled 'np'.

I'm not able to help much more I'm afraid. You mention you want a little message saying success, but nowhere in your HTML do you have anything like that. So I think you need to learn a little more about how HTML works, and the basics of JavaScript and then this will start to make a bit more sense. Right now you're just copying and pasting stuff... which is how we all start, but to customize this you really need to understand the fundamentals first.

Good luck :)

  • 0

Updated last post with what I wanted the resulting outcome to be, that seems to work (inserts np into database) but it isn't inserting the user in. To get the user logged in I use sessions (obviously), so what I am wondering is with JavaScript can you make a var hold the value of a PHP session. If not, I am determining the user in the ajax.php file, but it doesn't seem to want to add that into the database.

So where we are at: it inserts np into the database but doesn't insert user. We still need to say if the post succeeded or failed too. I do know HTML but don't know how to incorporate it into JavaScript to display the message. I just need a little more explanation Rob. I learned PHP this way too, when I didn't understand something after looking it up, I went and asked places. I am now half decent with PHP but just a beginner with JavaScript.

  • 0

Hint: try to work out what this line of code is supposed to do, based on what we've discussed here previously and by looking into the appropriate jQuery documentation. Once you understand that, you'll see what you need to do to get a success or failure message.

$('.success').fadeIn(200).show();

  • 0

I've looked at that line multiple times Rob. I know it displays the fail or success but I'm not sure how to use it. I even added a part in my CSS file (.success) because I thought that is what was needed.

Can you explain to me what this does, or at least direct me to a page that will give me a brief idea of how to use it and what it does?

  • 0

Just heading to bed, but here's a line-by-line description of the JS:

&lt;script type="text/javascript"&gt;
   $(function() {                                   // Run this function when both jQuery and the DOM is ready
      $("#sub").click(function() {                  // When the element with an ID of 'sub' is clicked, run this function
         var npMessage = $("#np").val();            // Set the value of the element with an ID of 'np' into a variable called 'npMessage'
         $.ajax({                                   // Start an Ajax request
            type: "POST",                           // ... of type 'POST'
            url: "inc/ajax.php",                    // ... to this URL
            data: {np:npMessage},                   // Sending the value of npMessage (set earlier) under the name 'np'
            success: function(){                    // If the Ajax request succeeds, run this function
               $('.success').fadeIn(200).show();    // Fade in any HTML elements with a class of 'success' on the page, then show them (last bit is redundant)
               $('.error').fadeOut(200).hide();     // Fade out any HTML elements with a class of 'error' on the page, then hide them (last bit is redundant)
            }                                       // End of the success method
         });                                        // End of the Ajax request
         return false;                              // Prevent the normal behaviour of the button (submitting the page in a non-Ajax way)
      });                                           // End of the click handler
   });                                              // End of the jQuery DOM ready handler
&lt;/script&gt;

jQuery documentation - for more information on the $.ajax function.

Firebug - a browser plugin for Firefox that helps visually show Ajax requests and whether they succeed

  • 0

Thanks. I just don't understand how to display the success message or the failed message. I know I need to do something like:

&lt;div class="success"&gt;Success!&lt;/div&gt;

somewhere in the page, but I don't know where, unless it's in a called function it's just going to constantly be displayed. Not sure if you will see this before you go to bed, but if you do please reply to this one. If you do see it, please also tell me how to clear the textbox after everything has been submitted.

  • 0

Sort of had it working, but now the messages won't display. I realise I have to make 2 spans with error and success, and set display to none. I then fade it in when it has the right stuff entered and fade out success and fade in error when it doesn't.

It seems to be having trouble though with the following code, not sure why it is doing it.

&lt;script type="text/javascript"&gt;
    $(function() {  
        $("#sub").click(function() {    
            var npMessage = $("#np").val(); 

            if (npMessage=='') {
                $('.success').fadeOut(200).hide();
                $('.error').fadeIn(200).show(); 
            } else {
                $.ajax({   
                    type: "POST",  
                    url: "inc/ajax.php", 
                    data: {np:npMessage},
                    success: function(){ 
                        $('.success').fadeIn(200).show();
                        $('.error').fadeOut(200).hide();
                    }
                });
            return false;   
            });
        });
    &lt;/script&gt;

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

    • No registered users viewing this page.
  • Posts

    • Flameshot 14.0 Final by Razvan Serea Flameshot is a free and open-source, cross-platform tool to take screenshots with many built-in features to save you time. Using Flameshot is as simple as launching, dragging the selection box to cover the area you want to capture, making annotations as needed in on-screen and saving the shot to your computer, all with a very simple and straightforward interface. Flameshot allows users to simply upload their screenshots directly to the cloud in order to easily share it with others. You can upload your image directly to Imgur with a single click and share the URL with others. In-app screenshot editing - You can choose to add an arrow mark, highlight text, blur a section (blur or pixelate an area), add a text, draw something, add a rectangular/circular shaped border, add an incrementing counter number, and add a solid color box with Flameshot's built-in editing tools. Command-line interface (CLI) - Flameshot has several commands you can use in the terminal without launching the GUI via a command line interface. The command line interface lets you script Flameshot and use it as the subject of key binds. Flameshot 14.0 release notes: This release brings major improvements to multi-monitor support, fractional scaling support, new capture workflows, and a long list of bug fixes across all platforms. Changelog: New Multi-Monitor Capture Workflow New monitor selection screen before capture for better multi-monitor and mixed-scaling support. Option to auto-capture the monitor under the cursor (X11 & Windows). Tray menu can directly select a monitor. Linux Improvements XDG Desktop Portal is now the primary screenshot method. Added legacy X11 fallback option for minimal window managers. New D-Bus capture API for scripting and automation. Windows Enhancements Global screenshot hotkeys now supported (not limited to Print Screen). New portable mode stores settings next to the executable. Clipboard now always uses PNG format for better compatibility. CLI & Platform Updates Redesigned flameshot screen command with per-monitor capture support. Added native Nix Flake support. More compact launcher UI and improved update notifications. Major Fixes Multiple Wayland stability fixes, including KDE Plasma crash fixes. Clipboard compatibility improvements for GNOME, Wayland, X11, Windows, and macOS. Fixed D-Bus hangs, capture crashes, and HiDPI region issues. Other Changes Dropped Ubuntu 20.04 (Focal) support. Updated translations and build infrastructure. Intel macOS builds are no longer provided. [full release notes] Download: Flameshot 14.0 | 18.1 MB (Open Source) Download: Flameshot Portable | 53.0 MB Links: Flameshot Home Page | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Helium Browser 0.13.4.1 by Razvan Serea Helium is a private, fast, and honest Chromium-based web browser — built for people, with love. It offers the best privacy by default, unbiased ad-blocking, and a clean experience free from bloat and noise. Proudly based on Ungoogled-Chromium, Helium removes Google’s clutter while keeping a fast, efficient development pipeline. With thoughtful touches like native !bangs and split view, Helium is a people-first, fully open-source browser that puts control back in your hands. Privacy, security, and control come first. Ads, trackers, and third-party cookies are blocked automatically, HTTPS is enforced everywhere, and all Chromium extensions work seamlessly — while Google can’t track your activity. Helium’s 13,000+ offline-ready !bangs let you jump straight to sites or AI tools like ChatGPT instantly. Open-source, people-first, and unbiased, Helium delivers a browsing experience that’s fast, secure, and free from noise, ads, and compromises. Helium Browser key features: Performance Fast, efficient, and lightweight — built on Chromium’s optimized engine. Energy-saving and consistent — stays fast over time without slowing down. No bloat — stripped of unnecessary components for maximum speed. Minimalist interface — compact, clean, and distraction-free. Customizable toolbar — hide elements you don’t need. Smooth and stable — no flicker, lag, or animation glitches. Comfort-focused experience — intuitive and unobtrusive. Privacy & Security Best privacy by default — blocks ads, trackers, phishing, and third-party cookies. Unbiased ad-blocking — powered by community filters and uBlock Origin. No telemetry or analytics — zero background web requests on first launch. Strict HTTPS enforcement — warns for insecure sites. Passkeys supported — modern authentication made simple. No built-in password manager or cloud sync — your data stays yours. Extension Compatibility Full Chromium extension support — including MV2 extensions. Anonymized Chrome Web Store requests — Google can’t track extension installs. Extended MV2 support — maintained for as long as possible. Smart Features Native !bangs — browse faster using 13,000+ offline-ready shortcuts. AI integration — use !chatgpt and others directly from the address bar. Offline functionality — bangs work without an Internet connection. Philosophy People-first design — open source, transparent, and community-driven. No ads, no noise, no bias — privacy and honesty over profit. Helium Browser 0.13.4.1 changelog: 0a4f1149 revision: bump to 4 (#1969) 4848de1f helium/core: enable the chromium screenshot feature (#1968) e0dec3f5 onboarding: integrate strings to i18n system (#1948) 417fa5bc i18n: fix newline parsing for onboarding 7a339b39 i18n: add foraged translations for onboarding 4f090cff i18n/generate: add handling for onboarding strings bfe48d58 i18n_apply: manually override parent grd logic for onboarding strings ab214e3c onboarding: bump in deps, wire up grdp afa6a059 helium/core: disable pdf infobar feature (#1965) eba585e7 helium/ui/vertical: fix new tab button alignment and icon size (#1964) 6ecfc9e0 helium/ui/tabs: fix horizontal tab hover background color (#1963) 3db87dc0 helium/ui/tabs: fix new tab button hover/press colors (#1962) 6bbdcc3e helium/ui: improve tab group UI in all layouts (#1961) 53deb314 helium/ui/tabs: enable tab group hover cards e93aece7 helium/ui/vertical: fix tab group appearance, prevent line overlap 629f5495 helium/ui/tabs: restore solid group header colors, enable new colors 961c962e helium/ui/tabs: move horiz tab group underline to bottom, make it thick c96deab6 merge: update to chromium 149.0.7827.155 (#1959) 36db56b4 i18n: update source.gen.json 5ce006ae patches: refresh for chromium 149.0.7827.155 b4c1ea62 merge: update ungoogled-chromium to 149.0.7827.155 4e5e8671 Update to Chromium 149.0.7827.155 08a3e7da helium/ui/layout: disable mute on collapsed vertical tabs (#1778) a0a5bbaf helium/core: simplify context menu and prevent huge widths (#1951) c4732aac devutils/i18n: add forage command (#1944) 11d16986 devutils/i18n: add an option to translate using local CLI tools (#1942) d820c3a2 i18n/prompt: tighten translation rules to prevent common errors (#1940) cf827007 Update to Chromium 149.0.7827.114 6e3d5164 Update to Chromium 149.0.7827.102 Download: Helium 64-bit | Portable 64-bit |~100.0 MB (Open Source) Download: Helium ARM64 | Portable ARM64 Links: Helium Home Page | macOS | Linux | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Glow 26.10 by Razvan Serea Glow provides detailed reporting on every hardware component in your computer, saving you valuable time typically spent searching for CPU, motherboard, RAM, graphics card, and other stats. With Glow, all the information is conveniently presented in one clean interface, allowing you to easily access and review the comprehensive hardware details of your system. Glow provides detailed information on various system aspects, including OS, motherboard, processor, memory, graphics card, storage, network, battery, drivers, and services. The well-organized format ensures easy access to the required information. You can export all the gathered data to a plain text file, facilitating sharing with others for troubleshooting purposes. No installation needed. Just decompress the archive, launch the executable, and access computer-related information. Glow runs on Windows 11 and Windows 10 64-bit versions. Glow 26.10 changelog: New Features The bootstrapping algorithm has been completely redesigned. The software can now launch directly without requiring TS Preloader. As part of this change, the startup splash screen displayed during initialization has been removed. In addition, spikes in CPU usage have been eliminated, resulting in a more stable architecture with significantly lower memory consumption. The Microsoft Office detection infrastructure within the Operating System section has been enhanced. Additional detection support has been added for Office C2R (Click-to-Run) installations. Furthermore, the license status evaluation system has been improved, and the priority order has been revised as follows: Licensed > Grace Period > Other (NOTIFICATIONS, EVALUATION, etc.). Glow now includes preliminary support for Wi-Fi 8 technology, allowing more detailed information to be displayed for Wi-Fi 8-compatible network adapters. Glow now provides full support for Bluetooth 6.2. Adapters supporting Bluetooth 6.2 can be analyzed in greater detail and with improved accuracy. The disk distribution view in the Disk section has been modernized, replacing the traditional table layout with a new 2×2 card-based design. The TS Custom Controls module has been updated to v26.7. Thanks to the new custom controls, all Türkaysoft applications now offer a more modern and consistent user interface aligned with Windows 11 design standards. Bug Fixes Potential line-ending handling issues in the Office detection code within the Operating System section have been resolved. Additionally, the output format has been standardized to UTF-8 to prevent character encoding issues and ensure consistent data processing. Several stability and file management issues within the Debugging infrastructure have been addressed. Problems that prevented new log files from being created after Debugging was disabled, as well as issues causing debug records to be lost, have been fixed. File deletion and reaccess issues that occurred after file locks were released have also been resolved. In addition, a bug that caused newly recreated log files to remain locked after deletion has been eliminated. Unnecessary blank lines within debug logs and the extra empty line that could appear at the end of log files have also been corrected. A shortcut key conflict caused by assigning identical hotkeys to both the DNS Test Tool and the Donation page has been fixed. The DNS Test Tool can now be accessed using CTRL + Shift + D, while the Donation page is available via CTRL + Alt + D. Changes The service responsible for providing the Public IP Address and Internet Service Provider information in the Network section has been updated to use the ipinfo.io infrastructure. This change improves the accuracy and consistency of the displayed data. (No external requests are made while Hiding Mode is enabled.) Some terms in the Dutch and Korean language files have been updated to make them clearer and more user-friendly. [TS Updater] Before the update process begins, users are now prompted to choose whether they would like to view the release notes. Note: Always unzip the program before using it. Otherwise you may get an error. Download: Glow 26.10 | 1.8 MB (Open Source) Links: Glow Homepage | Screenshot | Github Get alerted to all of our Software updates on Twitter at @NeowinSoftware
  • Recent Achievements

    • Reacting Well
      BizSAR earned a badge
      Reacting Well
    • First Post
      AndreaB earned a badge
      First Post
    • Week One Done
      Huge Trailer earned a badge
      Week One Done
    • Week One Done
      Classifyskilleducation earned a badge
      Week One Done
    • One Month Later
      eurospharma62 earned a badge
      One Month Later
  • Popular Contributors

    1. 1
      +primortal
      579
    2. 2
      +Edouard
      182
    3. 3
      PsYcHoKiLLa
      75
    4. 4
      Michael Scrip
      73
    5. 5
      neufuse
      64
  • Tell a friend

    Love Neowin? Tell a friend!