Sending data from view to controller AJAX - ruby-on-rails

how can I send the var lang to the controller so I can use it in partiel. here is my shot:
$("#search-select").on("click", function() {
var lang = $('#search-select').dropdown('get value');
$.get({
url: translations_url
data: lang,
success: function(){
console.log('data sent');
}
});
});
EDIT
current code:
$("#search-select").dropdown();
$("#search-select").on("click", function() {
var lang = $('#search-select').dropdown('get value');
$.get({
url: "#{translations_url}",
dataType: "script",
data: {
lang: lang
}
});
});
problem: params[:lang] still don't work in controller

Set correct _path to your post method:
$.ajax({
url: '<%= controller_path %>', method: 'POST',
beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))},
data: { lang: lang },
dataType: 'json',
success: function (data) {
console.log(data);
}
});
Now you can work with lang in your controller
def method
params[:lang] # do something
answer = 'Then, you can return some data to view'
respond_to do |format|
format.json { render json: answer }
end
end

you're missing , after url: translations_url, also if you can send data as JSON with key and value, like data: {lang: 'value'}, also you don't need to specify method name if you're using GET, see the below example
$.ajax({
url: translations_url,
data: {lang: 'value'},
success: function(){
console.log('data sent');
}
});
if you need to use POST Method then include method: 'post' incase jquery ajax method doesn't call js.erb file you need to add dataType: 'script'

You can't use route path helpers on the frontend. But you can send proper URL from backend to frontend via data-attribute:
#search-select{ data: { path: translations_url } }
And then in your js:
$("#search-select").on("click", function() {
var url = $(this).data('path'),
data = { lang: $(this).dropdown('get value') };
$.get({
url: url,
data: data,
success: function(){
console.log('data sent');
}
});
});

Related

Why i can not send parameter to controller with ajax?

