Passing data from Ajax to Rails controller - ruby-on-rails

I'm having a little problem with my rails app.
I am trying to pull a random name from an array and pass it into my rails controller and into a method.
This is my AJAX:
var artists = [array with some names]
randomA = {}
var randomArtist = artists[Math.floor(Math.random()*artists.length)];
randomA['a_name'] = randomArtist.toString();
$.ajax({
url: "/songs_echowrap/" + randomA.a_name,
dataType: "json"
}).success(function(data) {
Do Stuff
}
});
});
Here is my routes:
get 'songs_echowrap/:artist_name' => 'users#get_echonest'
Here is my controller:
def get_echonest
foo = params[:artist_name]
#rec = Echowrap.playlist_basic(:artist => params[:artist_name] , :results => 25)
render json: #rec
end
The param is 'undefined' when i run a binding.pry in my terminal.

Do like this in ajax,
$.ajax({
type: "GET",
url: "/songs_echowrap?artist_name=" + randomA.a_name,
datavalue: 'html',
}).success(function(data) {
Do Stuff
}
});
});
In routes,
get 'songs_echowrap' => 'users#get_echonest'
In controller,
def get_echonest
foo = params[:artist_name]
#rec = Echowrap.playlist_basic(:artist => params[:artist_name] , :results => 25)
render json: #rec
end

Within your ajax call you should specify the method (in this case, looks like a GET) and the data required:
$.ajax({
type: "GET",
url: "/songs_echowrap/" + randomA.a_name,
data: randomA.a_name,
}).success(function(data) {
Do Stuff
}
});
});

Try This:
small change with your code, it will work add data varidable in your ajax call like this:
var artists = [array with some names]
randomA = {}
var randomArtist = artists[Math.floor(Math.random()*artists.length)];
randomA['a_name'] = randomArtist.toString();
$.ajax({
url: "/songs_echowrap/" + randomA.a_name,
dataType: "json",
data: {artist_name: randomA.a_name }
}).success(function(data) {
Do Stuff
}
});
});

Sorry, I am relatively new to Javascript and I should have been more clear with my code.
I realized that one of my variables was in the wrong scope so it kept returning as undefined.
I was making two AJAX requests, and I thought i could return the value from the first and pass it through to the second. This question helped me understand my problem: How do I return the response from an asynchronous call?
this is my javascript now:
$('span').on('click', function(){
$('#s_title').empty();
$("#playlist_title").empty();
$("#viito_list").empty();
var p_title = $(this).html();
$("#playlist_title").append(p_title);
var id = $(this).data("id");
var artistsList = []
$.ajax({
url: "/songs/"+id,
dataType: "json",
success: successCallback
})
function successCallback(data){
for(var i = 0; i < data.length; i++){
function msToTime(duration) {
var seconds = parseInt((duration/1000)%60),
minutes = parseInt((duration/(1000*60))%60)
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;
return minutes + ":" + seconds ;
}
artistsList.push(data[i].artists[0].name);
$("#s_title").append("<tr> <td>" + data[i].name + "</td>" + "<td>" + data[i].artists[0].name + "</td>" + "<td>" + msToTime(data[i].duration_ms) + "</td>" + "<td><span class='glyphicon glyphicon-remove song-select'></span>" + "</td> </tr>")
}
randomArtist = artistsList[Math.floor(Math.random()*artistsList.length)];
getWeird(randomArtist)
}
function getWeird(rando){
$.ajax({
type: "GET",
url: "/songs_echowrap?artist_name=" + rando,
dataType: "json"
}).success(function(data) {
$("viito_list").empty();
for(var i = 0; i < data.length; i++){
$("#viito_list").append("<tr> <td>" + data[i].title + "</td>" + "<td>" + data[i].artist_name + "</td> </tr>")
}
});
}
});

Related

select2 with ajax not displaying results

I'm trying to retrieve suppliers with select2 and ajax.
So this is my js code,
$(document).ready(function(){
$('.supplier_suggestion').select2({
placeholder: 'Search for supplier',
ajax: {
type: 'GET',
url: '/search_supplier',
delay: 250,
data: function(params){
var query = {
q: params.term
}
return query;
},
dataType: 'json',
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.text,
id: item.id
}
})
};
}
}
});});
I got this in my haml (which called the js file above)
%b.tosca XXX
.input-field
= f.text_field :supplier_name, class: "supplier_suggestion browser-default"
= error_for #ro_nonreg, :supplier_name
and this ini search_controller.rb
def search_supplier
search = params[:q]
search_pattern = '%' + search.downcase + '%'
result_raw = Supplier.where('lower(supplier_name) LIKE ? OR lower(shadow_id) LIKE ?', search_pattern, search_pattern)
result = []
result_raw.each do |data|
data_hash = {}
data_hash[:id] = data.shadow_id
data_hash[:text] = data.supplier_name
result << data_hash
end
render_secure_json supplier: result
end
what am i missing here?

