• 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

    • Waymo recalls self-driving software after cars enter closed freeway work zones by Paul Hill Waymo, the self-driving car maker owned by Alphabet – the parent company of Google –, has recalled some of its fifth-generation Automated Driving Systems (ADS). It did so after some of its cars drove through closed construction zones. According to the National Highway Traffic Safety Administration (NHTSA), the affected vehicles were capable of driving through a closed freeway construction zone and continuing to drive at speed. The listing on the NHTSA website says that Waymo is currently developing a solution to fix this issue, but in the meantime, freeway driving is being restricted. Waymo will update its ADS software so that vehicles can detect when they can avoid entering construction zones. According to the Safety Recall Report, on April 20, 2026, Waymo’s Field Safety Committee began meetings reviewing an event from April 11, 2026, and five events from April 19, 2026, where Waymo’s autonomous vehicles didn’t recognize and drove past ramp closure signs into the pre-planned freeway construction zones. This took place in Phoenix, Arizona. Separately, on May 18, 2026, seven Waymo vehicles entered freeway lanes with active construction in the San Francisco Bay Area by driving between cones that were placed to show the lane was closed. On the back of both of these events, Waymo restricted freeway driving until it could address the issue. In June, Waymo’s Safety Board reviewed the issue and additional information related to ADS performances around construction zones; then, as a result, it decided to conduct a recall. This development is not good for Waymo as it adds to a growing list of technical hiccups its cars have experienced. Ultimately, it will lead to more scrutiny from lawmakers around the world who will be more cautious about letting autonomous vehicles on their roads without tighter regulation. For readers in areas where Waymo operates, does this news make you more wary about stepping into one of these vehicles?
    • I'm still on Windows 10 22H2 because I didn't want to deal with all the issues in Windows 11, so I waited almost a week before installing the latest Patch Tuesday update (KB5094127), I went ahead and did it, and it was a huge mistake—ever since then, my File Explorer has seen a performance drop of about 30% when transferring large files... Once again, Microsoft has outdone itself! This update cannot be uninstalled, either through the Control Panel (via Settings) or by accessing Advanced Startup Options. The only possible alternative would be to use system restore points, but I’d have to reinstall all app and driver updates (and there’s no guarantee it would work). Or there’s the “nuclear option” of a in-place repair without losing files or apps, but even then, all my customizations would be lost! Microsoft just can’t help but mess everything up! Way to go, Microsoft! But I still don’t want your c****y Windows 11!
    • Microsoft: Windows 11 could finally solve a major issue across AMD, Nvidia, and Intel GPUs by Sayan Sen While Microsoft has been trying to improve it, Windows 11 is definitely not flawless, as even today some issues are taking a year to publicly acknowledge. However, one area of trouble that may finally see much better results soon is graphics driver crashes. Work on graphics driver timeouts, also called Timeout and Detection Recovery (TDR), is not new as the latest WDDM 3.2 also has specific improvements regarding it. Windows Display Driver Model (WDDM) version 3.2 is supported on Windows 11 24H2 and 25H2. However, with the upcoming version 26H2, TDR crash diagnosis could go to the next level as Microsoft is introducing a new DirectX 12 API feature called "DirectX Dump Files". Similar to how system memory dump files work when a system crashes or freezes or encounters any such major issue, DirectX Dump Files (DDF) will essentially record a snapshot of the GPU execution right at the moment a graphics-related crash or hang or freeze occurs, so that developers can better understand and diagnoze these TDR and timeout detection errors. The dump will be available as a .dxdmp file for analysis and it will be a comprehensive dump file generated with detailed insights about the hardware, drivers, Windows, as well as the affected application. This should be another welcome change in this department. Earlier at GDC 2026, when the technology was first debuted, Microsoft had shared more details regarding it. The company had explained how DDF is designed to gather data from every layer of the graphics stack into a single file, eliminating the need for developers to manually correlate logs from multiple tools. As mentioned above, the dump can contain a lot of useful details like GPU hardware state information such as register values, shader program counters, page fault virtual addresses, shader memory data, and command buffers. Alongside that, it also captures DirectX runtime and kernel information, including D3D objects, pipeline state objects, device error data, adapter details, and CPU call stacks. Microsoft says the feature has been built around two primary use cases: retail device removals and local device removals. The former allows developers to collect crash information from end users' systems in the field, while the latter helps QA teams and developers investigate issues on test machines. Developers will also be able to include up to 2 MB of custom application data through new D3D12 APIs, providing additional context for troubleshooting. In addition, Microsoft is introducing three dump collection modes ranging from zero-overhead capture, which has no runtime performance impact on supported hardware, to higher-detail modes that collect more vendor-specific debugging data. On compatible Tier 2 hardware, zero-overhead dumps will be enabled by default, meaning developers may begin receiving useful crash diagnostics without making any code changes. The table below explains the three tiers: Tier Description NO_OVERHEAD Enables crash capture with no runtime cost and is suitable for broad deployment MEDIUM_OVERHEAD Provides a balance, capturing additional diagnostic data with moderate impact HIGH_OVERHEAD Collects the most detailed GPU and driver state available, enabling deeper investigation at the cost of higher runtime overhead In terms of availability, the company expects broader release to be around the fall of 2026, which should be right around the time when Windows 11 version 26H2 lands. Right now, DirectX Dump Files are available as a preview and currently, only AMD has the compatible AgilitySDK Developer Preview driver version 26.10.07.02. You can find the official announcement post here on Microsoft's website.
    • And with SO much better perf than the laggy mess that is Files.
  • Recent Achievements

    • One Month Later
      Sharbel earned a badge
      One Month Later
    • First Post
      BizSAR earned a badge
      First Post
    • Week One Done
      Jordan Smith earned a badge
      Week One Done
    • Reacting Well
      BizSAR earned a badge
      Reacting Well
    • First Post
      AndreaB earned a badge
      First Post
  • Popular Contributors

    1. 1
      +primortal
      598
    2. 2
      +Edouard
      190
    3. 3
      PsYcHoKiLLa
      80
    4. 4
      Michael Scrip
      76
    5. 5
      Steven P.
      69
  • Tell a friend

    Love Neowin? Tell a friend!