I have set up a rails api and it only response in the following format which is done through the serializer:
data: { user_name: 'Test User' }
And on the view side, I have got the following partial:
.user-change
= render partial: 'test_user', locals: {user_name: current_user.name}
What would be the correct way to change the user_name as per the API response from the following successful ajax request?
$("#change-me").click(function() {
var user_id;
user_id = $("#user_id").val();
$.ajax({
url: "/api/v1/user/change/" + user_id,
method: "POST",
dataType: "json",
data: JSON.stringify({
{
user_id: user_id,
}
}),
success: function(res, status, xhr) {
let response = res.data;
let userName = response.user_name;
// Update user_name after this event on the partial?
}
},
error: function(res) {
}
});
})
Partial code: _test_user.html.haml
.col-md-9
%p= "Hi! This is the request change from #{user_name}."
Related
I have an index method that respond with Json call to Datatable such as:
respond_to do |format|
format.html
format.json { render json: PeopleDatatable.new(params, user: current_user, view_context: view_context) }
end
I would like to be able to pass an array of all the IDs in the response to a dom in my view such as <div id: "people">1,2,3,4</div>
As per the gem description, the People records are generated in the
app/datatables/people_datatable.rb
using:
def get_raw_records
User.all
end
I tried adding the following in the view's script:
$(document).ready(function () {
$.ajax({
type: "GET",
url: "<%= peoples_path(format: :json) %>",
dataType: "json",
success: function(data) {
alert(data.name)
$('#bouba').html(data);
}
});
});
but the result is an undefined object class.
What would be the easiest way to do so please?
I am using the following gem for my datatable Rails ajax Datatable
Open /people.json and see what you get as a response, it looks something like this:
{
"recordsTotal": 2,
"recordsFiltered": 2,
"data": [
{
"id": "1",
"name": ""
},
{
"id": "2",
"name": ""
},
]
}
Now that you know what the structure looks like, send ajax request to that url:
<div id="people-ids"></div>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "GET",
// send request to the correct url: "/people.json"
url: "<%= people_path(format: :json) %>",
dataType: "json",
success: function({data}) {
// ^
// extract "data" attribute from the response
console.log(data) // you can see what you get in the console
// extract ids
const user_ids = data.map(user => user.id)
// do what you like with the ids
$("#people-ids").html(user_ids.join());
}
});
});
</script>
I have followed this tutorial: https://blog.andrewray.me/how-to-set-up-devise-ajax-authentication-with-rails-4-0/ And am using rails 5.1.
I have implemented the json response in the controller:
class RegistrationsController < Devise::RegistrationsController
respond_to :json
end
And when I call the ajax I only get an Html/Text response:
function createUser(callback) {
$.ajax({
type: "POST",
url: window.urls.createUser,
data: {
authenticity_token: $("meta[name=csrf-token]").attr("content"),
user: grabOrderFormUserData()
},
success: function(data) {
console.log("Data: " + data);
},
error: function (data) {
//console.log("error");
}
})
}
That call works fine, but returns the HTML page of the sign up.
The url I use is createUser: hostUrl + '/users/'
What did I miss?
And no, if I add .json to my url, it will respond with 500 error code.
I think you missed to mention dataType: "json" with your ajax call , try this
function createUser(callback) {
$.ajax({
url: window.urls.createUser,
type: "POST",
data: {`enter code here`
authenticity_token: $("meta[name=csrf-token]").attr("content"),
user: grabOrderFormUserData()
},
dataType: "json",
success: function(data) {
console.log("Data: " + data);
},
error: function (data) {
//console.log("error");
}
})
}
and also in your controller try to call this block in case if you are not getting json response,
respond_to do |format|
format.json {
render json: {.....}
}
end
thank you.
I know there are many questions about that already on stackoverflow but none of them has been useful for me. Here is my ajax code:
function update_schedule($task){
var taskId = $task.data("taskId"),
startHour, endHour,
userId = $('#users').val();
if( !$task.hasClass('daily-task')){
startHour = getStartHour($task),
endHour = startHour + (+$task.data('time'));
}
console.log(startHour, endHour)
$.ajax({
url: '/heimdall/update_scheduled_task',
method: 'POST',
data: { "task_id": taskId, "start_hour": startHour, "end_hour": endHour, "user_id": userId },
success: function (){
console.log("SUCESS!!", data['head'])
},
error: function () {
console.log("FAILURE");
},
async: true
});
}
The controller code:
def update_scheduled_task
scheduled_task = ScheduledTask.find_or_create_by(task_id: params[:task_id])
scheduled_task.update_attributes(start_hour: params[:start_hour], end_hour: params[:end_hour], task_id: params[:task_id], user_id: params[:user_id])
end
I want to return the id of found or created task. I don't know how to send/receive this information. I've read about respond to but still I don't know how to use it in this case.
You may do render json: ... to return the required info to ajax in JSON format:
def update_scheduled_task
scheduled_task = ScheduledTask.find_or_create_by(task_id: params[:task_id])
scheduled_task.update_attributes(start_hour: params[:start_hour], end_hour: params[:end_hour], task_id: params[:task_id], user_id: params[:user_id])
render json: {scheduled_task_id: scheduled_task.id}
end
And in the ajax function's success, use it like:
success: function (data){
var data = JSON.parse(data);
console.log(data["scheduled_task_id"]);
},
First, you need to improve your controller code structure (You can rely on the default scaffold generator methods). Then, you must indicate that your method will respond to json format only, with the answer you want to return, something like this:
def update_scheduled_task
scheduled_task = ScheduledTask.find_or_create_by(task_id: params[:task_id])
if (scheduled_task && scheduled_task.update_attributes(start_hour: params[:start_hour], end_hour: params[:end_hour], task_id: params[:task_id], user_id: params[:user_id]))
render json: { scheduled_task_id: scheduled_task.id }
else
render json: { error: l18n.t("error.messages.request_error") }
end
end
Then, you must modify the success and failure response methods of the jquery ajax request. Here's an example of how it might look:
$.ajax({
url: "/heimdall/update_scheduled_task",
method: "post",
data: { task_id: taskId, start_hour: startHour, end_hour: endHour, user_id: userId },
success: function(result) {
if (result["scheduled_task_id"] != null) {
console.log("Schedule record => " + result["scheduled_task_id"])
} else {
console.log("Error: " + result["error"])
}
},
error: function() {
console.log("Ajax request error");
},
// async: true => By default JQuery set true to async param.
});
Do not forget that you need to add a rule to access this method in the file config/ruotes.rb, something like this:
post update_scheduled_task, :defaults => { :format => 'json' }
I hope this helped you, regards!
jQuery's success and error callbacks rely on the status code returned by the controller. Make sure that you return the right status code when you are unable to create/read/update the object. On success, simply render a JSON with the id property set. I beleive update_attributes returns true on success:
if scheduled_task && scheduled_task.update_attributes(...)
render json: { id: scheduled_task.id }
else
head :unprocessable_entity
end
I'm making a POST request from a nested form which is written in reactjs such that it is making an ajax request to create method of the products controller.
React Code:
I have an empty object in the getInitialState like this
getInitialState: function() {
return {
products: [{name: '', price: '', quantity: ''}],
count: 1
};
},
When i submit the form,
handleSubmit: function(e) {
e.preventDefault();
var productsArray = this.state.products;
$.ajax({
data: {
product: productsArray
},
url: '',
type: "POST",
dataType: "json",
success: function ( data ) {
console.log(data);
// this.setState({ comments: data });
}.bind(this)
});
},
the object gets populated and the parameter hash becomes like this
Parameters: {"product"=>{"0"=>{"name"=>"", "price"=>"", "quantity"=>""}}, "shop_id"=>"gulshop"}
So i'm getting
ActiveRecord::UnknownAttributeError (unknown attribute '0' for Product.):
How can i get the parameter hash like this:
Parameters: {"product"=>[{"name"=>"", "price"=>"", "quantity"=>""}], "shop_id"=>"gulshop"}
What can be done for it ?
Your original error 'unknown attribute '0' for Product.' is because the Product class does not have an attribute '0'. I'm not sure where the '0' is coming from as you haven't posted your react code that makes the request.
You can easily make a request from your component using jQuery's .ajax method. e.g
$.ajax({
type: 'POST',
url: '/your_url',
data: {
course: {
name: 'Hello World',
price: 120
}
}
});
You would then have something like the following in your controller..
class ProductController < ApplicationController
def create
#product = Product.create(product_params)
end
private
def product_params
params.require(:product).permit(:name, :price)
end
end
I want to create an action that returns me a single string value:
def delay_calulation()
dr = Dr.find(params[:id])
delay = dr.calc()
respond_to do |format|
format.json { render json: {"value" => delay}}
end
end
but I a "fail" in my ajax call:
$("#btn_delay").on("click", function () {
$.ajax({
type: "GET",
dataType: "script",
url: "/drs/delay_calulation/1"
})
.done(function(response){
console.log(response);
})
.fail(function(response){
console.log(response);
});
});
How can I get a single string, or something like that.
You need to pass id to the controller action while calling through Ajax. You can retrive the string by using the key name that you have mentioned in the controller.
$.ajax({
url: '/drs/delay_calulation',
data: {id: (you need to pass the id)},
type: "get",
dataType: "json",
success: function(data){
var a = data["delay"]
},
failure: function(data){
var a = data["delay"]
}
});