Joppo
Joppo

Reputation: 729

jquery submit function does not work

I'm developing a webpage which creates a form with various select tags dynamically. Unfortenatley the jquery submit function passes incorrect information to the php file (form_submit.php) that must process this information; the (netbeans 7.4) debugger always shows default (not selected) values in $_POST within the php file instead of the selected values . The even stranger part: when I copy (in the code below) the console output with the serialised formdata straight into the following ajaxcode (see code), the php debugger shows the correct -selected values within the $_POST array..(?)

The resulting form is quite substantial. The only theoretical cause I can think of is that therefore the execution of 'var dataAjax = $( this ).serialize();' takes time and is not finished when the following ajax call starts...(??)

The code:

$("#myForm").submit(function(event){
event.preventDefault();

var dataAjax = $( this ).serialize(); //does not work, but when copying the string from the console in line below it does work.
console.log('SUBMITTED FORM: '+ dataAjax  );
//next line is only used as a test
//var dataAjax = 'agreementapproval0=SolarX_10&selected_emeterproductid0=SolarX_10_1_1&selected_eproductid0=SolarX_10_2_4&selected_emeterproductid1=NOSELECTION&selected_emeterproductid2=NOSELECTION&selected_eproductid1=NOSELECTION&selected_eproductid2=NOSELECTION&form_token=30688e467ee88167805ad0f330809d74';


    $.ajax({
        type: "POST",
        url: "form_submit.php",
        data: dataAjax, 
        dataType: "json",
        async: true,

        success: function(msg){
        if(msg.statusgeneral == 'success'){

        }
        else
        {

        }//else
        }, //succes: function   
        error: function(){

    $("#errorbox").html("There was an error submitting the form. Please try again.");
        }
    });//.ajax

//make sure the form doesn't post
//return false; //depreciated

//} //if(form.valid()

});//$("#myForm").submit()


<form id="myForm" name="myForm" action="" method="post">    
    <div id="wrapper"></div> <!--anchor point for adding set of product form fields -->  
    <input type="hidden" name="form_token" value="<?php echo $form_token; ?>" />
    <input type="submit" name="submitForm" value="Confirm">
</form>

Upvotes: 0

Views: 199

Answers (1)

mdolbin
mdolbin

Reputation: 936

It works fine http://jsfiddle.net/a9DN4/

You might have been trying to hook form before it have been created, try to wrap your code with

$( document ).ready(function() {
  // Handler for .ready() called.
});

PS and move event.preventDefault(); to the 1st string of your function, as Kevin says.

Upvotes: 1

Related Questions