Ajax Bad Request 400 Rails - javascript

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

Related

this.state.search_results.map is not a function but it's an array

render: function(){
console.log(this.state.search_results);
var renderedSearchResults = this.state.search_results.map((result) => {
The console.log prints:
[{"id": "testGroup2"}, {"id": "testGroup77777"}, {"id": "testGroup1"}, {"id": "testGroup3"}]
The data is obtained through:
$.ajax({
url: this.props.routes.search,
contentType: 'application/json',
type: 'POST',
data: JSON.stringify(searchObj),
success: function(data){
console.log(data);
this.setState({search_results:data});
}.bind(this),
error: function(xhr, status,err){
console.error("/api/response", status, err.toString());
}.bind(this)
});```
Through:
def post(self):
"""
Makes a request to search for a specific
searchtype: Group
searchstring: ""
requestedfields: []
"""
search_type = self.json_data.get('searchtype', 'Group')
search_string = self.json_data.get('searchstring', '')
requestedfields = self.json_data.get('requestedfields', ['id'])
search_model = {
'Group': Group(),
'User': User()
}[search_type]
search_fields = {
'Group': ['id', 'tags'],
'User': ['username']
}[search_type]
# check if requestedfields contains valid fields
for field in requestedfields:
if field == 'id':
continue
value = search_model.default().get(field, None)
if value is None:
return self.set_status(400, "Model {0} does not have requested field {1}".format(search_type, field))
try:
search_results = search_model.search_items(search_string, search_fields, requestedfields)
except err:
return self.set_status(400, "Something went wrong")
self.set_status(200, "Success")
return self.write(tornado.escape.json_encode(search_results))
I'm really confused as to how this.state.search_results isn't an array that I can iterate through, can anyone see what's going on?
I've tried using console.log(Object.prototype.toString.call(data)); inside the success function and I get:
[object String]
Try to set json data type in an explicit way, while doing your ajax request:
$.ajax({
dataType: 'json',
//...
});
Most probably Intelligent Guess that is used to detect data type by jQuery, is giving wrong result.
Found my answer, didn't set dataType: "json" in my ajax request.

Rails ajax Dynamic select

Seems that the code is correct!
so, someone could spare any information why the second(subcategories) partial did not update? Thank's
I put on js:
$(document).ready(function() {
return $(document).on('click', "input[type='radio'][name='product[gender_id]']", function(evt) {
return $.ajax('update_category_select', {
type: 'GET',
dataType: 'script',
data: {
gender_id: $("input[type='radio'][name='product[gender_id]']:checked").val()
},
error: function(jqXHR, textStatus, errorThrown) {
return console.log("AJAX Error: " + textStatus);
},
success: function(data, textStatus, jqXHR) {
return console.log("Dynamic state select OK!");
}
});
});
return $(document).on('change', '#categories_select', function(evt) {
return $.ajax('update_subcategory_select', {
type: 'GET',
dataType: 'script',
data: {
category_id: $("#categories_select option:selected").val()
},
error: function(jqXHR, textStatus, errorThrown) {
return console.log("AJAX Error: " + textStatus);
},
success: function(data, textStatus, jqXHR) {
return console.log("Dynamic state select OK!");
}
});
});
});
First Partial:
$("#categories_select").empty().append("<%= escape_javascript(render(:partial => #categories)) %>")
If the firt partial is updated update the second partial
Second partial:
$("#subcategories_select").empty().append("<%= escape_javascript(render(:partial => #subcategories)) %>")
Products Controller
#catagories = Category.where("gender_id = ?", params[:gender_id])
respond_to do |format|
format.js
end
end
def update_subcategory_select
#subcategories = Subcategory.where("category_id = ?", params[:category_id])
respond_to do |format|
format.js
end
end
The return is used inside a function to return a value/expression and the following sentences are not executed.
In your javascript do you have something like:
function(){ //Document ready
return 1; //Here you on click
return 2; //Here you on change
}
So return 2 is never called. In your case, the event handler for 'change' is never attached so subcategories are not updated.
Just remove all return in your javascript code.

Undefined append after an ajax post in rubyonrails

I'm trying to append some information after posting with ajax
this is are my routes:
match 'api/people/', to: 'people#people_get_all', via: [:get]
match 'api/people/:id', to: 'people#people_get', via: [:get]
match 'api/people/', to: 'people#create', via: [:post]
this is my javascript:
var $people = $('#people');
var $first_name = $('#first_name');
$('#add_user').on('click', function(){
var person = {
person: {
first_name: $first_name.val(),
last_name: $last_name.val(),
location: $location.val(),
phone: $phone.val()
}
};
$.ajax({
type: 'POST',
url: '/api/people/',
data: person,
success: function(newPerson){
$people.append('<p><strong>First Name: </strong>' + newPerson.first_name + '</p>');
},
error: function(){
alert('error saving person to database');
}
});
});
When I click on the button, it will save the record successfully in the database but when the append happens it brings an undefined value.
Do I have something wrong here?
This is the controller:
before_action :set_person, only: [:show, :edit, :update, :destroy]
def create
#person = Person.new(person_params)
respond_to do |format|
if #person.save
format.html { redirect_to #person, notice: 'Person was successfully created.' }
format.json { render :show, status: :created, location: #person }
else
format.html { render :new }
format.json { render json: #person.errors, status: :unprocessable_entity }
end
end
end
private
def set_person
#person = Person.find(params[:id])
end
def person_params
params.require(:person).permit(:first_name, :last_name, :location, :phone)
end
this is what happens after pressing the button, it brings undefined
You need to tell $.ajax that the response is JSON, using the dataType: option.
$.ajax({
type: 'POST',
url: '/api/people/',
data: person,
dataType: 'json',
success: function(newPerson){
$people.append('<p><strong>First Name: </strong>' + newPerson.first_name + '</p>');
},
error: function(){
alert('error saving person to database');
}
});

Routing error in ajax on ruby on rails

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..

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