I write this ajax in view page in asp.net mvc:
<script type="text/javascript">
$(document).ready(function () {
$("#Shareitem").click(function (e) {
var serviceURL = '/Register/FirstAjax';
$.ajax({
type: "POST",
url: serviceURL,
data: '123',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
alert(data);
}
function errorFunc() {
alert('error');
}
});
});
</script>
and this is my action method in controller:
[HttpPost]
public ActionResult FirstAjax(string value)
{
string test = value.Trim();
return Json("PROF.VALI", JsonRequestBehavior.AllowGet);
}
but in this line:
string test = value.Trim();
get this error:
An exception of type 'System.NullReferenceException' occurred in UserRegister.dll but was not handled in user code
How can i solve that?thanks.
You need to send the data in a format that matches the name of the parameter of the method your posting to. Change the ajax data option to
data: JSON.stringify({ value: '123' }),
Alternatively, you can just use
data: { value: '123' },
and remove contentType: "application/json; charset=utf-8", option so it uses the default ('application/x-www-form-urlencoded; charset=UTF-8')

Best way to return a string from a controller to ajax call

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

Making AJAX call to MVC API

I am trying to make an API call with ajax:
svc.authenticateAdmin = function (id, code) {
$.ajax({
url: 'api/event/authenticate',
data: { 'id': id, 'code': code },
datatype: 'json',
contentType: 'application/json',
type: 'GET',
success: function (data) {
App.eventBus.publish('authenticationComplete', data);
}
});
};
The method in the API Controller:
[ActionName("All")]
public bool Authenticate(int id, string code)
{
var repo = new MongoRepository<Event>(_connectionString);
var entry = repo.FirstOrDefault(e => e.Id == id);
return entry.AdminPassword == code;
}
But I am getting a 404 error: urlstuff/api/event/authenticate?id=123&code=abc 404 (Not Found)
I have copied the implementation from a number of known working calls (that I did not write). That look like:
svc.getEventFromCode = function (code) {
$.ajax({
url: '/api/event/',
data: { 'code': code },
dataType: 'json',
type: 'GET',
success: function (data) {
App.eventBus.publish('loadedEvent', data);
App.eventBus.publish('errorEventCodeExists');
},
error: function () {
App.eventBus.publish('eventNotFound', code);
}
});
};
and
svc.getEventPage = function (pageNumber) {
$.ajax({
url: '/api/event/page/',
data: { 'pageNumber': pageNumber },
dataType: "json",
contentType: "application/json",
type: 'GET',
success: function (data) {
App.eventBus.publish('loadedNextEventsPage', data);
}
});
};
But neither has to pass in 2 parameters to the API. I'm guessing it's something really minor :/
Your action name is called "Authenticate", but you have included the following which will rename the action:
[ActionName("All")]
This makes the URL
/api/event/all
The problem lies in your url.
Apparently, ajax interpret / at the start of the url to be root
When the application is deployed on serverserver, its URL is something like http://localhost:8080/AppName/
with api/event/page/, ajax resolve the URL to http://localhost:8080/AppName/api/event/page/ or an url relative to your current directory.
However, with /api/event/page/, the URL is resolved to http://localhost:8080/api/event/page/
Hope it helped.

Read cross domain JSON response

<script>
$.ajaxSetup( {contentType: 'application/json'} );
function submit_data(f){
alert('submitting')
var data_string = $(f).serialize();
$.ajax({
url: "http://localhost:3000/application/1/contact_us.json?jsonpcallback=?"+data_string,
dataType: "jsonp",
type : 'post',
processData: false,
crossDomain: true,
contentType: "application/json",
jsonp: false,
jsonpcallback: result()
});
}
function result(){
alert('back in')
alert(data)
}
function jsonp1300279694167(){
alert('dhoom')
}
</script>
I have script above querying across domain and posting data within a form.
Everything seems to work fine. JSON response can be seen in the firebug console. I want to process the response and display status messages accordingly to the user. How should I achieve it?
UPDATE
I have tried as suggested by T.J. Crowder but have no luck yet. The modified code is as below
function submit_data(f){
alert('submitting')
var data_string = $(f).serialize();
$.ajax({
url: "http://localhost:3000/application/1/contact_us.json?"+data_string,
dataType: "jsonp",
crossDomain: true,
success: handleSuccess()
});
}
function handleSuccess(data) {
alert("Call completed successfully");
alert(data);
}
This does not accesses data and alerts undefined. If I try to pass it from success: handleSuccess() it errors and redirects with a http request.
I am getting response from a Ruby on Rails application. Here is the method I am hitting
def create
errors = ContactUsForm.validate_fields(params)
logger.info errors.inspect
if errors.blank?
respond_to do |format|
format.json {render :json => {:status => 'success'}.to_json}
end
else
respond_to do |format|
format.json {render :json => {:status => 'failure', :errors => errors}.to_json}
end
end
end
Is there any thing that I need to configure in my rails app
You're close. You just use the success callback as usual (see the ajax docs), not a special one:
$.ajax({
url: "http://localhost:3000/application/1/contact_us.json?jsonpcallback=?"+data_string,
dataType: "jsonp",
type : 'post',
processData: false,
crossDomain: true,
contentType: "application/json",
jsonp: false,
success: function(data) {
// Use data here
}
});
Also, your code:
jsonpresponse: result()
...would call the result function and then use its return value for the jsonpresponse property of the ajax call. If you want to use a separate function, that's fine, but you don't include the (), so:
$.ajax({
url: "http://localhost:3000/application/1/contact_us.json?jsonpcallback=?"+data_string,
dataType: "jsonp",
type : 'post',
processData: false,
crossDomain: true,
contentType: "application/json",
jsonp: false,
success: result
});
function result(data) {
// use `data` here
}
Also, I'm pretty sure you don't need/want the jsonp parameter if you use success, so:
$.ajax({
url: "http://localhost:3000/application/1/contact_us.json?jsonpcallback=?"+data_string,
dataType: "jsonp",
type : 'post',
processData: false,
crossDomain: true,
contentType: "application/json",
success: result
});
function result(data) {
// use `data` here
}
Finally: Are you sure you want to set contentType? That relates to the content being sent to the server, not the content being received from it. If you're really posting JSON-encoded data to the server, great, you're fine; but it looks like you're using jQuery's serialize function, which will not produce JSON (it produces a URL-encoded data string). So you probably want to remove contentType as well, both from the call and from the ajaxSetup call.
I hope if you can try jQuery-JSONP
jQuery-JSONP How To
[Example]
$.getJSON('server-url/Handler.ashx/?Callback=DocumentReadStatus',
{
userID: vuserID,
documentID: vdocumentID
},
function(result) {
if (result.readStatus == '1') {
alert("ACCEPTED");
}
else if (result.readStatus == '0') {
alert("NOT ACCEPTED");
}
else {
alert(result.readStatus);
}
});
I tried many tutorials including the answers above but had no luck. So I implemented it something like below
Form
<form action="" onsubmit="submit_data(this, '1'); return false;">
// some form fields
</form>
Submit function for form
<script>
function submit_data(f, app_id){
var data_string = $(f).serialize();
$.ajax({
url: "http://www.example.com/"+app_id+"/contact_us.js?"+data_string,
dataType: "jsonp",
crossDomain: true,
});
}
function show_errors(jsonOb)
{
$("span.error").remove();
$.each(jsonOb, function(key,val){
$("#contact_us_form_"+key).after("<span class=error>"+val+"</span>")
});
}
</script>
In my controller
def create
#application = Application.find params[:application_code]
#errors = ContactUsForm.validate_fields(params, #application)
#application.save_contact_us_form(params[:contact_us_form]) if #errors.blank?
respond_to do |format|
format.js #{render :json => {:status => 'success'}.to_json}
end
end
And finally in create.js.erb
<% if #errors.blank? %>
window.location = "<%= #application.redirect_url %>"
<% else %>
var errors = replaceAll('<%= escape_javascript(#errors.to_json)%>', """, "'")
var errors_json = eval('(' + errors + ')')
show_errors(errors_json);
function replaceAll(txt, replace, with_this) {
return txt.replace(new RegExp(replace, 'g'),with_this);
}
<% end %>
This way I called submit_form on form submit and called show_errors javascript function from server it self. And it works..
But still I would like to have comments if this is a worst solution?

how do I get the form data in a javascript object so I can send it as the data parameter of an $.ajax call

How to return json after form.submit()?
<form id="NotificationForm" action="<%=Url.Action("Edit",new{Action="Edit"}) %>" method="post" enctype="multipart/form-data" onsubmit='getJsonRequestAfterSubmittingForm(this); return false;'>
<%Html.RenderPartial("IndexDetails", Model);%>
</form>
$.ajax({
url: '<%=Url.Action("Edit","Notification") %>',
type: "POST",
dataType: 'json',
data: $("#NotificationForm").submit(),
contentType: "application/json; charset=utf-8",
success: function(result) {
if (result.Result == true) {
alert("ghjghsgd");
}
},
error: function(request, status, error) {
$("#NotSelectedList").html("Error: " & request.responseText);
}
});
I guess what you're actually looking for is not the Submit method, but how to serialise the form data to a json object. To do this you have to use a helper method like here: Serialize form to JSON
Use this instead of running the submit() method, and you'll be fine.
Also, this question is a duplicate of this (even though the question text, and the title are completely misleading): Serialize form to JSON with jQuery
Posting the jQuery extender, just in case, so that it doesn't get lost :)
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
After you have this in your page, you can update your ajax call with this:
$.ajax({
url: '<%=Url.Action("Edit","Notification") %>',
type: "POST",
dataType: 'json',
data: $("#NotificationForm").serializeObject(),
contentType: "application/json; charset=utf-8",
success: function(result) {
if (result.Result == true) {
alert("ghjghsgd");
}
},
error: function(request, status, error) {
$("#NotSelectedList").html("Error: " & request.responseText);
}
});
UPD: If you want to POST the form, then get the response as a json object, and do another ajax call.. then you should look at the jquery.form plugin. you will be able to post your form using an ajax call, then get the response, and run some js when it will return.

Resources