0

When a user inserts data into a form and then submits it, it goes to my php script and inserts the data. The script will return a value letting the user know if the data was inserted or not. Since I am using JQuery, I have no idea how to do this. Can someone please point me in the right direction? All I'm after here is a nice, neat little 200px by 25px container that will fade in and the user MUST click it to acknowledge it.

Now that I think about it, since users are not the brightest lights in the harbor, it would be really cool if I could not only show then this css box letting them know if the insert was successful but also show them the customer that was inserted in case they forgot where they left off.

Thanks.

Paolo Bergantino
  • 480,997
  • 81
  • 517
  • 436
user109162
  • 147
  • 4
  • 16

3 Answers3

4

I'm not going to mark this as a duplicate, but you are essentially asking the best way to show notifications using jQuery. And that has been asked before. In a nutshell, in your basic setup all you need to do is show a div and fade it in, but there are a lot of plugins out there that handle more situations.

As far as showing them the customer that was inserted or whatever, all you have to do is return a JSON response from the server and handle it with the success callback of your AJAX request. You will have access to the data passed back from the server then.

To explain a little further: What you seem to be asking to do is how to send a request to a server using Ajax, get a notification that everything went as expected, and then show a notification in the webpage depending on what happened. If that is correct, I'm going to move on with these assumptions.

Let's put together a simple form to add a new customer to a fictional website. It might look like this:

<form action='add_customer.php' method='POST' id='add_customer_form'>
    First Name: <input type='text' name='first_name'><br>
    Last Name: <input type='text' name='last_name'><br>
    Email: <input type='text' name='email'><br>
    <input type='submit' value='Add Customer'>
</form>

Now, our naive, insecure PHP code to handle this form submission (through AJAX) might look something like this. I say naive and insecure because you would do more data validation (as you never trust anything coming from the client) and would certainly need to clean the data to prevent SQL injections. This is an example, however, so it might look like this:

$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email = $_POST['email'];
if(mysql_query("
    INSERT INTO customers
    (first_name, last_name, email)
    VALUES 
    ('$first_name','$last_name','$email')
   ")) {
    $success = 1;
    $message = 'Customer ' . $first_name . ' successfully added!';
} else {
    $success = 0;
    $message = 'Something went wrong while adding the customer!';
}
print json_encode(array('success' => $success, 'message' => $message));

We might then handle the sending of this form and the receiving of data from the server, using jQuery, with code that looks a little something like this:

$(function() {
    $('#add_customer_form').submit(function() { // handle form submit
        var data = $(this).serialize(); // get form's data
        var url = $(this).attr('action'); // get form's action
        var method = $(this).attr('method'); // get form's method
        $.ajax({
            url: url, // where is this being sent to?
            type: method, // we're performing a POST
            data: data, // we're sending the form data
            dataType: 'json', // what will the server send back?
            success: function(data) { // the request succeeded, now what?
                // here data is a JSON object we received from the server
                // data.success will be 0 if something went wrong
                // and 1 if everything went well. data.message will have
                // the message we want to display to the user
                // at this point you would use one of the techniques I linked
                // to in order to display a fancy notification

                // the line below will dynamically create a new div element,
                // give it an ID of "message" (presumably for CSS purposes)
                // and insert the message returned by the server inside of it
                var $div = $('<div>').attr('id', 'message').html(data.message);

                if(data.success == 0) {
                    $div.addClass('error'); // to personalize the type of error
                } else {
                    $div.addClass('success'); // to personalize the type of error
                }
                $('body').append($div); // add the div to the document
            }
        });
        return false; // prevent non-ajax form submission.
    });
});

I haven't tested any of this code but the idea is there. You return a format, JSON, from the server, with data, and handle the success callback jQuery fires when the request is complete, and add an element to your document you can style however you want (and show with things like fadeIn() if you want) with a message describing what happened. You might also need to catch the error callback (which fires if your server doesn't respond for whatever reason) and firing off another alert in that situation.

Community
  • 1
  • 1
