Yii And Jquery Ajax Csrf Issue

Hello:

Been using Yii for the past few weeks now and so far I love it. But I’m running into a problem making an Ajax call to a web service I’ve set up in YII from jQuery. I’m using the great FullCalendar component and I’m trying to set up a callback so that my calendar will query the controller for the data it needs.

But each time I’m getting a The CSRF token could not be verified. response.

Here’s what the snippets of code look like (header and response follow):




<script type='text/javascript'>

	$(document).ready(function() {

 		var mouseXPos;

        var mouseYPos;

        var csrfToken = <?php echo "'".Yii::app()->request->csrfToken."'"?>;

		

        $(document).mousemove(function (e) {

            mouseXPos = e.pageX;

            mouseYPos = e.pageY;

        });

        

        $("body").bind("ajaxSend", function(elm, xhr, s){

		   if (s.type == "POST") {

			  	xhr.setRequestHeader('X-CSRF-Token', csrfToken);

			  	xhr.setRequestHeader('YII_CSRF_TOKEN', csrfToken);

		   }

		});


 

		$('#calendar').fullCalendar({

  		  theme: true,

  		  defaultView: 'agendaWeek',

  		  firstHour: 8,

		  header: {

			left: 'prev,next today',

			center: 'title',

			right: 'month,agendaWeek,agendaDay',						

		  },

		  editable: false,

		  

		  eventClick: function(calEvent,jsEvent,view){

			

			var htmlText = calEvent.title+'<p>'+

						'Instructor: '+calEvent.instructor1;


			$("#calendardialog").dialog("option", { position: [mouseXPos+5, (mouseYPos+5)-$(document).scrollTop()] });											  

		  	$("#calendardialog").dialog("option", "title", calEvent.school);

		  	$("#calendardialog").html(htmlText).dialog();

		  	$("#calendardialog").dialog("open");


			// change the border color just for fun

		  },

		  

		  events: function(start,end,callback){		  

		  

		  	var soapMessage = 

						'\x3C?xml version=\"1.0\" encoding=\"UTF-8\"?\x3E\n\x3Cdefinitions xmlns=\"http:\x2F\x2Fschemas.xmlsoap.org\x2Fwsdl\x2F\" xmlns:tns=\"urn:SchoolControllerwsdl\" xmlns:soap=\"http:\x2F\x2Fschemas.xmlsoap.org\x2Fwsdl\x2Fsoap\x2F\" xmlns:xsd=\"http:\x2F\x2Fwww.w3.org\x2F2001\x2FXMLSchema\" xmlns:wsdl=\"http:\x2F\x2Fschemas.xmlsoap.org\x2Fwsdl\x2F\" xmlns:soap-enc=\"http:\x2F\x2Fschemas.xmlsoap.org\x2Fsoap\x2Fencoding\x2F\" name=\"SchoolController\" targetNamespace=\"urn:SchoolControllerwsdl\"\x3E\n  \x3Cwsdl:message name=\"getScheduleRequest\"\x3E\n    \x3Cwsdl:part name=\"schoolId\" type=\"xsd:integer\"\x2F\x3E\n    \x3Cwsdl:part name=\"startDate\" type=\"xsd:string\"\x2F\x3E\n    \x3Cwsdl:part name=\"endDate\" type=\"xsd:string\"\x2F\x3E\n  \x3C\x2Fwsdl:message\x3E\n  \x3Cwsdl:message name=\"getScheduleResponse\"\x3E\n    \x3Cwsdl:part name=\"return\" type=\"xsd:string\"\x2F\x3E\n  \x3C\x2Fwsdl:message\x3E\n  \x3Cwsdl:portType name=\"SchoolControllerPortType\"\x3E\n    \x3Cwsdl:operation name=\"getSchedule\"\x3E\n      \x3Cwsdl:documentation\x3EReturns the array of calendar events -- accessible as a web service\x3C\x2Fwsdl:documentation\x3E\n      \x3Cwsdl:input message=\"tns:getScheduleRequest\"\x2F\x3E\n      \x3Cwsdl:output message=\"tns:getScheduleResponse\"\x2F\x3E\n    \x3C\x2Fwsdl:operation\x3E\n  \x3C\x2Fwsdl:portType\x3E\n  \x3Cwsdl:binding name=\"SchoolControllerBinding\" type=\"tns:SchoolControllerPortType\"\x3E\n    \x3Csoap:binding style=\"rpc\" transport=\"http:\x2F\x2Fschemas.xmlsoap.org\x2Fsoap\x2Fhttp\"\x2F\x3E\n    \x3Cwsdl:operation name=\"getSchedule\"\x3E\n      \x3Csoap:operation soapAction=\"urn:SchoolControllerwsdl#getSchedule\" style=\"rpc\"\x2F\x3E\n      \x3Cwsdl:input\x3E\n        \x3Csoap:body use=\"encoded\" namespace=\"urn:SchoolControllerwsdl\" encodingStyle=\"http:\x2F\x2Fschemas.xmlsoap.org\x2Fsoap\x2Fencoding\x2F\"\x2F\x3E\n      \x3C\x2Fwsdl:input\x3E\n      \x3Cwsdl:output\x3E\n        \x3Csoap:body use=\"encoded\" namespace=\"urn:SchoolControllerwsdl\" encodingStyle=\"http:\x2F\x2Fschemas.xmlsoap.org\x2Fsoap\x2Fencoding\x2F\"\x2F\x3E\n      \x3C\x2Fwsdl:output\x3E\n    \x3C\x2Fwsdl:operation\x3E\n  \x3C\x2Fwsdl:binding\x3E\n  \x3Cwsdl:service name=\"SchoolControllerService\"\x3E\n    \x3Cwsdl:port name=\"SchoolControllerPort\" binding=\"tns:SchoolControllerBinding\"\x3E\n      \x3Csoap:address location=\"http:\x2F\x2Flocalhost:8888\x2Fparker-anderson\x2Findex.php\x2Fschool\x2Fschedule?ws=1\"\x2F\x3E\n    \x3C\x2Fwsdl:port\x3E\n  \x3C\x2Fwsdl:service\x3E\n\x3C\x2Fdefinitions\x3E';

		  			  	

		  	$.ajax({

		  		type: 'POST',

		  		data: soapMessage,

		  		dataType: 'json',		  	

		  		success: function(doc){

		  			var events = [];

		  			alert(doc);

					$(doc).find('event').each(function() {

						events.push({

							title: $(this).attr('title'),

							start: $(this).attr('start') // will be parsed

						});

					});

					callback(events);

		  		},

		  		error: function(a,b,c){

		  			alert(a + "\n"  + b + "\n" + c);

		  		}

		  	});

		  }


		});

				

	});

	

