Link to home
Start Free TrialLog in
Avatar of dale_abrams
dale_abrams

asked on

jQuery Javascript order of operations problem

I'm having trouble with jQuery and Javascript processing elements before they should be. Specifically, I have an HTML form that when the user hits the submit button, I need to intercept the submission and send the data via AJAX to a script that returns a JSON signature. Once I have that signature, then I need to populate one of the HTML form fields with the data and then submit the form via a normal HTML POST. What is happening is that the form is getting submitted with the signature field blank. So, its not waiting for the return statement to send the POST. Here is a scaled down example:

<html>
    <body>
       <script type="text/javascript" src="jquery.js" />
       <script type="text/javascript">
              $j = jQuery;

              function processTransaction(){
                $j.ajax({
	   	     type: "POST",
		     url: "get_signature.php",
		     data: { 
					'test': $j("#test").val(),
					'signature': $j("#signature").val()
				},
		     success: function( data ){
				var json = jQuery.parseJSON( data );
				if( json.error != undefined ) {
					$j("#result_message_error").append('<p>There was an error in the AJAX JSON response.</p>');
					return false;
				} else { 
					$j("#signature").val(json.success.signature);
					return true;
				}
			}
		});   
          }
       </script>
        <form name="form1" id="form1" action="www.someURL.com" method="POST" onSubmit="return processTransaction()">
            <input type="hidden" name="signature" value="" />
            <input type="text" name="test" value="" />
            <input type="submit" value="submit" />
        </form>
    </body>
</html>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Gary
Gary
Flag of Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of buttonMASTER
buttonMASTER

I think the ajax call and the form submit is happening at the same time. If you return false in your function to stop the form submit from the  button click and use jquery to submit the form on success it should work like you want it to.

              function processTransaction(){
                $j.ajax({
	   	     type: "POST",
		     url: "get_signature.php",
		     data: { 
					'test': $j("#test").val(),
					'signature': $j("#signature").val()
				},
		     success: function( data ){
				var json = jQuery.parseJSON( data );
				if( json.error != undefined ) {
					$j("#result_message_error").append('<p>There was an error in the AJAX JSON response.</p>');
				} else { 
					$j("#signature").val(json.success.signature);
					$j('#form1').submit();
				}
			}

		});  
          return false;
         }
 

Open in new window