On Apr 22, 2008, at 2:36 PM, tlphipps wrote:
>
> I'm just guessing here, but I would think it would be related to your
> xhr.setRequestHeader line. I don't really understand why you need
> that anyway in this case. What happens if you completely remove the
> beforeSend: parameter from your $.ajax?
As a follow-up, I've got this fixed. First, the answer to the "why
beforeSend". It turns out that dataType: 'json' does the same thing. I
need the Accept header so Rails understands to render JSON. For non-
javascript aware browsers, the element that's being hijacked is an
anchor, so it decays to a normal http request and is dealt with
accordingly.
The old failing code hooked the click event of an anchor tag (angle
brackets replaced with curlies}:
{span id="task1"}
{a class="start start-timer" href="/a/link/to/somewhere/to/
start"}start{/a}
{/span}
The js called the function below as:
ajaxBind($('#task1 a'));
This hooked the click handler to the 'a' element, but the side effect
of the successful completion of the ajax call was to replace the
contents of the span. That meant that the DOM element that was grabbed
no longer was present. The element that replaced it, while it matched
the same selector, was not hooked up to the event handler.
The solution was to bind the event handler to the span only, then
drill down for the 'a' element in the ajaxBind function.
In case anyone else is hunting down a similar odd case.
:)
> On Apr 22, 3:51 pm, "s.ross" <[EMAIL PROTECTED]> wrote:
>> I'm having a strange problem using $.ajax. Better to illustrate with
>> the code:
>>
>> function ajaxBind(trigger) {
>> trigger.click(function(){
>> $.ajax({
>> type: "POST",
>> url: $(this).attr('href'),
>> data: {
>> 'authenticity_token': $
>> ('input[name=authenticity_token]').val()
>> },
>> dataType: 'json',
>> beforeSend: function(xhr) {
>> xhr.setRequestHeader("Accept", "application/json");
>> },
>> // json contains id and partial keys
>> success: function(json) {
>> $('#task' + json['task']).html(json['partial']);
>> }
>> });
>> return false;
>> });
>>
>> }
>>
>> When the DOM element "trigger" is clicked, a request to the server is
>> issued and the JSON response comes back. Hokey, dokey. The response
>> is
>> an html link. Something along the lines of:
>>
>> partial: "link in html that google would strip out anyway"
>>
>> This gets inserted using the html() function, as you see in the
>> success: part of the $.ajax call, and all is well until I click on
>> the
>> new link. Then the link is interpreted as a request to open a
>> document
>> of type application/json. Firebug doesn't reveal anything unusual
>> about the inserted HTML. Does anyone see the problem here?
>>
>> Thanks