Welcome Guest! To access all forums & features, please register an account or sign-in. → Why register?



[jQuery] Submitting a form


17 replies to this topic - - - - -

#1 Shazer2

    Neowinian

  • 59 posts
  • Joined: 15-April 11

Posted 15 April 2011 - 03:58

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:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
    <script type="text/javascript" >
    $(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;
    });
    </script>

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

<?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());  
?>

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.


#2 vetRob

  • 7,332 posts
  • Joined: 06-July 03
  • Location: London, UK

Posted 15 April 2011 - 04:22

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.

#3 OP Shazer2

    Neowinian

  • 59 posts
  • Joined: 15-April 11

Posted 15 April 2011 - 04:25

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?

#4 vetRob

  • 7,332 posts
  • Joined: 06-July 03
  • Location: London, UK

Posted 15 April 2011 - 04:34

Can you post your entire HTML file please? Either a link to it, or the source file.

First step is to ensure the Ajax request is being sent successfully.

#5 OP Shazer2

    Neowinian

  • 59 posts
  • Joined: 15-April 11

Posted 15 April 2011 - 04:39

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

<?php
session_start();
include("inc/connect.php");
?>
<html>
<head>
    <title>Home</title>
    <link rel="stylesheet" href="inc/style.css" type="text/css" />
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
    <script type="text/javascript" >
    $(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;
    });
    </script>

</head>
<body>
    <div align="center">
        <div class="header">
            <div class="logo">
                <a href="index.php"><img src="inc/logo.png" alt="Logo" /></a><br />
            </div>
            
            <?php
            $user = $_SESSION['username'];
            
            if (!$user) {
                header("location:login.php");
            }
            ?>
            
            <div class="useri"><br />
            
            <?php echo "Logged in as: <a href='#'>".$user."</a><br />"; ?>
            
            <a href="logout.php">Logout</a>
            </div><br /><br /><br /><hr />
    
            <div class="newsbox">
                    <u><b>News</b></u><hr />
                    <?php
                    $sql = mysql_query("SELECT * FROM `feed`") or die(mysql_error());
                    while ($rnews = mysql_fetch_array($sql)) {
                        echo $rnews['news']."<br /><br />";
                    }
                    ?>
            </div>
            
            <div class="updatebox">
            <u><b>Updates</b></u><hr />
            <?php
            $sql = mysql_query("SELECT * FROM `feed`") or die(mysql_error());
            while ($rupdate = mysql_fetch_array($sql)) {
                echo $rupdate['update']."<br /><br />";
            }
            ?>
            </div>
            
            <div class="newspost">
            <form id="submit" name="submit" method="POST"> 
            <input name="np" type="text" id="np" style="margin-left: 1px; margin-right: 1px; width: 99%;" />
            <input name="sub" type="submit" id="sub" style="float: right;" value="Post!" />
            </form>
            <br /></div><br />
            
        </div>
    </div>
</body>
</html>


#6 vetRob

  • 7,332 posts
  • Joined: 06-July 03
  • Location: London, UK

Posted 15 April 2011 - 04:42

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() {


#7 OP Shazer2

    Neowinian

  • 59 posts
  • Joined: 15-April 11

Posted 15 April 2011 - 04:45

Alright so I've fixed that bit up. However it still isn't inserting any of the data what so ever into the database. The insert statement is right but it still won't insert it.

Do you have any other ideas?

#8 vetRob

  • 7,332 posts
  • Joined: 06-July 03
  • Location: London, UK

Posted 15 April 2011 - 04:50

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

<script type="text/javascript">
   $(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;
      });
   });
</script>


#9 OP Shazer2

    Neowinian

  • 59 posts
  • Joined: 15-April 11

Posted 15 April 2011 - 04:52

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.

#10 vetRob

  • 7,332 posts
  • Joined: 06-July 03
  • Location: London, UK

Posted 15 April 2011 - 04:56

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 :)

#11 OP Shazer2

    Neowinian

  • 59 posts
  • Joined: 15-April 11

Posted 15 April 2011 - 05:00

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.

#12 vetRob

  • 7,332 posts
  • Joined: 06-July 03
  • Location: London, UK

Posted 15 April 2011 - 05:03

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();


#13 OP Shazer2

    Neowinian

  • 59 posts
  • Joined: 15-April 11

Posted 15 April 2011 - 05:06

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?

#14 vetRob

  • 7,332 posts
  • Joined: 06-July 03
  • Location: London, UK

Posted 15 April 2011 - 05:10

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

<script type="text/javascript">
   $(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
</script>

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

#15 OP Shazer2

    Neowinian

  • 59 posts
  • Joined: 15-April 11

Posted 15 April 2011 - 05:15

Thanks. I just don't understand how to display the success message or the failed message. I know I need to do something like:
<div class="success">Success!</div>

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.