I use select2 to call an ajax search on my form. The form is unable to get response with my ajax, I tested at postman my Brand method, and it is able to return json, so I wonder if it is something wrong with my apllication.js or input? Previously I test with:
Sample input
<%= f.select :brand_id, Brand.all.collect {|x| [x.name, x.id]}, {include_hidden: false} %>
it is able search all data inside brand table.
products_controller.rb
def brand
#brands = Brand.select(:id, :name).where("name like :q", q: "%#{params[:q]}%")
respond_to do |format|
format.json { render json: {brands: #brands.map { |e| {id: e.id, name: e.name} }}
}
end end
input form
<%= f.hidden_field :brand_id, class: "brand-select", data: { source: dashboard_brand_path, placeholder: 'Search for a name' } %>
application.js
$( ".brand-select" ).select2({
minimumInputLength: 1,
placeholder: "Brand search",
theme: "bootstrap",
tags: [],
ajax: {
url: "/dashboard/brand",
dataType: 'json',
type: "GET",
quietMillis: 50,
id: function(obj) {
return obj.id;
},
data: function (term) {
return {
q: params.term, // search term
page: params.page
};
},
results: function (data) {
return {
results: $.map(data, function (item) {
return {
name: item.name,
id: item.id
}
})
};
}
},
});
Thank for helping
<%= f.hidden_field :brand_id, class: "brand-select", data: { source: dashboard_brand_path, placeholder: 'Search for a name' } %>
You have Used hidden_field. I guess you should use
<%= f.select :brand_id, Brand.all.collect {|x| [x.name, x.id]}, {include_hidden: false}, class: 'brand-select', placeholder: 'Search for a name' %>
Related
I am trying to add google autocomple api, but it works only after page reload and sometimes doesn't works even after ``page reload , Below is the code:
<%= javascript_include_tag 'https://maps.googleapis.com/maps/api/js?key=' + Rails.application.secrets.google_api_key + '&libraries=places' %>
<div class="mui-textfield" data-turbolinks="false">
<input type="hidden" name="id" value='' id="user_id">
<%= text_field_tag :location, nil, id: 'txtPlaces', class: "form-text", placeholder: '', required: true %>
<%= hidden_field_tag :full_address, nil, id: 'full_address', class: "form-text", placeholder: '' %>
</div>
<script>
var ready = function () {
var options = {
type:['(regions)'],
componentRestrictions: {
country: ['au']
}
};
google.maps.event.addDomListener(window, 'load', function () {
var input = document.getElementById('txtPlaces');
var places = new google.maps.places.Autocomplete(input, options);
google.maps.event.addListener(places, 'place_changed', function () {
$("#full_address").val($("#txtPlaces").val());
});
});
// This is some custom requirement
$('.save-address').on('click', function(e){
if($("#full_address").val() !== $("#txtPlaces").val()){
e.preventDefault();
e.stopPropagation();
$("#txtPlaces").val('');
$(this).submit();
}
});
};
<%#*$(document).ready(ready);%>
<%#*$(document).on('page:load', ready);%>
$(document).on("turbolinks:load", ready);
</script>
I have tried both above ready and page:load function as well but no luck
Other than this, below is the code to reach above page
<li><%= link_to('Active', admin_staffs_path(status: 'accepted'), data: { turbolinks: false })
I just migrated to a different bootstrap template now my ajax functions is not working and my php file which handles the functions is not appearing in the XHR inspect tool of chrome.
I only have this jquery script ? is this enough for running an ajax function? I
<!-- Jquery Core Js -->
<script src="../dashboard-assets/plugins/jquery/jquery.min.js"></script>
HTML CODE
<form id="upload_book_form" method="POST">
<p>Upload Books</p>
<input type="file" id="uploadbookinfo" name="uploadbookinfo" value="Import" />
</form>
SCRIPT FUNCTION
<script type="text/javascript">
$(document).ready(function() {
//upload book
$('#uploadbookinfo').change(function() {
$('#upload_book_form').submit();
});
$('#upload_book_form').on('submit', function(event) {
event.preventDefault();
$.ajax({
url: "adminfunctions.php",
method: "POST",
data: new FormData(this),
contentType: false,
processData: false,
success: function(data) {
var getdata = data.trim();
if (getdata == "SUCCESS") {
swal({
title: 'Success!',
text: 'Book Added , Try refreshing the page',
type: 'success',
confirmButtonClass: "btn btn-success",
buttonsStyling: false
}).then(function() {
$("#uploadbookinfo").val(null);
});
} else if (getdata == "ERRORFILETYPE") {
swal({
title: 'Oops...',
text: 'File type is not supported',
type: 'error',
confirmButtonClass: "btn btn-danger",
buttonsStyling: false
}).then(function() {
$("#uploadbookinfo").val(null);
});
} else {
swal({
title: 'Sorry for the inconvenience!',
text: "There's a problem. Please contact the technical support for any concerns and questions.!",
type: 'error',
confirmButtonClass: "btn btn-info",
buttonsStyling: false
}).then(function() {
$("#uploadbookinfo").val(null);
});
}
},
error: function(jqXHR, exception) {
console.log(jqXHR);
}
});
});
});
</script>
So im creating a basic tasklist where i want to set them done, when the <li>is clicked. When it's clicked i want that a class is added to the <li> thats clicked. i could not figure this out with the docs so i hope someone could help me out :D
The code i already have:
<transition-group name="list">
<li class="list-item list-group-item" v-for="(task, index) in list" :key="task.id" v-on:click="finishTask(task.id)" >
#{{ task.text }}
<button #click="removeTask(task.id)" class="btn btn-danger btn-xs pull-right">Delete</button>
</li>
</transition-group>
</ul>
</div>
// get the csrf token from the meta
var csrf_token = $('meta[name="csrf-token"]').attr('content');
export default {
data() {
return {
list: [],
taskInput: {
id: '',
text: ''
}
};
},
// So the tasks will show when the page is loaded
created() {
this.allTasks();
},
methods: {
// get all the existing tasks
allTasks() {
axios.get('tasks').then((response) => {
this.list = response.data;
});
},
// create a new task
createTask() {
axios({
method: 'post',
url: '/tasks',
data: {
_token: csrf_token,
text: this.taskInput.text,
},
}).then(response => {
this.taskInput.text = '';
this.allTasks();
});
},
// remove the tasks
removeTask(id) {
axios.get('tasks/' + id).then((response) => {
this.allTasks();
});
},
finishTask(id) {
axios({
method: 'post',
url: 'tasks/done/' + id,
data: {
_token: csrf_token,
data: this.taskInput,
},
}).then(response => {
this.allTasks();
});
}
}
}
I know how i should do this with jquery but not with vue js, i hope this aint a to stupid question :D
You can bind css classes and styles, add a Boolean done property to your note object with default value of false, when you click the note change its done property to true. here is an example
new Vue({
el:"#app",
data:{
notes: [
{ text: "First note", done:false },
{ text: "Second note", done:false },
{ text: "Third note", done:false },
{ text: "Fourth note", done:false },
{ text: "Fifth note", done:false }
]
},
methods:{
finishNote(note){
// send your api request
// then update your note
note.done = true
}
}
})
.done{
background-color:green;
}
<script src="https://cdn.jsdelivr.net/npm/vue#2.5.13/dist/vue.min.js"></script>
<div id="app">
<ul>
<li v-for="note in notes" :class="{done:note.done}" #click="finishNote(note)">{{note.text}}</li>
</ul>
</div>
You can use the event argument. Which is automatically provided on your on click method.
onListClicked(event) {
event.target.className += " myClass";
}
Here I did a demo for you: https://jsfiddle.net/6wpbp70g/
I initialize the table as follows:
<div id="ordersList"
data-role="uigrid"
data-scrollable="false"
data-checkbox="true"
data-pageable="true"
data-class="zebra"
data-bind="source: orders, events : { selectionChanged: selectionChanged }"
data-columns="[
<% if (isSeller) { %>
{ title: 'Покупатель', field: 'buyerName' },
{ title: 'GLN покупателя', field: 'buyerGln' },
<% } else { %>
{ title: 'Продавец', field: 'sellerName' },
{ title: 'GLN продавца', field: 'sellerGln' },
<% } %>
{ title: 'Номер заказа', templateId: 'col-template' },
{ title: 'Статус', field: 'status' }
<% if (!isSeller) { %>
,{ title: '', templateId: 'col2-template', width: 35 }
<% } %>
]"></div>
</div>
How to add the class to the table?
This variant does'n work - data-class="paging-fix zebra"
uh ... did you try add it by usual way?
<div id="ordersList" class="MyClass"
data-role="uigrid"
...
Here you can see that class is added.
In your case, creating a grid whith an div, you can apply an Class direcly in your selector, if you preffer or if you having problems, you can append class to the widget Wrapper (something like : Objectgrid.wrapper) after initialization
Hope this help
How do you get the value of the textbox field and send as data inside of ajaxOptions? I tested my view and it prints out the test variable successfully from my Django views. I am using X-editable for Jquery. Heres what textbox input looks like:
http://jsfiddle.net/xBB5x/197/
views.py
def create_post(request):
print request.POST.get("test", "");
return HttpResponse(json,content_type="application/json")
HTML
<a id="other1" data-pk="First Name" data-name="test">First Name</a>
AJAX
$(document).ready(function() {
$('#other1').editable({
type: 'text',
pk: 1,
url: '/create_post/',
ajaxOptions: {
data: {
csrfmiddlewaretoken: '{{ csrf_token }}',
test: "hi",
},
},
placement: 'top',
title: 'New Expense',
success: function(response, newValue) {
if(response.status == 'error') return response.msg; //ms
},
});
});
Instead of ajaxOptions, use params. If I remember correctly, test and its value will be included in your POST request by x-editable. Try something like this:
Html
<a id="other1" data-pk="1" data-name="test">First Name</a>
AJAX
$(document).ready(function() {
$('#other1').editable({
type: 'text',
url: '/create_post/',
params : function(params) {
params.csrfmiddlewaretoken = '{{ csrf_token }}';
return params;
},
placement: 'top',
title: 'New Expense',
success: function(response, newValue) {
if(response.status == 'error') return response.msg; //ms
},
});
});