1

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");
  }
 });
user109162
  • 147
  • 4
  • 16
  • Hey nutjob. :) I think the part of your question that is confusing me is the "JSON script" part. Are you actually referring to the code I put in your last question to handle the form submission? Do you mean you want to abstract it out into a plugin sort of thing so you can just call that on a particular form on a page and have it handle everything nicely? – Paolo Bergantino May 22 '09 at 02:17
  • Wait, what does this have to do with JSON? What on earth is a "JSON Script" ? – Breton May 22 '09 at 02:18
  • Hi Paolo.. Thanks for the reply. Actually what I am talking about is exactly what you have said. I want to abstract your code and simply include it where I may need it. I'm referring to the JSON script as the JQuery code you posted, not the PHP or the html. I told you a was newer than new to all this. :) – user109162 May 22 '09 at 02:21
  • "dataString" is not a data type. I don't see where you define it, but if you use the serialize() on it, it IS a JSON object. if your server is then returning JSON, you have to add an extra parameters, dataType: 'json', and have your success callback receive it. – Paolo Bergantino May 22 '09 at 04:09

2 Answers2

2

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.

Community
  • 1
  • 1
Paolo Bergantino
  • 480,997
  • 81
  • 517
  • 436
  • 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. – user109162 May 22 '09 at 02:26
  • I'm sorry, I still don't think I am that clear. I just got off work and my mind is mush. :) – user109162 May 22 '09 at 02:27
  • That's what I am talking about. You can just save the above code in something like ajaxform.js, have a script tag like 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 May 22 '09 at 02:28
  • 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? – user109162 May 22 '09 at 02:32
  • 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 May 22 '09 at 02:36
  • 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. :) – user109162 May 22 '09 at 02:40
  • @altCognito: Ah, a noles cheer will melt my heart everytime. :) – Paolo Bergantino May 22 '09 at 02:44
  • 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? – user109162 May 22 '09 at 02:44
  • @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 May 22 '09 at 02:45
  • haha... I must be getting old cuz I have no idea what or *who* noles is. :) – user109162 May 22 '09 at 02:45
  • @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
    - Noles, short for Seminoles, is the mascot of my university (Florida State)
    – Paolo Bergantino May 22 '09 at 02:46
  • 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. – user109162 May 22 '09 at 02:47
  • 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? – user109162 May 22 '09 at 02:50
  • Yeah, you could do that. I don't see why not. – Paolo Bergantino May 22 '09 at 02:56
  • 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! – user109162 May 22 '09 at 03:00
  • 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. – user109162 May 22 '09 at 03:53
  • 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. – user109162 May 22 '09 at 04:10
2

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
  • 12,814
  • 10
  • 39
  • 55