Can I populate a variable in Knockout and then set it to a hidden variable of my model?

Using MVC 4, I am populating a variable with knockout (in a razor view), and I want to pass that variable back to my controller through my viewmodel. For example
var selectedProgramOptions;
$.ajax({
type: "GET",
contentType: "application/json",
dataType: "jsonp",
url: ceraSvcUrl + "/api/Registrations/GetRegistrationOptions?regId=#Model.Registration.Id",
success: function (result) {
selectedProgramOptions = result;
$.ajax({
type: "GET",
contentType: "application/json",
dataType: "jsonp",
url: ceraSvcUrl + "/api/Programs/GetProgramOptions?programId=#Model.Registration.Program.Id",
success: function (allProgsResult) {
if (allProgsResult.length == 0)
$('#programOptionsDiv').hide();
for (var i = 0; i < allProgsResult.length; i++) {
var match = false;
for (var j = 0; j < selectedProgramOptions.length; j++) {
if (allProgsResult[i].Name == selectedProgramOptions[j].Name) {
match = true;
self.AvailableOptions.push(new ProgramOption(selectedProgramOptions[j].Name, selectedProgramOptions[j].ChargeCode, selectedProgramOptions[j].Price, true, selectedProgramOptions[j].Notes, selectedProgramOptions[j].OptionGroup));
}
}
var chgCode = allProgsResult[i].ChargeCode;
if (match == false && ["TG", "TN", "TP", "TV", "TW", "E2", "E3", "L2", "L3"].indexOf(chgCode) <= -1)
self.AvailableOptions.push(new ProgramOption(allProgsResult[i].Name, allProgsResult[i].ChargeCode, allProgsResult[i].Price, false, allProgsResult[i].Notes, allProgsResult[i].OptionGroup));
}
}
});
}
});
This is the code to populate the knockout field is the self.AvailableOptions. I need to put that field into #Model.Registration.AvailableOptions.

Select2 nested json parsing not working Rails3

