AjaxLink : Browser is simply printing the Json output

I’m using ajaxLink() to create links, which, when clicked, handle various actions.

Most of the time, the links work properly. However, some of the time, when clicked, the links simply display the Json array rather than interpet it. It’s as if the MIME type is not set on certain occasions. Here’s the code:




// Generate the ajaxLink:

$url = '/handleClick.php';

echo CHtml::ajaxLink($linkText,

		      $url,

		      // ajax options

		      array(

			    'type' => 'GET',

			    'dataType' => 'json',

			    'error' => 'function(data)   { alert("error!");  }',

	                    'success' => 'function(data) { alert("success"); }',

                      ),

		      // htmloptions

		      array(

			    'id' => 'handleClick',

			    'href' => $url,

			    )

		      );


// Here's the code that handles the link being clicked (i.e. handleClick.php)

$data = array();

$data['foo'] = 'bar';

echo json_encode($data);


// Most of the time, when the ajaxLink generated as shown above gets clicked,

// the handler does its job, and all is well.

// But SOMETIMES, the browser LITERALLY prints the json encoded by handleClick.php, and what I see

// in my browser is what's shown below:

{"foo":"bar"}




Has anyone run into this before? I thought this might have something to do with the MIME type being ignored,

but why is not ignored in all cases? And how do I explicitly set the MIME type for links generated using CHtml::ajaxLink?

Thanks in advance!

Emily

Only an idea, didn’t look closer, but this looks strange to me:


'href' => $url,

You should remove it, this is not required and actually wrong (you set the "standard", non-ajax link target to an ajax action).

Strange. I tried your code and it works Ok. In what cases does your code display the Json array?

I too tried your code and could not get the code to display…

but as @Mike pointed out the href=$url is the problem…

Seems that at some times when you click the link your browser does not make an AJAX call to handleClick.php but simply redirects to it, because by setting the href you are making this HTML source


<a id="handleClick" href="/handleClick.php">AJAX LINK</a>

without setting the href option you make this HTML source


<a id="handleClick" href="#">AJAX LINK</a>

This way if AJAX is not called (for some strange reason), nothing will happen…

Thanks for the replies. Removed the "href" attribute and all works dandy.

Best,

Emily