We help IT Professionals succeed at work.
Get Started

jQuery Javascript order of operations problem

dale_abrams
dale_abrams asked
on
969 Views
Last Modified: 2014-05-20
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

Comment
Watch Question
CERTIFIED EXPERT
Expert of the Year 2014
Top Expert 2014
Commented:
This problem has been solved!
Unlock 1 Answer and 2 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE