Robert
Robert

Reputation: 925

Submitting Ajax Form From Ajax Loaded Page

I have a page which is generated within ajax.

On that page there is a 2 forms, #form1 and #form2.

I have the jquery the code for submitting the form is as follows:

jQuery("#form1").on('submit', function(e){

        e.preventDefault();

        var sendurl = '/xxx/xxx/xxx/xxx.php';

        var varable1 = jQuery('#infor1').val();
        var varable2 = jQuery('#infor2').val();
        var varable3 = jQuery('#infor3').val();
        var varable4 = jQuery('#infor4').val();
        var varable5 = jQuery('#infor5').val();
        var varable6 = jQuery('#infor6').val();
        var varable7 = jQuery('#infor7').val();

        jQuery.ajax({url: sendurl + '?varable1=varable1' + 'varable2=' + varable2 + 'varable3=' + varable3 + 'varable4=' + varable4 + 'varable5=' + varable5 + 'varable6=' + varable6 + 'varable7=' + varable7}).done(function(data) {

            if(data === 'fail'){
                jQuery('.error').html('Something went wrong with your form request please try again!').slideDown(500).delay(4000).slideUp(500);
                jQuery('input[type=submit]', jQuery("#submittions")).removeAttr('disabled');
                return false;
            }

            if(data !== 'fail'){
                jQuery('#showresults').slideUp(600);
                jQuery('.show-complete-detail').html(data);
                jQuery('#applicationcomplete').delay(1500).slideDown(400);
            }

        }); 
});

I have also tried the:

jQuery().submit();

That does not work either.

I am assuming that because the page is loaded in using ajax that it can not find the form with the id of form1?

Has anyone any ideas on where I am going wrong.

Thanks :)

Upvotes: 0

Views: 102

Answers (3)

Norlihazmey Ghazali
Norlihazmey Ghazali

Reputation: 9060

For dynamically loaded content, use event delegation like so :

// replacing document with top level parent
// something like parent container
jQuery(document).on('submit','#form1', function(e){ ... }

And one more thing, data passed from ajax url like that is bad idea, you should use data properties to send data, see below example :

$.ajax({
     type : 'POST', // or GET
     url : 'your url here',
     data : {
        var1 : variable1
         .......
     },
    .... Another properties...
 }).done(data){...});

Upvotes: 1

HEMANT SUMAN
HEMANT SUMAN

Reputation: 488

bind with document

jQuery(document).on('submit','#form1', function(e){


});

use the console.log for sendurl

console.log(sendurl)

Upvotes: 0

Mark
Mark

Reputation: 4873

Delegate the event to a higher level dom element that wasnt added dynamically.

ie)

$("#FormContainer").on("#form1", "submit",function(){
    //   Do Form tuff....
});
$("#FormContainer").on("#form", "submit",function(){
   //   Do Form tuff....
});

Upvotes: 0

Related Questions