Routing error in ajax on ruby on rails - javascript

I have this in my .html.erb code:
$.ajax({
url: "/timeMachineEdit",
data: {editTimeMachine: newArray},
type: 'POST',
success: function (res) {
if (res.result === 'ok') {
alert('Data saved');
} else {
alert('Save error');
}
},
error: function () {
alert('Save error.');
}
});
This in my datasets_controller.rb
def timeMachineEdit
#dataset = current_user.dataset
#dataset.machine_time = params[:editTimeMachine]
end
And in my routes.rb:
match "/timeMachineEdit", to: "datasets#timeMachineEdit"
But when is submited shows:
POST http://localhost:3000/timeMachineEdit 500 (Internal Server Error)
Where is the problem here?
is the routes in the ajax url or something else?

The problem is in your route definition....
try match "/timeMachineEdit", to: "datasets#timeMachineEdit"
I think, it will still not work because of the nature of format..In the datasets_controller try the following code...
def timeMachineEdit
#dataset = current_user.dataset
#dataset.machine_time = params[:editTimeMachine]
respond_to do |format|
format.js
end
end
Also change the dataType of your AJAX request to "script" in order to correctly match it with format.js else the format will be / which will select the first format that you will specify in the respond_to block..

Related

Not able to pass parameters through url in Ajax request using Rails

I'm trying to pass a parameter through a url in an Ajax request that's triggered by a confirmation dialogue. I'd like to fetch the value of that parameter in my Rails controller given a successful request but I haven't been able to do it.
I've tried so far the following code:
Here my Ajax request where I've been adding the param in the URL plus other params in data
function continueSave() {
var name = $('#leader_name').val();
var persisted_time = $('#leader_time').val();
$.ajax({
type: "POST",
url: "/leaderboards/1/?test=1",
data: { leader: { name: name, time: time } },
success: success
});
}
Here the dialogue-related JS
function nameAlert() {
return confirm("Name already exists. Would you like to continue?");
};
(function() {
if (nameAlert()) {
continueSave();
}
else {
//something else here
}
})();
Although the request successfully reaches the controller there's params[:test] is nil in the controller.
I've also tried to pass the test param in data, but it is not working either.
Would appreciate some help.
The relevant controller action (leaders_controller.rb)
def create
#leader = Leader.new(leader_params)
#leader.leaderboard_id = #leaderboard.id
#name_repeated = !#leaderboard.leaders.find_by(name: #leader.name).nil?
#check = params[:test]
if params[:test].nil? && #name_repeated == true
render :template => 'leaders/repeated_name.js.erb'
else
#leader.save
#rank = #leader.rank_in(#leaderboard)
respond_to do |format|
if #leader.save
format.html { redirect_to root_path }
format.js { }
else
end
end
end
end
Note:
1.- 'leaders/repeated_name.js.erb' contains the code for the Ajax request
2.- In routes Leader resource is nested within Leaderboard resource
Sorry guys I found the mistake. It was a dumb one.
I have shallow nested routes so that leaders is nested in leaderboards, therefore I was using the incorrect path for the request. It should be:
$.ajax({
type: "POST",
url: "/leaderboards/1/leaders?test=1",
data: { leader: { name: name, time: time } },
success: success
});
I should have caught that before sorry for wasting your time.
I'll post here - my comments are getting too long.
Try adding { type: 1} to your data and changing type to GET. Rails params contain both GET and POST data - you don't even have to change your controller.
function continueSave() {
var name = $('#leader_name').val();
var persisted_time = $('#leader_time').val();
$.ajax({
type: "GET",
url: "/leaderboards/1/",
data: { leader: { name: name, time: time }, test: 1 },
success: success
});
}

Ajax Bad Request 400 Rails

