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');
}
});
Related
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
I'm calling an AJAX function from a select_tag like so:
<%= select_tag 'quantity', options_from_collection_for_select(order.options), :quantity, :quantity, order.quantity), onchange: "update_price(#{order.id}, this.value);" %>
And here's the function:
<script type='text/javascript'>
function update_price(order_id, quantity) {
$.ajax({
url: "/cart/" + <%= #cart_transaction.id %> + "/update_quantity",
type: "POST",
data: {
"order_id" : order_id,
"quantity" : quantity },
dataType: "html"
});
}
</script>
My .js.erb isn't called ever, and I suspect it's because I haven't specified remote: true anywhere, but since I don't have a form per se I don't know how to do that. Any help?
Relevant controller code here:
class CartTransactionsController < ApplicationController
load_and_authorize_resource
respond_to :html, :js
before_filter :set_cart_transaction
def update_quantity
#order = #cart_transaction.orders.find(params[:order_id])
#price = current_user.brand.prices
.where(template_id: #order.document.template.id)
.where(quantity: params[:quantity]).first
#order.update_attributes(
price_cents: #price.amount_cents, quantity: params[:quantity]
)
#cart_transaction.save!
respond_to { |format| format.js }
end
private
def set_cart_transaction
#cart_transaction = current_user.cart
end
def cart_transactions_params
params.require(:cart_transaction).permit(
:name, :email, :delivery_address, :comments
)
end
end
Update
Here's the .js.erb that isn't called for some reason:
console.log("update_quantity.js.erb file");
$('#price_cell').html("<%= j render(partial: 'price', locals: { order: #order }) %>");
$('#subtotals').html("<%= j render(partial: 'subtotals', locals: { cart_transaction: #cart_transaction }) %>");
Try this:
function update_price(order_id, quantity) {
$.ajax({
beforeSend: function(xhr) {
xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
},
url: "/cart/" + <%= #cart_transaction.id %> + "/update_quantity",
type: "POST",
data: {
"order_id" : order_id,
"quantity" : quantity }
});
}
Use dataType: "script", it will work and will render js.erb
I have the following controller actions:
def new
#tag = Tag.new({company_id: current_member.company_id })
end
def create
#tag = Tag.new(tag_params)
#companyid = current_member.company_id
respond_to do |format|
if #tag.save
format.html {redirect_to root_path}
format.json {render :json=> #tag}
else
format.html {redirect_to root_path}
end
end
end
Inside my new.html.slim view file I have:
= simple_form_for #tag, url: tags_new_path, html: {id:'tag_form_submit', method: :post}, format: :js, remote:true do |t|
=t.input :name, placeholder: 'tag'
=t.button :submit, "submit tag", id:"submit_tag_button"
javascript:
$(document).ready(function(){
$("#submit_tag_button").click(function(event){
event.preventDefault();
<!-- $("#tag_form_submit").hide(); -->
<!-- $('#add_tag_tag').hide(); -->
var text = $("#inputbox").val();
var name = $("#tag_name").val();
var datatosend = { tag: {name:name, company_id: "#{#companyid}" } };
$.ajax({
url: "/tags/new",
dataType: "json",
method: "post",
data: datatosend,
success: function(result){
console.log(result)
var nameVar=result.name;
var idVar=result.id;
console.log(nameVar);
console.log(idVar);
var newspan='<span class="checkbox"><label for="job_tag_ids_'+idVar+'" name="job[tag_ids]"><input class="check_boxes optional form-control" data-remote="true" id="job_tag_ids_'+idVar+'" name="job[tag_ids][]" type="checkbox" value="'+idVar+'">' + nameVar + '</label></span>';
$("#all_tags > div.form-group.check_boxes.optional.job_tags > div").append(newspan);
<!-- $(#event_tag_ids).append('hi'); -->
if ($("#event_tag_ids").length){
$("#event_tag_ids").append('<option value="'+idVar+'">'+nameVar+'</option>');
}
// after its appended, erase from form input
console.log(result.company_id);
$("#tag_name").val("");
}
})
})
});
In my datatosend varible I am trying to send:
var datatosend = { tag: {name:name, company_id: "#{#companyid}" } };
but #companyid is being posted as null. Why?
How do I successfully access #companyid from the controller inside my JavaScript so I can send it in when making my AJAX post call?
You're only assigning the #companyid instance variable in the create action of your controller, not the new action.
The view template you posted is rendered as part of the new action. So you should change your controller:
def new
#companyid = current_member.company_id
#tag = Tag.new(company_id: #companyid)
end
I have a Cart controller and a "show" view which shows the contents of the cart. I want to show the cart in every view of my Products controller. So, I'm rendering the cart/show in products/show using
<%= render "/cart/show" %>
Now, I want to update the cart via ajax when a user wants to add a product. Please guide me how I should design my controllers to achieve this.
How to use partials to DRY up your views.
http://guides.rubyonrails.org/layouts_and_rendering.html
function postToRailsApi() {
$.ajax({
type: "POST",
url: "the_url_you_want_to_post_to/endpoint",
data: {someData: {thisId: otherId}},
dataType: "json",
success: function(data) {
alert("OMG SUCCESS status:200")
}
});
In the rails controller:
respond_to do |format|
if #my_condition.save
format.html {render nothing: true, status:200}
format.js{render nothing: true, status:200}
format.json { render json: #timestamp, status: 200 }
else
format.html { render action: "new" }
format.js { render nothing: true, status: 400 }
format.json { render nothing: true, status: 400 }
end
end
Obviously your logic will be different.
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 }