Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 9 of 9
  1. #1
    Regular Coder LearningCoder's Avatar
    Join Date
    Jan 2011
    Location
    The Pleiades
    Posts
    923
    Thanks
    76
    Thanked 29 Times in 29 Posts

    Switching between js and jquery mid script?

    Hello, I have some simple form validation and I have an input field which needs to check a field in a database for a match, otherwise it's an invalid reference number. The check_form_values() function is called in the onclick event handler of the submit button.

    Here is what I have:
    Code:
    function check_email(email,index,error)
    {
    	var len = email.length;
    	
    	if(len == 0)
    	{
    		return index;
    	}
    	else
    	{
    		if(email.charAt(0) == "@")
    		{
    			error[index] = "Invalid email";
    			index++;
    			document.contact_form.email.focus();
    			return index;
    		}
    		else if(email.lastIndexOf(".") < email.lastIndexOf("@")) 
    		{
    			error[index] = "No period after the @ sign. Invalid email!.";
    			index++;
    			document.contact_form.email.focus();
    			return index;
    		}
    		else if(email.indexOf("@") == -1)
    		{
    			error[index] = "You didnt enter an @ sign in your email address.";
    			index++;
    			document.contact_form.email.focus();
    			return index;
    		}
    		else
    		{
    			return index;
    		}
    	}
    }
    
    function check_form_values()
    {	
    	var phone = document.contact_form.phone.value;
    	var error = new Array();
    	var count = 0;
    	var result_email;
    	
    	if(document.contact_form.name.value == "" || document.contact_form.name.value == "")
    	{
    		error[count] = "You must fill in the fields marked with a red asterix.";
    		count++;
    		document.contact_form.name.focus();
    	}
    	
    	if(phone.charAt(0) != "0" || phone.length < 10)
    	{
    		error[count] = "Your phone number must start with a 0 and cannot be less than 10 characters.";
    		count++;
    		document.contact_form.phone.focus();
    	}
    	
    	
    	
    	
    	
    	count = check_email(document.contact_form.email.value, count, error);
    	
    	
    	
    	if(count != 0){
    		
    		for(var n = 0;n < count; n++){
    			alert(error[n]);
    		}
    		
    		return false
    	}
    	else{
    		return true;
    	}
    	
    }
    Just after the check_email() function, I want to check for a value in the 'product id' input field and if it exists, I want to make an ajax call to the database to check that certain field in every row. I believe it would be easier to do this using jQuery.

    I am wondering if I am able to switch to jQuery mid script and is it considered good or bad practice??

    I was thinking of creating another function so my code is a bit easier to read, then as soon as I get inside the function start the jQuery ajax call

    Regards,

    LC.
    Last edited by LearningCoder; 12-19-2012 at 11:14 PM.

  • #2
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,537
    Thanks
    77
    Thanked 4,381 Times in 4,346 Posts
    Ummm...there's no such thing as "switching".

    jQuery *IS* JavaScript. So there's no "switch" to be made.

    Having said that.. If the only reason you will use jQuery on the page is for this one AJAX call... Why? AJAX can be done in just a few lines of vanilla JavaScript. Why drag in the entire jQuery library for something so simple?

    Oh, and in any case, your email test is virtually worthless. I could type in .@@@@@@.... and your code would be perfectly happy.

    Email validation has been discussed in this forum dozens if not hundreds of times. Do a simple search in the forum for *good* examples.

    ***********

    Also, your method of telling the user about errors is really bad.

    You go to all the trouble of creating an array of errors, but then you *STILL* output the errors via alert( ) one at a time!

    At the very least you could do:
    Code:
        if(count != 0)
        {
            alert( "Please correct:\n" + error.join("\n") );
            return false;
        }
        // there is NO POINT in having an else here!  the return means "return right now!"
        return true;
    However, as many here will be happy to tell you, alert( ) is very badly out of style. Some browsers allow users to turn off ALL alerts. And likely most all browsers will do so soon.

    **********

    p.s. There's also no need for your count variable.

    Code:
        if ( ...something fails validation... )
        {
            error.push( "...the error message..." );
        }
        ...
        if ( error.length == 0 ) return true;
     
        document.getElementById("somePlaceToShowErrors").innerHTML = error.join("<br/>");
        return false;
    Last edited by Old Pedant; 12-20-2012 at 12:04 AM.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #3
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,640
    Thanks
    0
    Thanked 649 Times in 639 Posts
    Quote Originally Posted by Old Pedant View Post
    However, as many here will be happy to tell you, alert( ) is very badly out of style. Some browsers allow users to turn off ALL alerts. And likely most all browsers will do so soon.
    The two that don't offer the opportunity to turn off alerts when the second one displays are IE and Opera - Opera offers the opportunity to turn off JavaScript when it displays the first alert.

    So the only browser currently where anyone need ever see a third alert is IE. That's assuming that Microsoft haven't duplicated the alert functionality from other browsers into IE10 - I haven't got access to check that version at the moment. If it isn't in IE10 I'd expect it to be in IE11.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #4
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,346
    Thanks
    11
    Thanked 589 Times in 570 Posts
    Quote Originally Posted by felgall View Post
    That's assuming that Microsoft haven't duplicated the alert functionality from other browsers into IE10 - I haven't got access to check that version at the moment. If it isn't in IE10 I'd expect it to be in IE11.
    IE10 shows only a close button, the title "Message from webpage" and the [X] close window button. There's no checkbox, secondary text, or other buttons...


    that said, IE10 is not set in stone; it can be live-patched at any time, and new features are expected to appear independent of version numbers.

    also, just to be contrary, i would point out that sometimes jQuery is faster than vanilla javascript. not really for a lowly ajax call, though it's not slower, but certain manipulations are common enough that chrome has targeted V8 to optimize jQuery code more than a hand-coded for-loop would be. it's like that fact that JS can outperform C++, depending on the compiler. GCC-compiled C++ is about 15% faster than V8 in tight loops, but V8 would outperform a naive college-project compiler by a substantial margin. The same principle go for large chunks of repetitive high-level routines, the very kind jQuery uses...


    my point isn't that jQuery is great, but that in this day and age, where browsers accelerate jQuery and the google CDN hosted copy is >80% 304s , it's not as objectionable as it was a few years ago.
    Last edited by rnd me; 12-20-2012 at 02:48 AM.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/5/28) IE7:0.1, IE8:5.3, IE11:8.4, IE9:3.2, IE10:3.2, FF:18.2, CH:46, SF:7.9, NON-MOUSE:32%

  • #5
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,640
    Thanks
    0
    Thanked 649 Times in 639 Posts
    Quote Originally Posted by rnd me View Post
    i would point out that sometimes jQuery is faster than vanilla javascript.
    But jQuery is just vanilla JavaScript that just happens to have been written by someone who knows a lot about writing JavaScript.

    There would be nothing to stop you from discarding 95%+ of the code in the jQuery file and just using the small part that you actually are calling - of course if you know enough JavaScript to actually identify the parts of jQuery you are using then you probably know enough to actually write those parts yourself anyway.

    The biggest problem with jQuery is all the novice programmers trying to use it where to use it properly requires an intermediate level of JavaScript knowledge.

    Of course by the time you really know jQuery well enough to use it to its best advantage you will know enough JavaScript that you could have written jQuery yourself. Most people with that level of JavaScript knowledge will likely have already written their own efficient equivalents to those parts of jQuery that they would actually use.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #6
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,346
    Thanks
    11
    Thanked 589 Times in 570 Posts
    Quote Originally Posted by felgall View Post
    There would be nothing to stop you from discarding 95%+ of the code in the jQuery file and just using the small part that you actually are calling - of course if you know enough JavaScript to actually identify the parts of jQuery you are using then you probably know enough to actually write those parts yourself anyway.

    Of course by the time you really know jQuery well enough to use it to its best advantage you will know enough JavaScript that you could have written jQuery yourself.

    i think you're on the mark but there's two sides to jQuery's intervention.

    the first and obvious one is the browser api unification it provides. In the age of IE6, even 7, this was a very compelling feature; after all, why should we as developers need to type both innerText and textContent ?

    in short, jQuery consolidated the DOM mess and offered what could arguably be called "missing" features to bare dom/js/css stack; mainly reliable "css selectors". I have no doubt that this is why it became #1.


    dom unification, or "IE7 support" or what have you, is less compelling by the day. XMLHttpRequest() went "native" in IE7, and even way back in IE8 they added the single biggest jQuery killer-blow: querySelelctorAll(). Most of jQuery's "Greatest Hits" are now available pretty consistently from the natural environment, especially on mobile, which is where the growth is.



    the 2nd half is a much tougher foot to push out of the door jam: plugins.

    If anything keeps jQuery alive, it will be it's plugins. There is HUGE momentum for many of these in the CMS and design community. Some of them are not half-bad. They more recently and now continue serve the same role that jQuery did initially: a survey of "what's missing".

    Now, we have html5 form validation specs, css reflections and transitions, native smooth scrolling, onhashchange(), history.pushState(), <script defer/async>, CSS animation, <input type=email|url|search|date>, Drag and Drop, and many more emerging in the wild. These capabilities first became mainstreamed as plugins.

    personally, i think a lot of plugins are poorly coded and slow, but the concepts they implement and the problems they attempt to address are of note.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/5/28) IE7:0.1, IE8:5.3, IE11:8.4, IE9:3.2, IE10:3.2, FF:18.2, CH:46, SF:7.9, NON-MOUSE:32%

  • #7
    Regular Coder Redcoder's Avatar
    Join Date
    May 2012
    Location
    /dev/null
    Posts
    333
    Thanks
    2
    Thanked 47 Times in 46 Posts
    Just my 2 cents, if this is for a signup page, email validation has spawned large debates and Regex's. The simple thing to do to validate someone's email is just to send them an email with a validation link during signup. Make it such that they can't login if they haven't been validated. Of course check for '@' and '.' .

    If its just a form for checking whether an email address exists, well if the email isn't there in the database, it isn't there.

  • #8
    Regular Coder LearningCoder's Avatar
    Join Date
    Jan 2011
    Location
    The Pleiades
    Posts
    923
    Thanks
    76
    Thanked 29 Times in 29 Posts
    Quote Originally Posted by Old Pedant View Post
    Ummm...there's no such thing as "switching".

    jQuery *IS* JavaScript. So there's no "switch" to be made.

    Having said that.. If the only reason you will use jQuery on the page is for this one AJAX call... Why? AJAX can be done in just a few lines of vanilla JavaScript. Why drag in the entire jQuery library for something so simple?
    I didn't realize it was as easy as you say because my JS book tells me that I have to check for ActiveXObjects or something then do two different things depending on what it returns. I thought it would be a lot easier with jQ.

    Quote Originally Posted by OldPedant
    Oh, and in any case, your email test is virtually worthless. I could type in .@@@@@@.... and your code would be perfectly happy.

    Email validation has been discussed in this forum dozens if not hundreds of times. Do a simple search in the forum for *good* examples.
    I know it isn't the best but I just wanted to add at least some js validation to prevent a certain submit to the server. It's a real difficult subject if you aren't familiar with RegExps. I'm not too worried though because if it does pass my JS validation, I have some PHP email validation which should catch it.

    Quote Originally Posted by OldPedant
    Also, your method of telling the user about errors is really bad.

    You go to all the trouble of creating an array of errors, but then you *STILL* output the errors via alert( ) one at a time!

    At the very least you could do:
    Code:
        if(count != 0)
        {
            alert( "Please correct:\n" + error.join("\n") );
            return false;
        }
        // there is NO POINT in having an else here!  the return means "return right now!"
        return true;
    However, as many here will be happy to tell you, alert( ) is very badly out of style. Some browsers allow users to turn off ALL alerts. And likely most all browsers will do so soon.
    Thank you very much that seems a much better way rather than alerting one at a time. If alert() is old and not used to much anymore, what is the other alternative? Do you just innerHTML anything you need to directly to the page? Is there a new way to show an alert() or should we not be using any alert type messages altogether?

    Quote Originally Posted by OldPedant
    p.s. There's also no need for your count variable.

    Code:
        if ( ...something fails validation... )
        {
            error.push( "...the error message..." );
        }
        ...
        if ( error.length == 0 ) return true;
     
        document.getElementById("somePlaceToShowErrors").innerHTML = error.join("<br/>");
        return false;
    Thank you very much, I think that code just answered my question above! I'll start editing the code as soon as I can sort my other issue out. Can't get onto my contact page because it connects to mysql and it doesn't seem to be loaded as an extension in my version of php :s I've got mysqlnd?

    Nevertheless thank you indeedy.

    Regards,

    Lc.

  • #9
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,537
    Thanks
    77
    Thanked 4,381 Times in 4,346 Posts
    > my JS book tells me that I have to check for ActiveXObjects or something then do two different things depending on what it returns

    Used to be true. But even MSIE 7 supports the standard way now. So you would only need to worry about it if you want to support MSIE 6 and before. Ancient history.

    I don't know what query you want to make of your PHP code. You mentioned a product id? What will your PHP send back? Just a "YES/NO" response or info about the product?

    But something like this:
    Code:
    function ajax( prodid )
    {
        // if you want to support MSIE 6 and 5:
        var http = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
    
        // if you don't care about IE 6 and 5:
        var http = new XMLHttpRequest();
    
        // rest same no matter what:
        var url = "http://www.yoursite.com/yourpage.php?productid= " + encodeURIComponent(prodid);
    
        http.open( "GET", url, true );
        http.send( );
    
        http.onreadystatechange = function( ) 
        {
            if (http.readyState==4)
            { 
                document.getElementById("productDetails").innerHTML = 
                    http.status == 200 ? http.responseText : "Error getting details: " + http.status;
            }
        }
    }
    Would you really drag in the entire jQuery library just to replace that simple code?
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •