I have an array of objects. I want to be when you click on the link, I came through all the objects and displays them on the page, at using ajax
run.js.erb
$(function(){
$("#next").click(function(){
$.post(<%= EngineHelper.nextQuestion %>, function(data){
$("#question").html(data);
});
return false;
});
});
But it does not work. in the script instead of <% = EngineHelper.nextQuestion%> substituted the current data array element. and I need to display the next array element
try converting it to jSON
so instead:
$.post(<%= EngineHelper.nextQuestion.to_json %>, function(data){
$("#question").html(data);
});
hope it helps :)
Related
I have a filter and a list of products (id, name, creation_date).
I can filter by id, name or creation_date. With an AJAX request I update a content div... but obviously the URL not change.
How can I append params to URL? For example:
localhost:3000/dashboard/catalog?name=radio&?date_creation=23-06-2013
I know that history.pushState(html5) exists... but I need that my app works in html4 browsers like IE9.
I tried Wiselinks (https://github.com/igor-alexandrov/wiselinks) which it uses History.js but it doesn´t use AJAX request.
Any ideas?
thanks
Finally I follow those RailsCasts tutorials:
http://railscasts.com/episodes/240-search-sort-paginate-with-ajax?language=es&view=asciicast
http://railscasts.com/episodes/246-ajax-history-state?language=es&view=asciicast
You are doing some AJAX call means, you must have invoked the AJAX part on radio button change
So I am assuming, you have done it using by radio button and the radio button name is 'choose_product'
You can add a hidden field in your view, where you can store your current date.
<div id='parentDiv'>
<%= hidden_field_tag 'current_date', Time.now.strftime('%d-%m-%Y') %>
Your radio button code
</div>
In the javascript add the following code. It is just a sample not complete solution.
$(document).ready(function(){
var showProducts = function(){
$("#parentDiv").on('click', "input[name='choose_product']", function(){
var ajax_url = 'localhost:3000/dashboard/catalog';
var url_param = '';
switch($(this).val()){
case 'creation_date':
var param_date = $('#current_date').val();
url_param = '?name=radio&date_creation=' + param_date;
break;
case 'name':
// Your code goes here
default:
//Your code goes here
}
// Here you will get the modified url dynamically
ajax_url += url_param
$.ajax({
url: ajax_url,
// your code goes here
});
});
}
showProducts();
});
A lot of time has passed, but it may be useful.
The code is also updated so if you have more then one ajax\remote link you will be able to merge the params of multiple urls.
Based on user1364684 answer and this for combine urls.
# change ".someClassA" or "pagination" to the a link of the ajax elemen
$(document).on('click', '.someClassA a, .pagination a', function(){
var this_params = this.href.split('?')[1], ueryParameters = {},
queryString = location.search.substring(1), re = /([^&=]+)=([^&]*)/g, m;
queryString = queryString + '&' + this_params;
#Creates a map with the query string parameters
while m = re.exec(queryString)
queryParameters[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
url = window.location.href.split('?')[0] + "?" + $.param(queryParameters);
$.getScript(url);
history.pushState(null, "", url);
return false;
});
# make back button work
$(window).on("popstate", function(){
$.getScript(location.href);
});
I am trying to make some useful directives with jQueryUI widgets for my AngularJS base application.
One of them works on "select" element and am ok with directives but only thing do not understand is this one:
When select list is populated from ajax request, how to tell to apply jqueryui widget when data is populated? Suppose it is with $watch but not sure how.
Edit:
In example I am trying to implement directive for the multiselect plugin.
Please note that I am simulating server reponse but putting everything in timeout.
Here is a code on plunker
You need to be $watching changes to the items list, then calling refresh on the multiselect plugin... Here is a plunk that shows the solution
angular.module('myui', [])
.directive('qnMultiselect', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, elem, attr) {
//set up the plugin.
elem.multiselect({ allowClear: false });
//get the source of the ngOptions
var parts = attr.ngOptions.split(' ');
var source = parts[parts.length - 1];
//watch the options source and refresh the plugin.
scope.$watch(source, function(value) {
elem.multiselect('refresh');
});
}
};
});
I have a helper method in my application controller that check to see when an object has been created. Basically if the total number of objects changes it alerts you on the page load with a flash message. This code works fine, but what I want to do is eliminate the need to reload.
How would this be done? I understand the solution would likely involve AJAX, but I'm a newbie to AJAX and rails so I'm not sure how to go about this. Thanks for the help!
<script type="text/javascript">
var i = setInterval( "checkObjectCount()", 10000 );
function checkObjectCount() {
count = <%= #object_count %>;
$.ajax({
url: 'ajax/request_object_count',
success: function(data) {
if (data > count) {
$('#alert_container').show();
clearInterval(i);
}
}
});
}
</script>
The below code having a selectbox with id='theservice' and a text field with id ='servicename'.This code autocompletes the servicename text field by checking which service is active in the service selectbox.But unfortunately the source string remains the same eventhought the selectbox is changed.
$( "#servicename" ).autocomplete({
source: "index.php?key="+($('#theservice').find('option:selected').val()),
minLength: 2,
});
Thanks a Lot
Probably a delegation issue.
Autocomplete propagation example added
//build the autocomplete function, sans source
$('#servicename').autocomplete({
minLength: 2
});
var theArray = [];
$('body').on('change', 'select', function(){
$.ajax({
url: 'index.php?key='+$(this).val(),
dataType: 'json/jsonp',
success: function(data){
//i don't know what the array you return looks like, but autocomplete expets a key:value relationship
$.each(data, function(key, value){
theArray.push({label: value, value: key});
});
//a custom function to pass the array into
startAutoComplete(theArray);
}
});
});
function startAutoComplete(array){
$('#servicename').autocomplete('option', 'source', array);
}
Using the above code, we instantiate the autocomplete instance, we only identify the parameters we need excluding the source.
We then define an empty array that we can push the data returned from our ajax request into.
In our select function, we pass the value over to the server to be parsed. I don't know if you are expecting JSON/JSONP formatting, so you'll have to change that yourself.
In the success:function(data) we're getting back the request from the server, it would be best if the response was json_encode'ed. Also, when we push the values into the array, it's best to use a key -> value relationship. Autocomplete allows for a label and a value to be accessed like function(event, ui){ //do stuff with ui.item.label / ui.item.value}'
We declare an uninitialized function outside of the scope of document.ready, and pass the array into the function. Within this function, we change the source of the autocomplete.
Hope this all makes sense.
Solved the issue by using the .autocomplete( "option" , optionName , [value] ) method
$( "#servicename" ).autocomplete({
source: "index.php?key="+($('#theservice').find('option:selected').val()),
minLength: 2,
search: function( event, ui ) {
$( "#servicename" ).autocomplete( "option" ,'source' ,'index.php?key="+($('#theservice').find('option:selected').val()));}
});
In my web app , I am showing rates of stocks.I am using jquery autocomplete to show options while entring stocks name. But I have built local copy of javascript array. I want to show the options from this local array , If search term is not found in local array then ajax call must be made to get the list from server side.
Thanks !!!
//Local array
var local_array=["option1","option2"];
//jqueryUI call of autocomplete function
$('#search_stock').autocomplete({
source:function(){
if(search term is found in local array)
{
show suggestion from local array.
}
else
{
make ajax call to show suggestions of stock names.
}
}
});
UPDATE
Here's the actual code
$(function() {
var cache = {'option1':'option1','option2':'option2'}, lastXhr;
$( "#stock_rates" ).autocomplete({
minLength: 2,
source: function( request, response ) {
var term = request.term;
if ( term in cache ) {
response( cache[ term ] );
return;
}
lastXhr = $.getJSON( "stock_rates.php", request, function( data, status, xhr ) {
cache[ term ] = data;
if ( xhr === lastXhr ) { response( data ); }
});
}
});
});
The example pages for jQuery UI autocomplete have an example of exactly this issue.
http://jqueryui.com/demos/autocomplete/#remote-with-cache. Click the 'View Source' link on that page to see the code for the example.
The key part is that 'source' takes arguments.
source: function(request, response){
You need to read request, either fetch the value from your cache, or do a request, and then call the response function and pass it the matched values.
Update
Your problem now is that the format that you are storing in your cache is wrong. The cache just stores data as it would be returned from your getJSON call, indexed by the search term. It is up to you do to do the prefix checking and such.
To continue the way you are trying now, you'll either need to populate the cache properly.
var cache = {
"o": ['option1', 'option2'],
"op": ['option1', 'option2'],
// ....
"option1": ['option1'],
"option2": ['option2']
};
Otherwise, you could store the data differently and put more logic in your 'source' function to do the prefix checking on a static array or something. That all really depends on the data you are caching though.
Use search event of autocomplete and check your condition in that event and based on that return true or false if you want to make a ajax call respectively.
Below is the sample code.
$('#search_stock').autocomplete({
search:function(event,ui){
if(search term is found in local array)
{
return false;
}
else
{
return true;
}
}
});