Rails is not accepting arrays in AJAX calls? - ruby-on-rails

My junk:
jQuery 1.3.2
Rails 2.3.5
If I perform a simple AJAX call like this :
$.ajax({
type: "POST",
url: "/admin/emails/" + id + "/distributions",
dataType: "script",
data: { value: ['1', '2'] }
});
Only 2 will return, not 1 and 2 .
Inside the HTTP POST headers in Firebug, it does say that is sending both :
authenticity_token bMmx0pnJ6ePq6ogwSCR1JH55U7wtrMEOy6ME4rNRmCI=
authenticity_token bMmx0pnJ6ePq6ogwSCR1JH55U7wtrMEOy6ME4rNRmCI=
value 1
value 2
Source
value=1&value=2&authenticity_token=bMmx0pnJ6ePq6ogwSCR1JH55U7wtrMEOy6ME4rNRmCI%3D&authenticity_token=bMmx0pnJ6ePq6ogwSCR1JH55U7wtrMEOy6ME4rNRmCI%3D
But when it hits my debugger in my create method :
{"authenticity_token"=>"bMmx0pnJ6ePq6ogwSCR1JH55U7wtrMEOy6ME4rNRmCI=",
"action"=>"create",
"value"=>"2",
"controller"=>"admin/distributions",
"email_id"=>"3"}
What might be going on here?
UPDATE
If I do this :
$.ajax({
type: "POST",
url: "/admin/emails/" + id + "/distributions",
dataType: "script",
data: { value: ["1",[data.value]], type: data.type }
});
I can get all the zips to pass through..

You should use such data format for this request
data: { value[0]: '1', value[1]: '2'}
this code make correct hash
var c = ['1', '2'];
var i = 0;
var b = {}; //hash for data:
c.each(function(zz){
b["value[" + i +"]"] = zz;
i=i+1;
});
usage:
data: b

Related

Search2 - Ajax results with no search

I'm using ajax to pull in data from a php file (which returns json).
I'm wondering, can you have results pulled from Ajax and loads on click without having to search? so essentially you click the field, it drops down with all the elements from Ajax. Couldn't find in the documentation.
Code:
jQuery('.producttypesajax').select2({
allowClear: true,
placeholder: {
id: '',
text: 'Search by Product Type'
},
ajax: {
url: base + '/appProductTypeSearch.php',
dataType: 'json',
delay: 250,
data: function( params ) {
return {
q: params.term // search term
};
},
processResults: function( data) {
return {
results: data
};
},
cache: true
},
minimumInputLength: 1
});
jQuery('.producttypesajax').on('select2:select', function (e) {
var data = e.params.data;
});
https://select2.org/data-sources/ajax
I believe there's no native solution for this, but I managed to do it somehow.
Since Select2 accepts Arrays as a data source, you can make an Ajax request returning your Json object and use it as an "Array".
Sample code:
$.ajax({
url: url,
type: 'get',
dataType: 'json',
success: function (jsonObject){
$('#mySelect').select2({ data: jsonObject });
}
});
It worked for me. Hope it helps.

Passing nested parameters to an ajax get request

In a Rails 5.1 app (without jQuery) how can I pass nested params via a GET ajax request?
I have the following
Rails.ajax({
url: select.getAttribute('data-url') + "?xxx",
type: "GET"
});
If I replace xxx with, for instance, pippo=pluto, in my controller
params[:name] #=> "pluto"
However, in my controller, I need to be able to access a nested param as below.
params[:user][:name] #=> "pluto"
It seems a simple problem but I cannot find a solution.
Here my JS
document.addEventListener('turbolinks:load', function() {
var select = document.querySelector("select[name='user[name]']")
if(select.options[select.selectedIndex].value) {
Rails.ajax({
url: select.getAttribute('data-url'),
type: "GET",
data: {
user: {
name: select.options[select.selectedIndex].value
}
}
});
}
});
Which produces (user[:name] is always selected)
{"object Object"=>nil, "controller"=>"steps", "action"=>"index"} permitted: false>
The query string works fine (but is ugly)
Rails.ajax({
url: select.getAttribute('data-url') + '?user[name]=' + select.options[select.selectedIndex].value,
type: "GET"
});
SIDE QUESTION: To avoid the ajax request in the first place is there an alternative way to automatically trigger the request of the select below when the page is loaded? Currently, it is triggered only when the selected option changes
<%= f.select :user, MyUsers.all,
{ data: { remote: true, url: duplicate_users_path } } %>
use data option in ajax (recommended)
Rails.ajax({
url: select.getAttribute('data-url'),
type: 'GET',
data: {
users: {
pippo: 'pluto',
pippo2: 'pluto2'
}
}
});
or query string as array
Rails.ajax({
url: select.getAttribute('data-url') + '?users[pippo]=pluto&users[pippo2]=pluto2',
type: 'GET'
});

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;
});
}
});

problems with passing html to the server with jquery

i have an ajax call
$.ajax({
url: '<%=Url.Action("SaveDetails","Survey") %>',
dataType: 'JSON',
cache: false,
data: { Id: selectedRow.Id, Value: surveyValue, FileName: filename, FileGuid: fileguid },
success: function(data) {
...
}
});
where the surveyValue is a html string. this call doesn't work. but is i change the surveyValue to an ordinary text i works fine.
how can i pass the html to the server?
I'm guessing you'll need to encode it:
data: { ... Value: encodeURIComponent(surveyValue), ... }
And on the server side:
string value = Server.UrlDecode(surveyValue);

Request URL encoding issue in $.ajax call and Max request URL length in $.ajax as compared to Ajax.ActionLink

I am doing a simple $.ajax request:
$.ajax({
type: "POST",
url: "/Run/" + param1 + "/" + param2,
dataType: 'html',
error: function(error) {
},
success: function(html) {
}
});
If my param2 value is like http://localhost/pub/file?val1=Some Text&val2=Some Text then encoding done using escape(param2), encodeURI(param2), encodeURIComponent(param2) doesn't help. And I get following ERROR -->
HTTP Error 400.0 - Bad Request
ASP.NET detected invalid characters in the URL
My Questions -->
How should I encode param2 ?
What is the maximum length of request URL in $.ajax call ?
Is request URL max length dependent on type of browser from which request is made ?
I have observed that if I use Ajax.ActionLink then I do not need to encode the parameters passed to action and I can pass parameters with length > 10,000 characters as well. But I do not know how to make an explicit call using Ajax.ActionLink from my java script. I need to click on that actionlink to make call through Ajax.ActionLink.
Benefits of Ajax.actionLink-->
Please see the length of parameter categoryName passed to action using Ajax.ActionLink (This is mine observation)
Such big parameters should be posted and not sent in the URL.
$.ajax({
type: 'POST',
url: '/Run',
data: { param1: param1, param2: param2 },
dataType: 'html',
error: function(error) {
},
success: function(html) {
}
});
This will automatically handle parameter encoding. If you absolutely insist on sending them in the url you may declare a global javascript variable that will hold the url to call:
<script type="text/javascript">
var url = '<%= Url.Action("Run"), new { param1 = "value1", param2 = "value2" } %>';
$(function() {
$.ajax({
type: 'POST',
url: url,
dataType: 'html',
error: function(error) {
},
success: function(html) {
}
});
});
</script>

Resources