Dynamically creating a form in jQuery and submitting it using JSON

I am trying to dynamically create a campaignmonitor newsletter subscription inside my XSLT code.

<script type="text/javascript"><xsl:text disable-output-escaping="yes"><![CDATA[ $(function() { $('#submit').click(function() { if ($('#nlapproved').attr('checked')) { newsletter(); } }); function newsletter() { $form = $('<form action="http://mydomain.createsend.com/t/j/s/jtes/" method="post" id="subForm" />'); $form.append('<input type="hidden" name="cm-name" id="hidName" />'); $form.append('<input type="hidden" name="cm-jtes-jtes" id="hidEmail" />'); $form.append('<input type="hidden" name="cm-fo-pikty" id="hidPrivateBusiness" />'); $form .find("#hidName") .val(']]></xsl:text><xsl:value-of select="$context//checkoutinformation/info[key='name']/value" disable-output-escaping="yes"/><xsl:text disable-output-escaping="yes"><![CDATA['); $form .find("#hidEmail") .val(']]></xsl:text><xsl:value-of select="$context//checkoutinformation/info[key='email']/value" disable-output-escaping="yes"/><xsl:text disable-output-escaping="yes"><![CDATA['); $form .find("#hidPrivateBusiness") .val(']]></xsl:text><xsl:value-of select="$acctype"/><xsl:text disable-output-escaping="yes"><![CDATA['); $.getJSON( $($form).get(0).action + "?callback=?", $($form).serialize(), function (data) { if (data.Status === 400) { alert("Error: " + data.Message); } else { // 200 alert("Success: " + data.Message); } } ); } }); ]]></xsl:text></script> 

Everything works fine until I name the getJSON method. After that, nothing works. I cannot find JavaScript errors in the console of the Mozilla console. And I checked if the form was created correctly. alert($('<div>').append(($form).clone()).html()); displays the correct result.

 <form action="http://mydomain.createsend.com/t/j/s/jtes/" method="post" id="subForm"><input value="552" name="cm-name" id="hidName" type="hidden"><input value=" aks@mydomain.com " name="cm-jtes-jtes" id="hidEmail" type="hidden"><input value="268278" name="cm-fo-pikty" id="hidPrivateBusiness" type="hidden"></form> 
+4
source share
1 answer

In the jQuery API documentation , execute the callback function:

success (data, textStatus, jqXHR) A callback function that is executed if the request is completed.

Perhaps adding a crash listener will help:

 $.getJSON( $($form).get(0).action + "?callback=?", $($form).serialize(), function (data) { if (data.Status === 400) { alert("Error: " + data.Message); } else { // 200 alert("Success: " + data.Message); } } ).error(function(data) { alert('have error http: ' + data); }).complete(function(data){ alert('have complete: ' + data); }); 

Update:

May also have something to do with JSON error. From the API document:

Important. Starting with jQuery 1.4, if the JSON file contains a syntax error, the request usually fails.

Switching to a call to $.get(...) can test this theory.

+1
source

All Articles