views:

541

answers:

1

I'm having an issue that is driving me nuts, and according to everything i have seen and read online, it should be working fine.

I'm using jQuery with my Rails app instead of prototype and am using the ajaxForm plugin to submit some form data via ajax. The form data gets submitted fine, the corresponding controller action gets called fine, the proper respond_to block for the js type gets called fine.

The problem arises in the fact that the content of the *.js.erb file is returned to the client browser and not interpreted as javascript. Nothing actually happens with it. Yes, I have set the dataType: 'script' but it still doesnt work. I've also tried not using the ajaxForm plugin and manually using a $.post function on form submit, but still the same result.

for some code samples, here is my ajaxForm call:

$("#purchase-item-form").ajaxForm({ 
  dataType: 'script'
});

I also am properly setting the accepts header, this is working fine because my format.js block is the one being executed

jQuery.ajaxSetup({
  'beforeSend': function(xhr) { xhr.setRequestHeader("Accept", "text/javascript") }
});

in my action *.js.erb file all I have is an alert statement at the moment to aid in debugging the issue until I can figure it out:

alert("action processed successfully");

This just doesnt work in firefox or safari. If I look in the firebug console, I can see the alert statement being returned as a response from the ajax call, its just not being evaluated by the client as javascript.

FYI, I'm running on Rails 2.3.4 and jQuery 1.3.2 if that matters

+1  A: 

I ran into the EXACT same problem. You have to manually eval the code that is returned. I can't remember exactly why it doesn't get evaled, but I was using the same plugins as you and this fixed it.

Edit 1: Readding article since it helped solve the problem.

Edit 2: Try the following:

$("#purchase-item-form").ajaxForm({ 
  dataType: 'script',
  success: evalResponse
});

function evalResponse(responseText, statusText) {
  eval(responseText);
}

Look here for a bit more information.

Topher Fangio
can you elaborate a bit more on what you mean? eval it how?
cpjolicoeur
thanks for the link. I added the dataType option to the global $.ajaxSetup and it seems to have fixed the issue.strange that that inline dataType option didnt make a difference, but thanks for the help.
cpjolicoeur
Glad you figured out what was wrong even though I kept changing my answer =P
Topher Fangio
Can we get some clarity here... is the eval enough? +1, in all cases.
Yar
so, I didnt even try the evalResponse method from Topher's code above.I simply added the dataType: "script" option to my $.ajaxSetup() global method.I don't know why but this made it works. For whatever reason, the inline dataType: "script" option in the ajaxForm function didn't get recognized by the browser
cpjolicoeur