</script>



Here’s what the relevant parts of header looks like:




Accept:application/json, text/javascript, */*; q=0.01

Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3

Accept-Encoding:gzip,deflate,sdch

Accept-Language:en-US,en;q=0.8

Cache-Control:max-age=0

Connection:keep-alive

Content-Length:2031

Content-Type:application/x-www-form-urlencoded; charset=UTF-8

Cookie:YII_CSRF_TOKEN=89aad1cf0ea57fa02fba87414245aeee8af3037es%3A40%3A%2212ab16441b7acc7e43db74fb691262ffda9b0858%22%3B; PHPSESSID=f9d42d970d195abc9aa9d2affe6d7e5f; SessPA=a5d495b0b313f5428d2df85ff354c5b0; role=0401957b6493aaa382a2c05ffdbc6d7fab09e2e5s%3A5%3A%22admin%22%3B; SQLiteManager_currentLangue=2

Host:localhost:8888

Origin:http://localhost:8888

Referer:http://localhost:8888/pe/school

User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.65 Safari/537.31

X-CSRF-Token:12ab16441b7acc7e43db74fb691262ffda9b0858

X-Requested-With:XMLHttpRequest

YII_CSRF_TOKEN:12ab16441b7acc7e43db74fb691262ffda9b0858



But every time I’m getting the "The CSRF token could not be verified." response.

If someone could help with this I’d really appreciate it.

No need to bind csrf token in header. Just send it as ajax data as


$.ajax({

                                type: 'POST',

                                data:{YII_CSRF_TOKEN:csrfToken ,soapMessage:soapMessage},

Hi,

What if ajax is located in separate js file? Maybe to pass params and use them?