I'm getting bad request error 400 using Ajax on Rails.
When i submit my form I have a string to send as parameter from Jquery and i want to retrieve it from params[:assignee] so i can extract the string and save it through my controller.
My controller:
def create
#task = Task.new(task_params)
#task.user = current_user
username = params.permit[:assignee]
#task.assignee = username
#set_category
respond_to do |format|
if #task.save
format.html { redirect_to tasks_url, notice: 'Task was successfully created. '+task_params.inspect}
#format.html { redirect_to #task, notice: 'Task was successfully created.' }
format.json { render :show, status: :created, location: #task }
else
format.html { render :new }
format.json { render json: #task.errors, status: :unprocessable_entity }
end
end
end
def task_params
params.require(:task).permit(:owner, :value, :completed, :category, :date, :assignee)
end
And this is my JS:
$( "#new_task" ).submit(function() {
alert("form: "+assignee);
//event.preventDefault();
$.ajax({
url: "/tasks",
type: "POST",
data: {assignee},
dataType: "json",
success: function(data) {
alert('successfully');
},
error: function(xhr, textStatus, error) {
alert(xhr.statusText+""+textStatus+""+error);
}
});
});
assignee is an username selected in a jquery auto-complete form:
select: function(event, ui) {
var terms = split(this.value);
// remove the current input
terms.pop();
// add the selected item
terms.push(ui.item.value);
// add placeholder to get the comma-and-space at the end
terms.push("");
this.value = terms.join("");
assignee=this.value;
$('input[name=commit]').prop("disabled",false);
return false;
}
My root is "task/" where you can see saved tasks and a form to create a new one.
I searched a lot on the net and I tried them all. How can I do? Thanks so much
400 Bad Request - The server cannot or will not process the request due
to an apparent client error (e.g., malformed request syntax, too large
size, invalid request message framing, or deceptive request routing).
wiki
Change the ajax code to:
$.ajax({
url: "/tasks",
type: "POST",
dataType: "json",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'), // Optional
'Content-Type': 'application/json'
},
data: JSON.stringify({ assignee: assignee }),
success: function(data) {
alert('successfully');
},
error: function(xhr, textStatus, error) {
alert(xhr.statusText+""+textStatus+""+error);
}
});
{assignee} that's a not valid JSON object it should be {assignee: assignee}
Also you should add a valid headers, The 'Content-Type' and (X-CSRF-TOKEN optional)
Solved!
$( "#new_task" ).submit(function(event) {
alert("form: "+assignee);
var value = $('#new_task').find('input[name="task[value]"]').val();
event.preventDefault();
$.ajax({
url: "/tasks",
type: "post",
contentType: "application/json",
data: JSON.stringify({ assignee: assignee, value: value }),
success: function(data) {
alert('successfully');
},
error: function(xhr, textStatus, error) {
alert(xhr.statusText+" "+textStatus+" "+error);
}
});
});
event.preventDefault(); --> without this, the form is submitted twice.
var value = $('#new_task').find('input[name="task[value]"]').val(); --> without this, i could lose my form value because of "post tasks" that reminds to task#create

Uncaught SyntaxError: Unexpected token u

I am trying to get a JSON response from a get request. However, I am getting the following error: Uncaught SyntaxError: Unexpected token u. I know the rails route works because I do get the response loaded successfully in the Console.
The Ajax Response is supposed to start when the checkbox changes and is checked.
Why am I getting this error from the $.parseJSON?
Rails Controller
def providers
#providers = User.order("last_name ASC, first_name ASC, middle_name ASC").where("provider_flag = ? and inactive_flag = ? and del_flag = ?", true, false, false).select("id, CONCAT(IFNULL(last_name,''), ', ', IFNULL(first_name,''), IFNULL(middle_name,'')) AS full_name");
respond_to do |format|
format.json { render :json => { :providers => #providers.to_json}, :status => :ok }
# format.json { render :json => #providers.to_json }
end
end
Javascript
$('#provider_chk').change(function() {
if($(this).is(":checked")) {
$.ajax({
url: '<%= providers_schedule_index_path %>',
type: 'GET',
dataType: 'json',
data: {
authenticity_token: $('meta[name=csrf-token]').attr('content')
},
success: function(data) {
console.log('loaded successfully.');
var providers = $.parseJSON(data.responseText)['providers'];
providers_count = $(providers).size();
console.log(providers);
console.log(providers_count);
},
error: function(data) {
console.log("An error has occurred!")
}
});
} else {
$('#providers_results').empty();
}
});
JSON Response
providers: "[{"id":2,"full_name":"Test, User"}]"
Your JSON response should look more like this:
providers: [{"id":2,"full_name":"Test, User"}]
The outermost quotations marks aren't needed.
If you really need the outer quote marks, you need to escape the inner ones.
In $.ajax({}), add the property "async:false". parseJSON hasn't gotten that JSON yet - it's immediately trying to operate on undefined ("u") and throwing the error.
Remove to_json since you are already telling rails to return json
format.json { render :json => { :providers => #providers }, :status => :ok }

Cannot receive Rails response with Ajax

When I post from phonegap (with ajax, in javascript) something to my rails server, the post succeeds, but I have no response from my server, so finally it fails. I don't understand why I cannot get the response ..
For example, here is my sign up script (javascript with ajax):
$('#sign-up-button').click(function(e) {
var str = $("#signUpForm").serialize();
$(".error").remove();
e.preventDefault();
$.ajax({url: "http://localhost:3000/api/users.json",
type: "POST",
data: str,
success: function(result, status) {
alert('success');
$.mobile.changePage( "welcome.html", { transition: "slide"} );
},
error: function(result) {
alert('error');
}
});
});
and my code on Ruby on rails side:
# POST /users
# POST /users.json
def create
#user = User.new(params[:user])
respond_to do |format|
if #user.save
format.html { redirect_to #user, notice: 'User was successfully created.' }
format.json { render json: #user, status: :created }
else
format.html { render action: "new" }
format.json { render json: #user.errors, status: :unprocessable_entity }
end
end
end
In firebug, I have : the message 201 Created, the user is created (I can check it), but I have no response, so the message alert('error') appears ...
Thanks a lot for your advices!
If you are expecting an empty response such as a 201, you need to specify dataType: 'text' in your $.ajax options. What's happening right now is that jQuery is attempting to parse the response as JSON, and failing as there is no response to parse.
I've just stopped to try making it working with Firefox, and launched it in X-code.
It worked.
I was wondering if I needed to work on a server to obtain a response from a post, somebody knows if X code creates a server?

JavaScript AJAX & Rails Controller (back-and-forth)

I'm sending information back-and-forth between a Rails controller and a JS file.
I'm sending the form to the controller through JS (works)
$("#help-email-submit").ajaxSubmit({url: '/help/send_help_email', type: 'post' });
I'm able to catch the event in the controller (works)
def send_help_email
....
end
In the same JS file that sent the above request, how do I capture the JSON response (below)? (doesn't work)
def send_help_email
...
cst_str = #current_support_ticket.to_s
respond_to do |format|
format.json { render :json => cst_str }
end
end
In the JS file
var xmlhttp = new XMLHttpRequest();
alert(xmlhttp.responseText);
UPDATE
I noticed a JS error that is preventing the success: function from executing:
Error
TypeError: 'undefined' is not a function (evaluating '$("#help-email- form").ajaxSubmit({url: '/help/send_help_email', type: 'post', complete: handlerResponse })')
This is the line that is triggering the error
$("#help-email-form").ajaxSubmit({url: '/help/send_help_email', type: 'post', complete: handlerResponse })
This is complete block
var handlerResponse = function(data) {
alert(data);
};
$('#help-email-submit').live('click', function(e) {
$('#sender-email-wrapper').fadeOut('fast', function() {
$("#help-email-sent").fadeIn('slow');
});
$("#help-email-form").ajaxSubmit({url: '/help/send_help_email', type: 'post', complete: handlerResponse })
e.preventDefault();
});
According to ajaxSubmit documentation, it accepts the same options that the jQuery.ajax method. So, to get the response, you can pass the complete callback to the call:
var handleResponse = function(data) {
// Use response here
};
$("#help-email-submit").ajaxSubmit({url: '/help/send_help_email', type: 'post', complete: handleResponse });
Depending on the version of jQuery that you are using, you can also pass the callback through the complete method on the return value from jQuery.ajax:
$("#help-email-submit").ajaxSubmit({url: '/help/send_help_email', type: 'post'}).complete(function(data) {
// Use response here
});

Categories

Resources