Paolo Bergantino
  • 480,997
  • 81
  • 517
  • 436
  • Thanks for your link. I just looked it over but I still don't see a way to have the window pop up if the server sends back an aknowledgement. Any thoughts? I know that I can pop up a box, heck, I can do that with an alert box but how does one inject data from server side? Thanks. – user109162 May 21 '09 at 05:50
  • 1
    You would use the code in the success callback of your ajax call. You return JSON from the server, tell jQuery what dataType to expect, and then use the data returned to populate the DIV. – Paolo Bergantino May 21 '09 at 05:53
  • Hey Paolo, thanks. I'm sorry but I don't understand. I am using JSON to import my database stuff into the textboxes but I'm not sure how to do what your talking about. Is there some sort of a tut that you could point me to that would explain this in detail? I'd sure like to use this.. It would help my users greatly. Thanks for any help you can provide. – user109162 May 21 '09 at 06:01
  • OMG.. Paolo. Thank you man! I didn't expect this. :) Comments and all. I actually thought you guys gave up on me so I left for a bit. Paolo, thank you vety much! – user109162 May 21 '09 at 06:51
  • Give up? Never. :) Let me know if you need any more help. If I remember correctly you also had that question about the best jQuery resources so I know how frustrating it is learning this at first. Once you get it going, though, it's really awesome. Good luck. – Paolo Bergantino May 21 '09 at 06:55
  • Yes, that was me. You have a good memory. :) Thanks so much! If I run into an issue I will be sure to post back and also, if you wouldn't mind, I'd sure like to pick you brain a bit over and above the comments you posted. I mean, they are clear and all but I'd like to know a little more in depth about what they are really doing behind the scenes. BTW: the PHP for me is no problem, its just the javascript stuff thats a bit arcane for me to pick up right now. – user109162 May 21 '09 at 07:05
  • I understand. I'm pretty active on this site if you can't tell so I'll usually jump on any question tagged javascript/jquery, but if its something else my email is in my profile and I don't mind answering questions anytime. – Paolo Bergantino May 21 '09 at 07:18
  • Thanks!! I am working on this now and I am almost through with the php. I can't wait. :D I'm like a kid with a new toy... And.. thank you for the offer to answer a question or two via email. I actually just checked out your site and you have quite a portfolio goin on there. Very nice work my friend! – user109162 May 21 '09 at 07:25
  • Haha, thanks. I need to update it with 2009 stuff. It's been a crazy year so far. :) – Paolo Bergantino May 21 '09 at 07:32
  • lol... If only I had the problem of too much work... I'm glad that you are keeping busy with work. It always seems like the developers that are really good seem to get all the work, and rightfully so. I generally work with server side but this stuff is like magic! I have never seen technology like this before. I mean, way back when, javascript was nothing and now, well, its come a long way. Anyhow, Paolo... I have this thing working. Thank you so much! I have a question that I'd like to ask you about the php side if I could. Should I start a new thread? – user109162 May 21 '09 at 07:43
  • Thanks, but I'm not getting all the work JUST YET ;) I'm actually still in school trying to get my stupid degree. I'm kind of lazy when it comes to school, especially because I think I know it all :D I do freelance work on the side to pay the bills until I can graduate and get a formal job hopefully doing this. But yeah, this jQuery's stuff is amazing. Anyhow, you should start a new question if you have anything else not directly related to this. – Paolo Bergantino May 21 '09 at 13:43
1

Fading effects can be accomplished by doing one of the following:

jQuery(myDiv).fadeIn()
jQuery(myDiv).fadeOut()
jQuery(myDiv).fadeTo()

I'd recommend you first create this css box - create the html and the css. Then you can experiment with fading - jQuery lets you specify arguments like fade color, fade duration, etc.

Gabriel Florit
  • 2,886
  • 1
  • 22
  • 36
1

Here is something to work from...

Your PHP script outputs this depending on results

$json = array(
    'success' => $insertSuccess,
    'message' => $numRecords . ' records inserted in ' . $insertTime . 's'
);

echo json_encode($json);

Then, in the callback of your JSON, you determine from parsing the JSON object if the insert was successful or not. Your callback might look something like this

function(data) {

    success = data.insertedSuccess;

    if (success) {
         $('#success').fadeIn(1000);
    } else {
         $('#failure').fadeIn(1000);
    }

}
alex
  • 479,566
  • 201
  • 878
  • 984
  • I'm really racking up these badges boy. :) Thanks for the snippet Alex. Paolo is suggesting something where I can use JSON to echo my server side stuff to a window which would be awsome! I just don't understand what he means. Can you translate? – user109162 May 21 '09 at 05:58
  • Yes, you could provide additional info in your JSON that you return like '1 record inserted in 0.01s' or similar. – alex May 21 '09 at 06:01
  • Hmm.. My JSON just returns an array from the database. Would I just add onto that array? – user109162 May 21 '09 at 06:05
  • I'll add some more to the answer – alex May 21 '09 at 06:27
  • Hey Alex, thanks! Paolo takes this one hands down. :) I truly appriciate your answer too. I think I can use the fadeIn() function in there as well. When you provided a sample of the encoded array, it kind of made sense to me. I feel terrible that I am having to learn to crawl all over again. – user109162 May 21 '09 at 07:02