I'm trying to make select2 working with my ajax loaded json data with nested attributes.
I wanna get something like this http://ivaynberg.github.io/select2/#multi.
eaxmple json:
[{
id: 1,
name: "GroupName",
users: [{id: 1, name: 'UserName'}, {id: 2, name: 'SecondUser}]
}]
On the site they use <optgroup label="GroupName"><option value="1">UserName</opyion></optgroup> and getting the right result.
In my case it displays nesting properly, but I can select only GroupName, but I need to select nested userName and make GrouoName unselectable, only gor informational purposes.
code:
$('#user_tokens').select2({
placeholder: "Search for a user",
minimumInputLength: 0,
tags: true,
multiple: true,
ajax: {
url: "messages/users_data.json",
dataType: 'json',
quietMillis: 100,
data: function(search, page) {
return {
q: search,
per: 3,
page: page
};
},
results: function(data, page) {
return {
results: data,
};
}
},
formatResult: formatResult,
formatSelection: formatSelection,
dropdownCssClass: "bigdrop"
});
formatResult:
var formatUserResult = function(data) {
var optgroup = "";
var users = "";
if (data.name !== undefined) {
data.users.forEach(function(e) {
users += "<li class='select2-results-dept-1 select2-result select2-result- selectable'>" +
"<div class='select2-result-label'>" +
"<span class='select2-match'></span>"+
e.firstname +
"</div>" +
"</li>";
});
optgroup += "<div class='select2-result-label'>" +
"<span class='select2-match'></span>" +
data.name + "</div>" +
'<ul class="select2-result-sub">' + users + '</ul>';
}
return optgroup;
}
The problem is that optgroup must have class: 'select2-result-unselectable'
Dunno what to do with it.

why jquery autocomplete doesnt work on https (secure pages)?

I am trying to make jquery autocomplete to be work on https (secured pages) pages but its not showing any dropdown.
I searched on this issue and found that its security issue.
can any one tell me how to turn on this autocomplete dropdown on https pages.
here is my code to jquery autocomplete :
function zipAutoCompletet(prefix) {
jQuery("#" + prefix + "_zip").autocomplete({
source: function (request, response) {
jQuery.ajax({
url: "http://ws.geonames.org/postalCodeSearchJSON",
dataType: "jsonp",
data: {
style: "full",
maxRows: 12,
postalcode_startsWith: request.term
},
success: function (data) {
response(jQuery.map(data.postalCodes, function (item) {
return {
label: item.placeName + (item.adminCode1 ? ", " + item.adminCode1 : "") + ", " + item.postalCode + ", " + item.countryCode,
value: item.postalCode
}
}));
jQuery('.ui-autocomplete').css('width', '188px');
}
});
},
minLength: 2,
select: function (event, ui) {
var myString = new String(ui.item.label);
var address = myString.split(',')
jQuery('#' + prefix + '_city').val(address[0]);
jQuery('#' + prefix + '_city').addClass('activated');
jQuery('#' + prefix + '_city').trigger('change');
jQuery('#' + prefix + '_city').parents('.row').removeClass('error-row')
jQuery('#' + prefix + '_city').parents('.row').addClass('ok-row')
var countryCode = address[3] ? address[3] : address[2]
countryCode = jQuery.trim(countryCode);
var countryName = jQuery('#' + prefix + '_country option[value="' + jQuery.trim(countryCode) + '"]').text()
jQuery('#countryContainer .jqTransformSelectWrapper span').html(countryName)
jQuery('#countryContainer .jqTransformSelectWrapper').addClass('selected-jqtranform');
jQuery('#' + prefix + '_country').parents('.row').addClass('ok-row')
jQuery('#' + prefix + '_country').parents('.row').removeClass('error-row')
jQuery('#' + prefix + '_country').val(jQuery.trim(countryCode))
var stateCode = address[2] ? address[1] : '';
stateCode = jQuery.trim(stateCode)
if (countryCode == 'US') {
var base = base_url;
base = base.replace("https", "http");
jQuery.ajax({
url: base + "/getStateName",
dataType: "jsonp",
data: {
stateCode: stateCode
},
success: function (data) {
stateName = data
jQuery('#jc_state').val(stateName);
jQuery('#jc_state').addClass('activated');
jQuery('#jc_state').parents('.row').removeClass('error-row')
jQuery('#jc_state').parents('.row').addClass('ok-row')
jQuery('#jc_state').trigger('change');
formValidate();
}
});
} else {
stateName = stateCode
jQuery('#jc_state').val(stateName);
jQuery('#jc_state').addClass('activated');
jQuery('#jc_state').parents('.row').removeClass('error-row')
jQuery('#jc_state').parents('.row').addClass('ok-row')
jQuery('#jc_state').trigger('change');
formValidate();
}
jQuery('#' + prefix + '_zip').parents('.row').addClass('ok-row')
jQuery('#' + prefix + '_zip').parents('.row').removeClass('error-row');
},
open: function () {
jQuery(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function () {
jQuery(this).removeClass("ui-corner-top").addClass("ui-corner-all");
},
change: function (event, ui) {
if (ui.item === null) {
jQuery("#" + prefix + "_zip").parents('.row').removeClass('ok-row');
jQuery("#" + prefix + "_zip").parents('.row').addClass('error-row');
$("#" + prefix + "_zip").val('');
}
}
});
}
I am using above code for zipcode field.This code works fine on non-https pages it works fine but when I tried it with https pages it doesnt shows.
any solutions are welcome.
As I looked into the service provider they are supporting jsonp and the following sample worked
$("input").autocomplete({
source: function (request, response) {
$.getJSON("http://ws.geonames.org/postalCodeSearchJSON?callback=?",
{ 'postalcode_startsWith': request.term, maxRows: 12, style: "full" },
function(data) {
if(data.postalCodes){
var x = $.map(data.postalCodes, function(v, i){
console.log(v)
return {
label: v.placeName + ' - ' + v.postalCode,
v: v.postalCode
}
});
response(x);
}
}
);
}
});
Demo: Fiddle

How do I pass a textbox value to jQuery .ajax method?

Here's my jquery method:
$.ajax({
type: "GET",
url: "Home/GetSocialMentionBlogs/"
dataType: "json",
success: function (data) {
var obj = JSON.parse(data);
$.each(obj.items, function (i, item) {
$("<strong><p>" + item.title + "</strong></p>").appendTo("#blogs");
if (i == 5) return false;
});
}
});
What I want to do is when a user clicks a button, callt his method, and pass in the value of a textbox so that the URL will now be:
url: Home/GetSocialMentionBlogs/value from text box
Of course I'll need to URL encode that, but as of now, I don't know how to pass in values to this .ajax function.
I'm completely new to jQuery and MVC so pardon my ignorrance ont he subject so far.
Well if the input field has an "id" value you'd just do
url: "Home/GetSocialMentionBlogs/" + $('#inputFieldId').val(),
If all you've got is the name, then you could do:
url: "Home/GetSocialMentionBlogs/" + $('input[name=inputFieldName]').val(),
Is that all you need to do or am I missing some detail?
Oh and to URL encode just use the Javascript encodeURIComponent() function.
$.ajax({
type: "GET",
url: "Home/GetSocialMentionBlogs/" + $('#textBoxID').val(),
dataType: "json",
success: function (data) {
var obj = JSON.parse(data);
$.each(obj.items, function (i, item) {
$("<strong><p>" + item.title + "</strong></p>").appendTo("#blogs");
if (i == 5) return false;
});
}
});

Resources