1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

onsubmit problems

Discussion in 'JavaScript' started by Jeremy Benson, Aug 9, 2015.

  1. #1
    Hello,

    I'm building a pretty big js application for my webpage, but the form onsubmit is submitting every time. I'm expecting to see some alerts before hand. I know some things are coded a little wonky. I got the errors weeded out from firbug. Now it just submits, so I'm thinking there's some other error... The onsubmit
    event is set to the function send_product()

    Edit: Found spelling error between this.success and the way success was being spelled in returns. Fixed all spelling errors, but still not working.

    jProduct.js
    
    function jProduct()
    {
      
       this.title;
       this.genre;
       this.company;
       this.price;
       this.ulr;
       this.format;
       this.languages;
       this.systemRequirements;
       this.mediaFirst;
       this.videos = new Array();
       this.crewUsernames = new Array();
       this.token;
      
       this.errors = new Array();
       this.success = false;
      
       this.update_title = function()
       {
        
         this.title = $('#title').val();
        
       }
      
       this.update_genre = function()
       {
        
         this.genre = $('#genre').val();
        
       }
      
       this.update_company = function()
       {
        
         this.company = $('#company').val();
       }
      
       this.update_price = function()
       {
        
         this.price = $('#price').val();
        
       }
      
       this.update_url = function()
       {
        
         this.url = $('#url').val();
        
       }
      
       this.update_format = function()
       {
        
         this.format = $('#format').val();
        
       }
      
       this.update_languages = function()
       {
        
        
         this.languages = $('#languages').val();
        
       }
      
       this.update_system_requirements = function()
       {
        
         this.systemRequirements = $('#systemRequirements').val();
        
       }
      
       this.update_media_first = function()
       {
        
         this.mediaFirst = $('#mediaFirst').val();
        
       }
      
       this.add_crew = function(usernameSet)
       {
        
         this.crew.push(usernameSet);
        
       }
      
       this.send_product = function()
       {
        
         // this function sends the product to server side script
        
         var validator = new jValidator;
        
         validator.validate_text(this.title, 1, 'title too short.');
         validator.validate_select(this.genre, '', 'select genre.');
         validator.validate_text(this.company, 1, 'enter company.');
         validator.validate_text(this.url, 2, 'enter url to store/site');
         validator.validate_select(this.format, '', 'select format');
        
         this.errors = validator.return_errors();
        
         if(this.errors.length < 0)
         {
           // There were no errors, send basic product info to server side script post_product.php
          
           var productData = {"title":this.title, "genre":this.genre, "company":this.company, "url":this.url, "format":this.format, "operation":"post"};
        
           $.ajax({
             method: "POST",
             url: "../../php/scripts/post_product.php",
             dataType:"html",
             data:productData
              
           }).done(function(html){
            
             if(html != '')
             {
               // append token to form, and send it with images and videos.
              
              var form = document.forms['post-product-form'];
              this.form_token(form, 'token', html);
            
              alert(html);
            
      if(this.send_crew())
              {
                
                if(this.send_videos())
                {
                  
                  this.success = true;
                  return this.success;
                  
                }else{
                  
                  // could not send videos
                  return this.success;
                  
                }
                
              }else{
                
                // could not send crew.
                return this.success;
                
              }            
              
              
               return this.success;
             }else{
              
               return this.success;
              
             }
            
             return this.success;
           });
                
         }else{
          
           // there were errors in validation
          
           return this.success;
        
         }
      
         // end send product
        
       }
      
       this.send_crew = function()
       {
        
         // loop this to send every crew member.
        
         for(i = 0; i < this.crewUsernames.length; i++)
         {
        
             var crewDate = {"crewID":this.crew[i], "token":this.token};
            
             $.ajax({
                 method: "POST",
                 url: "../../php/scripts/post_product_crew.php",
                 dataType:"html",
                 data:crewData
                          
               }).done(function(html){
                
                 if(html != 'complete' && i == this.crewUsernames.length)
                 {
                  alert(html);
                  
                   return true;
              
                 }else{
                  
                   return false;
                  
                 }
                
               });
         }
         // end send crew function
        
       }
    
       // this function will send videos to post_product_videos.php
      
       this.send_videos = function()
       {
        
         // loop this to send every video.
        
         for(i = 0; i < this.videos.length; i++)
         {
        
             var crewDate = {"video":this.videos[i], "token":this.token};
            
             $.ajax({
                 method: "POST",
                 url: "../../php/scripts/post_product_videos.php",
                 dataType:"html",
                 data:videoData
                          
               }).done(function(html){
                
                 if(html != 'complete' && i == this.videos.length)
                 {
                  
                   return true;
                   alert(html);
                  
            
                 }else{
                  
                   return false;
                  
                 }
                
               });
         }
         // end send crew function
        
       }
      
       this.form_token = function(formSet, keySet, valSet)
       {
         // This function will add product token to the form
         // This will allow for the server side script to update where token is in product table.
        
         var input = document.createElement('input');
         input.type = 'hidden';
         input.name = keySet;'name-as-seen-at-the-server';
         input.value = valSet;
         formSet.appendChild(input);
        
       }
      
       this.add_crew = function(usernameSet)
       {
        
         this.crewUsernames.push(usernameSet);
        
       }
      
       this.add_video = function (videoSet)
       {
        
         this.videos.push(videoSet);
        
       }
      
    }
    
    Code (JavaScript):
     
    Last edited: Aug 9, 2015
    Jeremy Benson, Aug 9, 2015 IP
  2. iterationlabs

    iterationlabs Active Member

    Messages:
    174
    Likes Received:
    2
    Best Answers:
    1
    Trophy Points:
    63
    #2
    Hey Jeremy,

    A few ideas.

    1) Why do you have the lines like "this.title;" that have no assignment? These won't be doing anything.
    2) This won't work: if(this.errors.length < 0)
    Length can never be less than 0. I think you want === 0.
     
    iterationlabs, Aug 9, 2015 IP
  3. Jeremy Benson

    Jeremy Benson Well-Known Member

    Messages:
    364
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    123
    #3
    Hey,

    Thanks for the reply. The fields are getting assigned during the typing process through update_[field] functions using onkeyup in the form.

    I never even noticed the logic error there. Thanks for the reply! I'll check it out, and report back :)

    thanks again.
     
    Jeremy Benson, Aug 9, 2015 IP
  4. Jeremy Benson

    Jeremy Benson Well-Known Member

    Messages:
    364
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    123
    #4
    Gah, Still giving me problems... Each of the scripts that ajax contacts returns "not done." as I just echoed that out in each script to test the code.

    I've edited the code to. I forgot to take into account that the user might not have added any crew, or videos, so those functions have to return something to keep the script going... I'm confused as all got out, lol.

    function jProduct()
    {
       
        this.title;
        this.genre;
        this.company;
        this.price;
        this.ulr;
        this.format;
        this.languages;
        this.systemRequirements;
        this.mediaFirst;
        this.videos = new Array();
        this.crewUsernames = new Array();
        this.token;
       
        this.errors = new Array();
        this.success = false;
       
        this.update_title = function()
        {
           
            this.title = $('#title').val();
           
        }
       
        this.update_genre = function()
        {
           
            this.genre = $('#genre').val();
           
        }
       
        this.update_company = function()
        {
           
            this.company = $('#company').val();
        }
       
        this.update_price = function()
        {
           
            this.price = $('#price').val();
           
        }
       
        this.update_url = function()
        {
           
            this.url = $('#url').val();
           
        }
       
        this.update_format = function()
        {
           
            this.format = $('#format').val();
           
        }
       
        this.update_languages = function()
        {
           
           
            this.languages = $('#languages').val();
           
        }
       
        this.update_system_requirements = function()
        {
           
            this.systemRequirements = $('#systemRequirements').val();
           
        }
       
        this.update_media_first = function()
        {
           
            this.mediaFirst = $('#mediaFirst').val();
           
        }
       
        this.add_crew = function(usernameSet)
        {
           
            this.crew.push(usernameSet);
           
        }
       
        this.send_product = function()
        {
           
            // this function sends the product to server side script
           
            var validator = new jValidator;
           
            validator.validate_text(this.title, 1, 'title too short.');
            validator.validate_select(this.genre, '', 'select genre.');
            validator.validate_text(this.company, 1, 'enter company.');
            validator.validate_text(this.url, 2, 'enter url to store/site');
            validator.validate_select(this.format, '', 'select format');
           
            this.errors = validator.return_errors();
           
            if(this.errors.length === 0)
            {
                // There were no errors, send basic product info to server side script post_product.php
               
                var productData = {"title":this.title, "genre":this.genre, "company":this.company, "url":this.url, "format":this.format, "operation":"post"};
           
                $.ajax({
                    method: "POST",
                    url: "../../php/scripts/post_product.php",
                    dataType:"html",
                    data:productData
                                       
                }).done(function(html){
                   
                    if(html != '')
                    {
                        // append token to form, and send it with images and videos.
                       
                      var form = document.forms['post-product-form'];
                      this.form_token(form, 'token', html);
                   
                      alert(html);
                   
                      if(this.send_crew())
                      {
                         
                          if(this.send_videos())
                          {
                             
                              this.success = true;
                              return this.success;
                             
                          }else{
                             
                               // could not send videos
                              return this.success;
                             
                          }
                         
                      }else{
                         
                           // could not send crew.
                          return this.success;
                         
                      }                     
                     
                     
                    }else{
                       
                        return this.success;
                       
                    }
                   
    
                });
                         
            }else{
               
                // there were errors in validation
               
                return this.success;
           
            }
       
            // end send product
           
        }
       
        this.send_crew = function()
        {
           
            // loop this to send every crew member.
           
            if(this.crewUsernames.length >= 1)
            {       
                for(i = 0; i < this.crewUsernames.length; i++)
                    {
                   
                            var crewDate = {"crewID":this.crew[i], "token":this.token};
                           
                            $.ajax({
                                    method: "POST",
                                    url: "../../php/scripts/post_product_crew.php",
                                    dataType:"html",
                                    data:crewData
                                                       
                                }).done(function(html){
                                   
                                    if(html != 'complete' && i == this.crewUsernames.length)
                                    {
                                        alert(html);
                                       
                                        return true;
                               
                                    }else{
                                       
                                        return false;
                                       
                                    }
                                   
                                });
                    }
       
            }else{
               
                return true;
               
            }
            // end send crew function
                 
        }
    
        // this function will send videos to post_product_videos.php
       
        this.send_videos = function()
        {
           
            // loop this to send every video.
             if(this.videos.length >= 1)
             {
                    for(i = 0; i < this.videos.length; i++)
                    {
                   
                            var crewDate = {"video":this.videos[i], "token":this.token};
                           
                            $.ajax({
                                    method: "POST",
                                    url: "../../php/scripts/post_product_videos.php",
                                    dataType:"html",
                                    data:videoData
                                                       
                                }).done(function(html){
                                   
                                    if(html != 'complete' && i == this.videos.length)
                                    {
                                      
                                        return true;
                                        alert(html);
                                       
                           
                                    }else{
                                       
                                        return false;
                                       
                                    }
                                   
                                });
                    }
             }else{
                
                 return true;
                
             }   
                    // end send crew function
           
        }
       
        this.form_token = function(formSet, keySet, valSet)
        {
            // This function will add product token to the form
            // This will allow for the server side script to update where token is in product table.
           
            var input = document.createElement('input');
            input.type = 'hidden';
            input.name = keySet;'name-as-seen-at-the-server';
            input.value = valSet;
            formSet.appendChild(input);
           
        }
       
        this.add_crew = function(usernameSet)
        {
           
            this.crewUsernames.push(usernameSet);
           
        }
       
        this.add_video = function (videoSet)
        {
           
            this.videos.push(videoSet);
           
        }
       
    }
    Code (JavaScript):
     
    Jeremy Benson, Aug 9, 2015 IP
  5. Jeremy Benson

    Jeremy Benson Well-Known Member

    Messages:
    364
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    123
    #5
    I had a jquery selector spelled wrong too in my update_url function..thanks again...

    This still isn't working right... There must be some error somewhere else... maybe the calls to send_crew and send_videos?

    function jProduct()
    {
       
        this.title;
        this.genre;
        this.company;
        this.price;
        this.ulr;
        this.format;
        this.languages;
        this.systemRequirements;
        this.mediaFirst;
        this.videos = new Array();
        this.crewUsernames = new Array();
        this.token;
       
        this.errors = new Array();
        this.success = false;
       
        this.update_title = function()
        {
           
            this.title = $('#title').val();
           
        }
       
        this.update_genre = function()
        {
           
            this.genre = $('#genre').val();
           
        }
       
        this.update_company = function()
        {
           
            this.company = $('#company').val();
        }
       
        this.update_price = function()
        {
           
            this.price = $('#price').val();
           
        }
       
        this.update_url = function()
        {
           
            this.url = $('#url').val();
           
        }
       
        this.update_format = function()
        {
           
            this.format = $('#format').val();
           
        }
       
        this.update_languages = function()
        {
           
           
            this.languages = $('#languages').val();
           
        }
       
        this.update_system_requirements = function()
        {
           
            this.systemRequirements = $('#systemRequirements').val();
           
        }
       
        this.update_media_first = function()
        {
           
            this.mediaFirst = $('#mediaFirst').val();
           
        }
       
        this.add_crew = function(usernameSet)
        {
           
            this.crew.push(usernameSet);
           
        }
       
        this.send_product = function()
        {
           
            // this function sends the product to server side script
           
            var validator = new jValidator;
           
           
            validator.validate_text(this.title, 1, 'title too short.');
            validator.validate_select(this.genre, '', 'select genre.');
            validator.validate_text(this.company, 1, 'enter company.');
            validator.validate_text(this.url, 2, 'enter url to store/site.');
            validator.validate_select(this.format, '', 'select format.');
       
            this.errors = validator.return_errors();
           
            if(this.errors.length === 0)
            {
                // There were no errors, send basic product info to server side script post_product.php
               
                var productData = {"title":this.title, "genre":this.genre, "company":this.company, "url":this.url, "format":this.format, "operation":"post"};
           
                $.ajax({
                    method: "POST",
                    url: "../../php/scripts/post_product.php",
                    dataType:"html",
                    data:productData
                                       
                }).done(function(html){
                   
                    if(html != '')
                    {
                        // append token to form, and send it with images and videos.
                       
                      var form = document.forms['post-product-form'];
                      this.form_token(form, 'token', html);
                   
                      alert(html);
                   
                      if(this.send_crew())
                      {
                         
                          if(this.send_videos())
                          {
                             
                              this.success = true;
                              return this.success;
                             
                          }else{
                             
                               // could not send videos
                              return this.success;
                             
                          }
                         
                      }else{
                         
                           // could not send crew.
                          return this.success;
                         
                      }                     
                     
                     
                    }else{
                       
                        return this.success;
                       
                    }
                   
    
                });
                         
            }else{
               
                // there were errors in validation
               
                return this.success;
           
            }
       
            // end send product
           
        }
       
        this.send_crew = function()
        {
           
            // loop this to send every crew member.
           
            if(this.crewUsernames.length >= 1)
            {       
                for(i = 0; i < this.crewUsernames.length; i++)
                    {
                   
                            var crewDate = {"crewID":this.crew[i], "token":this.token};
                           
                            $.ajax({
                                    method: "POST",
                                    url: "../../php/scripts/post_product_crew.php",
                                    dataType:"html",
                                    data:crewData
                                                       
                                }).done(function(html){
                                   
                                    if(html != 'complete' && i == this.crewUsernames.length)
                                    {
                                        alert(html);
                                       
                                        return true;
                               
                                    }else{
                                       
                                        return false;
                                       
                                    }
                                   
                                });
                    }
       
            }else{
               
                return true;
               
            }
            // end send crew function
                 
        }
    
        // this function will send videos to post_product_videos.php
       
        this.send_videos = function()
        {
           
            // loop this to send every video.
             if(this.videos.length >= 1)
             {
                    for(i = 0; i < this.videos.length; i++)
                    {
                   
                            var crewDate = {"video":this.videos[i], "token":this.token};
                           
                            $.ajax({
                                    method: "POST",
                                    url: "../../php/scripts/post_product_videos.php",
                                    dataType:"html",
                                    data:videoData
                                                       
                                }).done(function(html){
                                   
                                    if(html != 'complete' && i == this.videos.length)
                                    {
                                      
                                        return true;
                                        alert(html);
                                       
                           
                                    }else{
                                       
                                        return false;
                                       
                                    }
                                   
                                });
                    }
             }else{
                
                 return true;
                
             }   
                    // end send crew function
           
        }
       
        this.form_token = function(formSet, keySet, valSet)
        {
            // This function will add product token to the form
            // This will allow for the server side script to update where token is in product table.
           
            var input = document.createElement('input');
            input.type = 'hidden';
            input.name = keySet;'name-as-seen-at-the-server';
            input.value = valSet;
            formSet.appendChild(input);
           
        }
       
        this.add_crew = function(usernameSet)
        {
           
            this.crewUsernames.push(usernameSet);
           
        }
       
        this.add_video = function (videoSet)
        {
           
            this.videos.push(videoSet);
           
        }
       
    }
    Code (JavaScript):
     
    Last edited: Aug 9, 2015
    Jeremy Benson, Aug 9, 2015 IP
  6. Jeremy Benson

    Jeremy Benson Well-Known Member

    Messages:
    364
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    123
    #6
    On more post to see if this helps...

    I've commented everything out to my ajax call in send_product... everything worked until I let out this much code from the comments... I'm thinking there's an error in the way I'm using $.ajax.. This form will submit even tho I return false in the .done() function.. there has to be something wrong here..

    function jProduct()
    {
      
        this.title;
        this.genre;
        this.company;
        this.price;
        this.ulr;
        this.format;
        this.languages;
        this.systemRequirements;
        this.mediaFirst;
        this.videos = new Array();
        this.crewUsernames = new Array();
        this.token;
      
        this.errors = new Array();
        this.success = false;
      
        this.update_title = function()
        {
          
            this.title = $('#title').val();
          
        }
      
        this.update_genre = function()
        {
          
            this.genre = $('#genre').val();
          
        }
      
        this.update_company = function()
        {
          
            this.company = $('#company').val();
        }
      
        this.update_price = function()
        {
          
            this.price = $('#price').val();
          
        }
      
        this.update_url = function()
        {
          
            this.url = $('#url').val();
          
        }
      
        this.update_format = function()
        {
          
            this.format = $('#format').val();
          
        }
      
        this.update_languages = function()
        {
          
          
            this.languages = $('#languages').val();
          
        }
      
        this.update_system_requirements = function()
        {
          
            this.systemRequirements = $('#systemRequirements').val();
          
        }
      
        this.update_media_first = function()
        {
          
            this.mediaFirst = $('#mediaFirst').val();
          
        }
      
        this.add_crew = function(usernameSet)
        {
          
            this.crew.push(usernameSet);
          
        }
      
        this.send_product = function()
        {
          
            // this function sends the product to server side script
          
            var validator = new jValidator;
          
          
            validator.validate_text(this.title, 1, 'title too short.');
            validator.validate_select(this.genre, '', 'select genre.');
            validator.validate_text(this.company, 1, 'enter company.');
            validator.validate_text(this.url, 2, 'enter url to store/site.');
            validator.validate_select(this.format, '', 'select format.');
      
            this.errors = validator.return_errors();
          
            if(this.errors.length === 0)
            {
              
                // There were no errors, send basic product info to server side script post_product.php
              
                var productData = {"title":this.title, "genre":this.genre, "company":this.company, "url":this.url, "format":this.format, "operation":"post"};
              
                            
                $.ajax({
                    method: "POST",
                    url: "../../php/scripts/post_product.php",
                    dataType:"html",
                    data:productData
                                      
                }).done(function(html){
                    alert(html);
                    return false;
                   /*  
                    if(html != '')
                    {
                        // append token to form, and send it with images and videos.
                      
                      var form = document.forms['post-product-form'];
                      this.form_token(form, 'token', html);
                  
                      alert(html);
                  
                      if(this.send_crew())
                      {
                        
                          if(this.send_videos())
                          {
                            
                              this.success = true;
                              return this.success;
                            
                          }else{
                            
                               // could not send videos
                              return this.success;
                            
                          }
                        
                      }else{
                        
                           // could not send crew.
                          return this.success;
                        
                      }                    
                    
                    
                    }else{
                      
                        return this.success;
                      
                    }
                    */
    
                });
            
            
            }else{
              
                // there were errors in validation
              
                return this.success;
          
            }
      
            // end send product
          
        }
      
        this.send_crew = function()
        {
          
            // loop this to send every crew member.
          
            if(this.crewUsernames.length >= 1)
            {      
                for(i = 0; i < this.crewUsernames.length; i++)
                    {
                  
                            var crewDate = {"crewID":this.crew[i], "token":this.token};
                          
                            $.ajax({
                                    method: "POST",
                                    url: "../../php/scripts/post_product_crew.php",
                                    dataType:"html",
                                    data:crewData
                                                      
                                }).done(function(html){
                                  
                                    if(html != 'complete' && i == this.crewUsernames.length)
                                    {
                                        alert(html);
                                      
                                        return true;
                              
                                    }else{
                                      
                                        return false;
                                      
                                    }
                                  
                                });
                    }
      
            }else{
              
                return true;
              
            }
            // end send crew function
                
        }
    
        // this function will send videos to post_product_videos.php
      
        this.send_videos = function()
        {
          
            // loop this to send every video.
             if(this.videos.length >= 1)
             {
                    for(i = 0; i < this.videos.length; i++)
                    {
                  
                            var crewDate = {"video":this.videos[i], "token":this.token};
                          
                            $.ajax({
                                    method: "POST",
                                    url: "../../php/scripts/post_product_videos.php",
                                    dataType:"html",
                                    data:videoData
                                                      
                                }).done(function(html){
                                  
                                    if(html != 'complete' && i == this.videos.length)
                                    {
                                     
                                        return true;
                                        alert(html);
                                      
                          
                                    }else{
                                      
                                        return false;
                                      
                                    }
                                  
                                });
                    }
             }else{
               
                 return true;
               
             }  
                    // end send crew function
          
        }
      
        this.form_token = function(formSet, keySet, valSet)
        {
            // This function will add product token to the form
            // This will allow for the server side script to update where token is in product table.
          
            var input = document.createElement('input');
            input.type = 'hidden';
            input.name = keySet;'name-as-seen-at-the-server';
            input.value = valSet;
            formSet.appendChild(input);
          
        }
      
        this.add_crew = function(usernameSet)
        {
          
            this.crewUsernames.push(usernameSet);
          
        }
      
        this.add_video = function (videoSet)
        {
          
            this.videos.push(videoSet);
          
        }
      
    }
    Code (JavaScript):
     
    Jeremy Benson, Aug 9, 2015 IP
  7. iterationlabs

    iterationlabs Active Member

    Messages:
    174
    Likes Received:
    2
    Best Answers:
    1
    Trophy Points:
    63
    #7
    I think you have to call event.preventDefault() immediately in the submit handler if you don't want the form to submit.
     
    iterationlabs, Aug 9, 2015 IP
  8. Jeremy Benson

    Jeremy Benson Well-Known Member

    Messages:
    364
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    123
    #8
    No. It's not that I don't want the form to submit. I just don't want it to submit when there's an error. cleaned this up a lot. I found out that the return values for the functions have to be outside the .done() ajax functions. This is working pretty good now, but I'm finding a bug with my form_token functions. When that call is commented out inside send_product function the form works to the point where I'm debugging at... can you see if anything is wrong with this...

    The call
    this.form_token(form, 'token', this.token);
    Code (JavaScript):
    The function
    this.form_token = function(formSet, keySet, valSet)
        {
            // This function will add product token to the form
            // This will allow for the server side script to update at token
          
            var input = document.createElement('input');
            input.type = 'hidden';
            input.name = keySet;'variable name';
            input.value = valSet;
            formSet.appendChild(input);
          
        }
        
    Code (JavaScript):
    Thanks, Jb.
     
    Jeremy Benson, Aug 10, 2015 IP
  9. Jeremy Benson

    Jeremy Benson Well-Known Member

    Messages:
    364
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    123
    #9
    Ugh, in Firebug I'm getting the error..

    form_token not a function inside send_product.

    
    // When form_token is fixed of error not a function site must send whether or not crew and videos were added to php script.
    
    function jProduct()
    {
       
       this.title;
       this.genre;
       this.company;
       this.price;
       this.ulr;
       this.format;
       this.languages;
       this.systemRequirements;
       this.mediaFirst;
       this.videos = new Array();
       this.crewUsernames = new Array();
       this.token;
       
       this.hasCrew = false;
       this.hasVideos = false;
       
       this.errors = new Array();
       this.success = false;
       
       this.update_title = function()
       {
         
         this.title = $('#title').val();
         
       }
       
       this.update_genre = function()
       {
         
         this.genre = $('#genre').val();
         
       }
       
       this.update_company = function()
       {
         
         this.company = $('#company').val();
       }
       
       this.update_price = function()
       {
         
         this.price = $('#price').val();
         
       }
       
       this.update_url = function()
       {
         
         this.url = $('#url').val();
         
       }
       
       this.update_format = function()
       {
         
         this.format = $('#format').val();
         
       }
       
       this.update_languages = function()
       {
         
         
         this.languages = $('#languages').val();
         
       }
       
       this.update_system_requirements = function()
       {
         
         this.systemRequirements = $('#systemRequirements').val();
         
       }
       
       this.update_media_first = function()
       {
         
         this.mediaFirst = $('#mediaFirst').val();
         
       }
       
       this.add_crew = function(usernameSet)
       {
         
         this.crew.push(usernameSet);
         
       }
       
       this.send_product = function()
       {
         
         // this function sends the product to server side script
         
         var validator = new jValidator;
         
         
         validator.validate_text(this.title, 1, 'title too short.');
         validator.validate_select(this.genre, '', 'select genre.');
         validator.validate_text(this.company, 1, 'enter company.');
         validator.validate_text(this.url, 2, 'enter url to store/site.');
         validator.validate_select(this.format, '', 'select format.');
       
         this.errors = validator.return_errors();
           
         if(this.errors.length === 0)
         {
         
           
           // There were no errors, send basic product info to server side script post_product.php
         
           var productData = {"title":this.title, "genre":this.genre, "company":this.company, "url":this.url, "format":this.format, "operation":"post-js"};
      var ajaxWorked = true;
           $.ajax({
             method: "POST",
             url: "../../php/scripts/post_product.php",
             dataType:"html",
             data:productData
               
           }).done(function(html){
            // The return must be outside of the .done function.
             
             if(html != '')
             {
               // append token to form, and send it with images and videos.
               
              var form = document.forms['post-product-form'];
              this.token = html;
             
              this.form_token(form, 'token', this.token);
               
              alert(html);
              this.send_crew
              this.send_videos()
              this.success = true;     
           
             }
                     
           });
         
            return this.success;
         
         }else{
           
           // there were errors in validation
           
           return this.success;
         
         }
       
         // end send product
         
       }
       
       this.send_crew = function()
       {
         
         // loop this to send every crew member.
         
         if(this.crewUsernames.length >= 1)
         {     
           for(i = 0; i < this.crewUsernames.length; i++)
             {
             
                 var crewDate = {"crewID":this.crew[i], "token":this.token};
                 
                 $.ajax({
                     method: "POST",
                     url: "../../php/scripts/post_product_crew.php",
                     dataType:"html",
                     data:crewData
                               
                   }).done(function(html){
                     
                     if(html === 'complete' && i === this.crewUsernames.length)
                     {
                       alert('Crew Send: ' + html);
                       this.hasCrew = true;
                   
                     }
                     
                   });
                   
               // End loop to send crew
             }
           
           // End if crew not empty
         }
         
         // end send crew function     
       }
    
       // this function will send videos to post_product_videos.php
       
       this.send_videos = function()
       {
         // loop this to send every video.
          if(this.videos.length >= 1)
          {
             for(i = 0; i < this.videos.length; i++)
             {
             
                 var crewDate = {"video":this.videos[i], "token":this.token};
                 
                 $.ajax({
                     method: "POST",
                     url: "../../php/scripts/post_product_videos.php",
                     dataType:"html",
                     data:videoData
                               
                   }).done(function(html){
                     
                     if(html === 'complete' && i === this.videos.length)
                     {
                       
                       
                       alert('Video Send: ' + html);
                       this.hasVideos = true;
                     
                     }
                     
                 });
               // end loop to send videos
             }
           // End if videos not empty.
          }
         // end send videos function
       }
       
       this.form_token = function(formSet, keySet, valSet)
       {
         // This function will add product token to the form
         // This will allow for the server side script to update at token.
         /*
         var input = document.createElement('input');
         input.type = 'hidden';
         input.name = keySet;'variable name';
         input.value = valSet;
         formSet.appendChild(input);
         */
         return true;
       }
       
       this.add_crew = function(usernameSet)
       {
         
         this.crewUsernames.push(usernameSet);
         
       }
       
       this.add_video = function (videoSet)
       {
         
         this.videos.push(videoSet);
         
       }
       
       
       
    }
    
    Code (JavaScript):
     
    Last edited: Aug 10, 2015
    Jeremy Benson, Aug 10, 2015 IP
  10. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #10
    I'm seeing a number of little flubs that are likely tripping you up. I'll be nice and skip the usual ranting about the stupid malfing jQ crap.

    1) Since you aren't declaring any 'run-time' events, have you considered switching to object notation instead of the endless horde of "this"? Would clean up the code a bit.

    2) Ajax is async, your "current" state would never be set properly on your "return". jQuery does have the option to set "Async : false" as one of the parameters, but that can send the browser off to never-never land if the request takes too long; hence why using synchronous programming with AJAX is usually a bad idea. (That jQ probably shouldn't have added in the first place)

    3) You call it crew when defining it, but don't define crewUsernames... likewise you pass "crewdate" to the AJAX function but defined crewData... which is it? (NOT that I'd be wasting a variable on a one-time use data set)

    4) some consistency might help with code clarity, are you using camelCase or underscores, PICK ONE. (they're ALL object properties, so there's no reason for them to be different)

    5) "this" will not exist inside your event handler -- EVER.

    As such these:
    function(html){
            // The return must be outside of the .done function.
             
             if(html != '')
             {
               // append token to form, and send it with images and videos.
               
              var form = document.forms['post-product-form'];
              this.token = html;
             
              this.form_token(form, 'token', this.token);
               
              alert(html);
              this.send_crew
              this.send_videos()
              this.success = true;     
           
             }
                     
           });
         
            return this.success;
    Code (markup):
    Will be trying to access those properties on the EVENT, not your jProduct object. Those elements simply will not exist as scope is broken in event handlers.

    6) You don't need an if check for zero. "for (var i = 0; i < element.length; i++) {}" will NOT run the contents of the for loop if element.length is zero, as the condition is false. Condition is always run FIRST, making your "if(this.videos.length >= 1)" pointless code bloat unless you plan on having an ELSE at some point.

    7) Also not sure why you are looping a bunch of separate ajax sends if you've been adding them to the form like a good little doobie -- just let the form do it's job.

    8) You also seem to be pointlessly wrapping things to use jQuerys ****tarded val() method instead of just storing the element itself and pulling .value. A static property of an element will ALWAYS be faster than a method.... and cleaner. I'd make all those variables pointing at things simply be grabbed by document.getElementById and then just access .value directly instead of trying to use a "getter for nothing". Again part of how ... well, I was gonna skip ragging on the steaming pile of halfwit manure known as jQuery, that wasn't I?. GetElement(s)Byxxx, querySelector and jQ's wrapper for same are SLOW, that's why you want to try and use those once and only once to store a direct link.

    9) Since the AJAX call is likely going to happen more than once, it would be better to NOT pass anonymous functions to the AJAX handler.

    ----------------------

    Really that the function handler for the ajax method is async and does NOT have access to "this" is going to be a problem if jProduct is going to exist more than once on a page. The 'method' is going to need to go straight to jProduct. Are you doing "new jProduct" or is it only going to exist once?

    That said, a good scripted form validator should probably be hooking the form automatically using a trigger like classes or data attributes, NOT by directly indexing all the input/select/textarea by ID. You're brute forcing what should likely be automated. I could tell you a LOT more if I could see the actual form being processed. Same for the serializing the data -- the whole form should just be auto serialized, not manually tracked in separate sections as you are doing it. FIELDSETS for each of the sections could easily be leveraged as hooks for that.

    But again, I'd need to see the form and have a better grasp of what you are validating to weigh in better -- but that thing I said I'm not going to rant and rage over? It's stopping you from doing things efficiently/simply which is why when people call it simpler and easier I wonder what's in the flavor-aid.
     
    deathshadow, Aug 10, 2015 IP
  11. Jeremy Benson

    Jeremy Benson Well-Known Member

    Messages:
    364
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    123
    #11
    Hey, thanks DeathShadow, I was able to soak some of that in. I've been getting onto the whole 'this' context thing from some other pointers elsewhere. I set the context to this inside my $.ajax() parameters and now my functions and data members are being accessed. I've cleaned up the code quite a bit... The problem now is that send_product returns false, or something, unless I have an alert above the return statement. Check out the code below. It seems to fire all my member functions, but not send the form without the alert... not sure why...

    Also the form is kind of advanced, it's going to have searching features and what not, so sending the crew with the first call is not really possible that I know of, I'm not sure how many crew members are going to be added to any given item that's posted... it seem necessary to handle them separately.

    // When form_token is fixed of error not a function site must send whether or not crew and videos were added to php script.
    
    function jProduct()
    {
      
        this.title;
        this.genre;
        this.company;
        this.price;
        this.ulr;
        this.format;
        this.languages;
        this.systemRequirements;
        this.mediaFirst;
        this.videos = new Array();
        this.crewUsernames = new Array();
        this.token;
      
        this.hasCrew = false;
        this.hasVideos = false;
      
        this.errors = new Array();
          
        this.update_title = function()
        {
          
            this.title = $('#title').val();
          
        }
      
        this.update_genre = function()
        {
          
            this.genre = $('#genre').val();
          
        }
      
        this.update_company = function()
        {
          
            this.company = $('#company').val();
        }
      
        this.update_price = function()
        {
          
            this.price = $('#price').val();
          
        }
      
        this.update_url = function()
        {
          
            this.url = $('#url').val();
          
        }
      
        this.update_format = function()
        {
          
            this.format = $('#format').val();
          
        }
      
        this.update_languages = function()
        {
          
          
            this.languages = $('#languages').val();
          
        }
      
        this.update_system_requirements = function()
        {
          
            this.systemRequirements = $('#systemRequirements').val();
          
        }
      
        this.update_media_first = function()
        {
          
            this.mediaFirst = $('#mediaFirst').val();
          
        }
      
        this.add_crew = function(usernameSet)
        {
          
            this.crew.push(usernameSet);
          
        }
      
        this.send_product = function()
        {
          
            // this function sends the product to server side script
          
            var validator = new jValidator;
          
          
            validator.validate_text(this.title, 1, 'title too short.');
            validator.validate_select(this.genre, '', 'select genre.');
            validator.validate_text(this.company, 1, 'enter company.');
            validator.validate_text(this.url, 2, 'enter url to store/site.');
            validator.validate_select(this.format, '', 'select format.');
      
            this.errors = validator.return_errors();
          
            var productSent = false;
                      
            if(this.errors.length === 0)
            {
              
                // There were no errors, send basic product info to server side script post_product.php
          
                var productData = {"title":this.title, "genre":this.genre, "company":this.company, "url":this.url, "format":this.format, "operation":"post-js"};
              
                $.ajax({
                    context:this,
                    method: "POST",
                    url: "../../php/scripts/post_product.php",
                    dataType:"html",
                    data:productData
                                      
                }).done(function(html){
                    // The return must be outside of the .done function.
                  
                    if(html != '')
                    {
                  
                        // Set product sent to true, so send_product function returns true
                      productSent = true;
                    
                      // append token to form, and send it with images and videos.
                      
                      this.token = html;
                  
                      this.send_crew();
                      this.send_videos();
                  
                      var form = document.forms['post-product-form'];               
                      this.form_token(form, 'token', this.token);
              
                    }
                                
                });
              
              
            }else{
              
                // there were errors in validation
              
                return false;
          
            }
          
            alert('returning value');
            return productSent;
            // end send product
          
        }
      
        this.send_crew = function()
        {
          
            // loop this to send every crew member.
            if(this.crewUsernames.length >= 1)
            {      
              
                for(i = 0; i < this.crewUsernames.length; i++)
                    {
                  
                            var crewDate = {"crewID":this.crew[i], "token":this.token};
                          
                            $.ajax({
                                    context:this,
                                    method: "POST",
                                    url: "../../php/scripts/post_product_crew.php",
                                    dataType:"html",
                                    data:crewData
                                                      
                                }).done(function(html){
                                  
                                    if(html === 'complete' && i === this.crewUsernames.length)
                                    {
                                      
                                        this.hasCrew = true;
                              
                                    }
                                  
                                });
                              
                        // End loop to send crew
                    }
              
                // End if crew not empty
            }
          
            // end send crew function    
        }
    
        // this function will send videos to post_product_videos.php
      
        this.send_videos = function()
        {
          
            // loop this to send every video.
             if(this.videos.length >= 1)
             {
                    for(i = 0; i < this.videos.length; i++)
                    {
                  
                            var crewDate = {"video":this.videos[i], "token":this.token};
                          
                            $.ajax({
                                    context:this,
                                    method: "POST",
                                    url: "../../php/scripts/post_product_videos.php",
                                    dataType:"html",
                                    data:videoData
                                                      
                                }).done(function(html){
                                  
                                    if(html === 'complete' && i === this.videos.length)
                                    {
                                      
                                        this.hasVideos = true;
                                  
                                    }
                                  
                            });
                        // end loop to send videos
                    }
                // End if videos not empty.
             }
            // end send videos function
        }
      
        this.form_token = function(formSet, keySet, valSet)
        {
            // This function will add product token to the form
            // This will allow for the server side script to update at token.
            var input = document.createElement('input');
            input.type = 'hidden';
            input.name = keySet;'variable name';
            input.value = valSet;
            formSet.appendChild(input);
          
          
        }
      
        this.add_crew = function(usernameSet)
        {
          
            this.crewUsernames.push(usernameSet);
          
        }
      
        this.add_video = function (videoSet)
        {
          
            this.videos.push(videoSet);
          
        }
      
      
      
    }
    Code (JavaScript):
     
    Jeremy Benson, Aug 10, 2015 IP
  12. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #12
    The alert is giving the AJAX enough time to finish. Remember, AJAX is asynchronous -- it runs in the background and does NOT halt execution while it's running.

    If you do:

    var a = true;
    // do your AJAX call here
    a = false;

    A will most likely be set to false LONG before that AJAX call finishes. It is run in the background while Javascript plods on executing the code AFTER it. That's why it has a callback function which is run WHEN it is finished.

    I know jQuery has an option to make it synchronous, which would go something like this:

    $.ajax({
    	async : false,
    	context : this,
    	method: "POST",
    	url : "../../php/scripts/post_product.php",
    	dataType : "html",
    	data : productData
    }).done(function(html) {
    	// handle the result here
    });
    Code (markup):
    Which SHOULD SHOULD make that command wait until the AJAX is done before proceeding, but I REALLY recommend against doing that!

    As you are running three separate AJAX statements (for one data set, not sure why you'd do that...) I'd have a "done" counter that gets reset to however many requests are being done before you run any of those submits. I'd also be storing a handler to all three queries so if you start over you can cancel the existing requests. At the end of each function handler I'd decrement the counter, and if it hits zero then you call whatever it is you want done when all the requests are finished.

    You're pretty much diving headlong into event driven programming, which requires a VASTLY different mindset from normal "top down" execution programming. (laugh is THIS is the type of environment MVC is for, and why I laugh at the pathetically useless attempts to shoe-horn MVC into languages like PHP)

    JQ pissing on it doesn't help, as it hides a lot of the mechanism from you which can prevent learning how it REALLY works. That they can't seem to make up their mind on if you're passing things via an object or via methods sure as shine-ola doesn't help. It's another example of them trying so had to make it not work how it REALLY works, it's a miracle anyone can do anything useful with it.

    Admittedly there's a LOT of stuff people are doing on websites these days that as a developer I wouldn't even put there in the first place, and as a user just pisses me off as it usually has zero graceful degradation and is slow as molasses in February.
     
    Last edited: Aug 10, 2015
    deathshadow, Aug 10, 2015 IP
  13. Jeremy Benson

    Jeremy Benson Well-Known Member

    Messages:
    364
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    123
    #13
    I understand how asynchronous works. I just though .done() was the function that would fetch ajax up, and fire when the call was done... now I'm seeing that the code in the send_product() function is going to keep running and done is called whenever ajax is ready to call it, so got ya there..

    I don't have a clue how to work around this in the current context... I just want to fire the code as it reads... I'm used to code like that...

    This is gonna keep me stuck. I really need to know what to do if I'm going to do this without turning off async...

    I don't understand your counter method... also it's not three calls to ajax... send_crew() and send_videos() is going to call a script for each element in crewNames or videos arrays, one call for each video or name, because of the loop.. No one knows how many crew members a user is going to attach, so it has to be coded like that... I can't just send a json of unknown amount of names or videos.

    What do I need to learn here? even handlers, ajax event handlers, I really don't know..
     
    Jeremy Benson, Aug 10, 2015 IP
  14. Jeremy Benson

    Jeremy Benson Well-Known Member

    Messages:
    364
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    123
    #14
    Couldn't I just make the send_product() function return false, let it go through the loops, then send the form via form.submit()?
     
    Jeremy Benson, Aug 10, 2015 IP
  15. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #15
    Form.submit would be how I'd do it anyways -- regardless of how many videos or what have you are attached. If you make the name attribute on the ones for which you have no clue how many there would be end up something like video[] or crew[] it should on the PHP side automatically become an array inside $_POST... Then you wouldn't need AJAX at all -- just add the form elements then let the form do what it is supposed to do.

    Only reason to AJAX is if you don't want to leave the edit page -- and that's mostly done by the "pageloads are evil" paranoid nutters than for legitimate reasons in cases like this where you'd have so much stuff on the form. Client side validation BEFORE the submit I can understand when there's so much going on (though you STILL have to double-check it server side)... but when it comes time to just send it, let a form do what a form is supposed to do.

    Even if you did ajax it, I'd be serializing the entire form instead of trying to break it into pieces like you are. (at least that's what I THINK you are trying to do there, I'm not 100% clear on that without seeing the actual form).

    Actually, you have another problem -- so many ajax calls inside the FOR loop, that's just begging to fail or overtax the server. If those are actually just inputs you're adding dynamically, why not just have them be:

    <input type="text" name="crew[]" value="test1">
    <input type="text" name="crew[]" value="test2">
    <input type="text" name="crew[]" value="test3">
    <input type="text" name="crew[]" value="test4">

    When you let the form/submit do it's magic they would end up the equivalent of:

    $_POST['crew'] == ['test1', 'test2', 'test3', 'test4']

    Little detail of PHP and forms a lot of people don't learn -- then dive for the Javascript to try and implement. You know how I often rant and rave about "JavaScript for nothing" and "using JavaScript to do HTML or CSS' job"? Yeah, that. You want to add another slot to the form for someone to choose a file or add another name, just add it in the markup with name="something[]" and then let the form.submit do the submitting.

    It's why usually I'd just trap onsubmit and only cancel the submit if validation fails, no AJAX needed... unless the AJAX is verifying each and every single one, and that would be such a needlessly convoluted mess I'd not even go there in the first place.
     
    deathshadow, Aug 10, 2015 IP
  16. Jeremy Benson

    Jeremy Benson Well-Known Member

    Messages:
    364
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    123
    #16
    This way isn't going to work. I'm not using regular text fields... there's an interface for typing in a crew name, it searches the db.... found users show up in another div with their profile image, and what not... it's kind of mini advanced. A side question.

    "so many ajax calls inside the FOR loop, that's just begging to fail or overtax the server."

    Is there another solution to this? Inseam of sending the calls in a for loop could I send my entire array in a single go?

    Also, I really appreciate the help. It's doing good what I'm learning between forums... my first problem was learning callbacks, but it's hard... So I'm wondering if we can take this a step at a time here.... I've tried compartmentalizing my code... but I'm still getting issues. Inside this jProduct class I've created a function call do_ajax();

    The problem is I'm still running into issues. The axaj call in this function is STILL going to probably not complete before the function tries to return .done() html... so how can I fix this in this instance the proper way.

    this.ajax_run = function(methodSet, urlSet, dataTypeSet, dataSet)
        {
           
            var returnedData;
           
            $.ajax({
                    context:this,
                    method: methodSet,
                    url: urlSet,
                    dataType:dataTypeSet,
                    data:dataSet
                                       
                }).done(function(html){
                    // The return must be outside of the .done function.
                   
                    returnedData = html;
                                 
                });
           
                return returnedData;
           
        }
    Code (JavaScript):
    Do you know what I mean? I really need to learn to call ajax, and string callbacks... so I can send my crew array, send my videos array, and have everything working in order...
     
    Jeremy Benson, Aug 12, 2015 IP
  17. Jeremy Benson

    Jeremy Benson Well-Known Member

    Messages:
    364
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    123
    #17
    Ew, it's always something.. What am I missing in knowledge... Now that I've made this function, and thought about passing it a callback to call whatever function I want to pass in, I realize every call back is going to have its own parameters....

    Like say I wanted to call ajax_run and pass it my add token function to add the html, this would be fine.. but I also have a parameter to tell the add token function which form to add it to.. can you pass a callback with already loaded parameters? that wont fire until the end of a function...

    this.ajax_run = function(methodSet, urlSet, dataTypeSet, dataSet, callBackSet)
        {
      
                callBackSet = callBackSet || '';
          
                $.ajax({
                        context:this,
                        method: methodSet,
                        url: urlSet,
                        dataType:dataTypeSet,
                        data:dataSet
                                          
                    }).done(function(html, callBackSet){
                        // The return must be outside of the .done function.
                      
                        if(callBackSet != '')
                        {
                          
                            callBackSet(html);
                      
                        }        
                  
                });
              
        }
    Code (markup):
    There isn't enough parameters unless I modify my add token function

    this.form_token = function(formSet, keySet, valSet)
        {
            // This function will add product token to the form
            // This will allow for the server side script to update at token.
            var form = document.forms[formSet];
            var input = document.createElement('input');
            input.type = 'hidden';
            input.name = keySet;'variable name';
            input.value = valSet;
            formSet.appendChild(input);
          
          
        }
    Code (markup):
    I'm trying to learn to unbutcher my damn code, but this is not working.
     
    Jeremy Benson, Aug 12, 2015 IP
  18. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #18
    I REALLY think whatever it is you're doing (still not seeing the whole picture) you've ridiculously over-thought your solution.

    If users are entering "crew", why isn't that a input or other form element? Even if you're using some dumbass jacktard scripttardery to control it, the field itself should still be an input otherwise how the blazes are you expecting it to work?

    I'd really need to see the whole working page and/or a better understanding of what the data is and how users are entering it on your form -- since scripting without the markup is about as big a pile of gibberish as CSS without the markup... but really you seem to be screwing around with Ajax on something I don't think needs it... and certainly doesn't need it multiple times.
     
    deathshadow, Aug 15, 2015 IP