views:

88

answers:

2

Hey all. I was fortunate enough to have Paolo help me with a piece of jquery code that would show the end user an error message if data was saved or not saved to a database. I am looking at the code and my imagination is running wild because I am wondering if I could use just that one piece of code and import the selector type into it and then include that whole json script into my document. This would save me from having to include the json script into 10 different documents. Hope I'm making sense here.

$('#add_customer_form').submit(function() { // handle form submit

The "add_customer_form" id is what I would like to change on a per page basis. If I could successfully do this, then I could make a class of some sort that would just use the rest of this json script and include it where I needed it. I'm sure someone has already thought of this so I was wondering if someone could give me some pointers.

Thanks!


Well, I hit a wall so to speak. The code below is the code that is already in my form. It is using a datastring datatype but I need json. What should I do? I want to replace the stupid alert box with the nice 100% wide green div where my server says all is ok.

$.ajax({
  type: "POST",
  url: "body.php?action=admCustomer",
  data: dataString,
  success: function(){
    $('#contact input[type=text]').val('');
    alert( "Success! Data Saved");
  }
 });
+2  A: 

Here is the code I used in the last question, minus the comments:

$(function() {
    $('#add_customer_form').submit(function() {
        var data = $(this).serialize();
        var url = $(this).attr('action');
        var method = $(this).attr('method');
        $.ajax({
            url: url,
            type: method,
            data: data,
            dataType: 'json',
            success: function(data) {
                var $div = $('<div>').attr('id', 'message').html(data.message);
                if(data.success == 0) {
                    $div.addClass('error');
                } else {
                    $div.addClass('success');
                }
                $('body').append($div);
            }
        });
        return false;
    });
});

If I am right, what you are essentially asking is how you can make this piece of code work for multiple forms without having to edit the selector. This is very easy. As long as you have the above code included in every page with a form, you can change the $('#add_customer_form') part to something like $('form.json_response'). With this selector we are basically telling jQuery "any form with a class of json_response should be handled through this submit function" - The specific class I'm using is not relevant here, the point is you use a class and give it to all the forms that should have the functionality. Remember, jQuery works on sets of objects. The way I originally had it the set happened to be 1 element, but every jQuery function is meant to act upon as many elements as it matches. This way, whenever you create a form you want to handle through AJAX (and you know the server will return a JSON response with a success indicator), you can simply add whatever class you choose and the jQuery code will take over and handle it for you.

There is also a cleaner plugin that sort of does this, but the above is fine too.

Paolo Bergantino
Thanks Paolo. What I was wondering, and it may not be feasable, but I am big on code reuse. If I could save just that single code and maybe put it into a function and import the new selestor value, I wouldn't need to actually have 25 lines. I would just have the javascript tags that point to this single piece of code.
I'm sorry, I still don't think I am that clear. I just got off work and my mind is mush. :)
That's what I am talking about. You can just save the above code in something like ajaxform.js, have a script tag like <script type="text/javascript" src="ajaxform.js"></script> in any page that has a form, and if you give it the right class (json_response in my example), the jQuery code will always handle it.
Paolo Bergantino
Ok... so if I am understanding you correctly, I wouldn't even need to change the id selector in your JQ code only make sure to include the class selectors (.error and .success) in my html. Am I right?
You would need to change the ID selector if you want multiple forms to be matched by this (unless you give them all the same ID...). Presumably you have an external stylesheet where you keep the styles for .error and .success. If you include those in every page with a form and you include the javascript in every page with a form, everything would be taken care of. I'm sorry if I'm not being very clear I guess I'm not very good at explaining this stuff, haha.
Paolo Bergantino
+1, this is stellar help. Go noles!
altCognito
No Paolo, your great at explaining this, it's just that I am having a hard time wraping my brain around this new stuff and sometimes I just don't know how to explain what it is exactly that I need. Like above, I said that I want to use this code also for my try/catch blocks which was really confusing to the readers because your code only works for submitting a form. I would think however that I could modify this same code to use when my php barfs. No?I'm just starting to see SOOO many possibilities with JQ that it blows my mind. :)
@altCognito Whatever stellar help means....
@altCognito: Ah, a noles cheer will melt my heart everytime. :)
Paolo Bergantino
Ok.. you said that I would need to change the id selector. But you don't mean in your code, do you? I;m thinking that you mean in my html. right?
@nutjob: What try/catch blocks? In PHP or in Javascript? jQuery is not (usually...) executed server-side, so you might be missing the key distinction between stuff happening on the client vs the server. Maybe if you posted some code/pseudocode I can see what you mean easier?
Paolo Bergantino
haha... I must be getting old cuz I have no idea what or *who* noles is. :)
@nutjob: I do mean in my code; you would change the $('#add_customer_form') bit to something like $('form.json') and then have your form declaration be something like <form class='json' ...> - Noles, short for Seminoles, is the mascot of my university (Florida State)
Paolo Bergantino
Ok, here is what I was thinking... I see that I can return a true/false value from my php methods. So... I was wondering why I wouldn't be able to use JQ when my php scripts barf for whatever reason. Here is how I was planning to use it.
ah.. ok.. Well then.. Go Noles! :)Say that I have a php mailer script that imports a bunch of emails to send a mailing. Say the user presses the send button and the php starts compiling these emails and then for whatever reason, the script dies. I could encapsulate the mail function inside of try/catch block and on the catch side, fire this JQ script if anything bad happens. That is the general idea. Do you think it would work?
Yeah, you could do that. I don't see why not.
Paolo Bergantino
That's SO cool! If this could be done, I'm thinking that I could make a php error class or something like that that would show the user when something bad happened. They wouldn't need the stack that an exception outputs but a small error message telling them that something went wrong would be cool. It was just a thought though. Thanks Paolo!
I'm not certain if I should post in this same thread, but I kind of hit a wall. I am already using JQ in the form where I would like to add this little JQ popup and it has a datatype of datastring. For my server callback, I need a datatype of json. What should I do? I can post the code that I am currently using up top.
post the code :)
Paolo Bergantino
Hi Paolo. Thanks again. I posted it above in my original post. I can't see how this should tie together. Your script has a success function and so does the one that's already in the form. I totally forgot that I was using an ajax submit on that form.
+2  A: 

Based on your question, I think what you want is a jQuery selector that will select the right form on each of your pages. If you gave them all a consistent class you could use the same code on each page:

HTML

<form id="some_form_name" class="AJAX_form"> ... </form>

Selector:

$('form.AJAX_form")
acrosman
Hi acrosman. Thanks. I think that is what I may need. :)