no X-Requested-With: XMLHttpRequest in HTTP header when using $.ajax

A CJuiButton in CActiveForm will trigger a ajax call (inside pcap_frm_submit function) when clicked, and the CActiveForm is contained inside a CJuiDialog with ‘id’ = ‘pcap_frm_dlg’.

The code for the CJuiButton:




<div class="row buttons">

	<?php $this->widget('zii.widgets.jui.CJuiButton', array(

		'name'=>'pcap_frm_submit',

		'caption'=>'Generate',

		'onclick'=>'pcap_frm_submit',

	)); ?>

</div>



While the code ‘pcap_frm_submit’:




function pcap_frm_submit() {

	alert("pcap_frm_submit started");

	$.ajax({

		'url': '<?php echo $this->createUrl("GenPcap/ajaxCreate"); ?>',

		'context': $('#pcap_frm_dlg'),

		'type': 'POST',

		'dataType': 'json',

		'success': function(return_json) {

			alert('ajaxCreate return');

			if (return_json.status == 'not_yet_ok') {

				$(this).html(return_json.div);

			}

			else if (return_json.status == 'success') {

				$('<p>The pcap file is generated successfully</p>')

						.dialog({

					'buttons': {

							'ok': function() {alert('hi');$(this).dialog('close');}

					}

				});

			}

		},

	});

}



But when I view the http transaction in Firebug, there is no Requested-With: XMLHttpRequest in the request header. Every time I click the ‘pcap_frm_submit’ button, I am taken to a new page with scattered html. Why?

I finally figure out the problem.

A button inside a form by default will trigger a ‘submit’ event when clicked. This is why the http request header do not contains the ‘X-Requested-With: XMLHttpRequest’ line as it is just a normal ‘GET’ or ‘POST’. My solution is move the button outside the form, and include the following line in the ajax call:




$.ajax({

    ...

    data: $('#form_id').serializeArray(),

    ....

});



By the way, how to disable the ‘submitting’ characteristic of a button when it is inside a form?