Reputation: 3048
I am using ajax in my Rails app. In my application js i have
$('#request_name').on('focusout', function () {
var clientName = $(this).val();
$.ajax({
url: "/requests/autofill/"+clientName,
type: "GET",
contentType: 'text/javascript'
});
So i am sending ajax request to requests controller action autofill.
Autofill method:
def autofill
@client = Client.where("name=?",params[:name]).take
respond_to do |format|
format.js
format.html
end
end
alert("hello");
$('#request_mobile").val('hi there');
alert("hello");
$('#request_mobile").val('hi there');
But nothing happens, even alert is not launching. I don't know what i am doing wrong?
Upvotes: 0
Views: 296
Reputation: 4147
I don't think I understand entirely what's going wrong here, but I can see some ways to get closer to understanding the problem.
First of all, I believe it will be better for you to use $.get
instead of $.ajax
. It's just a bit less complicated to set.
Second thing - you actually don't need the contentType
param in the setup, 'cause it is not about the type of the return data, but the type of data you're sending in the request. The responce data type is set in the dataType
parameter.
Third thing, even if dataType
is set to script
, I'm not sure it will be executed, so the best way is to do it manually if you're 100% sure about your safety.
In the end, here's what should work.
$('#request_name').on('focusout', function () {
var clientName = $(this).val();
$.get("/requests/autofill/"+clientName, function(data) {
eval(data);
}
);
Upvotes: 1
Reputation: 1468
The problem is on your client-side. When it receives the Ajax response, it isn't executing it as javascript. It is executing it as text.
Add return false; after ajax
$('#request_name').on('focusout', function () {
var clientName = $(this).val();
$.ajax({
url: "/requests/autofill/"+clientName,
type: "GET",
contentType: 'text/javascript'
});
return false;
});
Upvotes: 0