Render rails fields_for through ajax call - javascript

I have an AJAX call:
$('#enrollment_members').change(function(){
var memberNumber = $(this);
$.ajax({type: 'GET',
url: $(this).href,
type: "get",
data: { members: memberNumber.val() },
error: function(){ alert("There was a problem, please try again.") }
});
return false;
console.log(data);
});
through which I send params[:members] into a new method.
I wanna do something like this:
def new
#enrollment = Enrollment.new
params[:members] ? params[:members].to_i.times { #enrollment.atendees.build } : #enrollment.atendees.build
respond_to do |format|
format.js
end
end
I need this value in order to know how many fields_for to build.
But this being in the new action, how can I update the content of the new view after inputting a value in the members input field?
From that ternary, #enrollment.atendees contains 4 objects.
My new.js.erb :
$("#contact-wrap").html("<%= j render(:partial => 'enrollments/form') %>");
The xhr response contains 4 fields_for forms.

Is the object #enrollment_members the input value you are trying to pass to the controller?
if so, try this:
$('#enrollment_members').change(function(){
var memberNumber = $(this);
$.ajax({type: 'GET',
url: $(this).href,
type: "get",
data: { members: memberNumber.serialize() }, //CHANGE
error: function(){
alert("There was a problem, please try again.")
}
});
return false;

Hmm are you really sure you need a custom made solution for this ? The behavior of dynamically adding/removing children in fields_for is already adressed by several gems like nested_form (no longer maintained) or cocoon (more promising)
I'd suggest to actually reuse their library even if you need to tweak it your way. Because doing an AJAX request is completely pointless. Your AJAX is a GET request that will always do the same thing, unless you have a custom atendees.build which will do weird things for successive calls (like incrementing a global counter somewhere).
Those gems I mentionned above will actually save the HTML fields to generate in a "template" (stored locally in HTML or JS), and just call this template when you want to add a new field.

I got it working by modifying the ajax call:
$('#enrollment_members').change(function(){
var memberNumber = $(this);
$.ajax({type: 'GET',
url: $(this).href,
type: "get",
dataType : "html",
data: { members: memberNumber.val() },
success: function( data ) {
var result = $('<div />').append(data).find('#contact-wrap').html();
$('#contact-wrap').html(result);
$('#atendees-wrap').show();
},
error: function( xhr, status ) {
alert( "Sorry, there was a problem!" );
}
});
return false;
});

Related

Ajax is not sending multiselect data to Django views

I am quite new to Django so bare with me.
I have a multiselct list in my webpage and I need to send the selected items to my views in order to make use of them.
To do so, I used ajax but when it doesn't seem to work for some reason.
This is the script:
$("#var_button").click(function(e) {
var deleted = [];
$.each($("#my-select option:selected"), function(){
deleted.push($(this).val());
});
alert("You have deleted - " + deleted);
e.preventDefault();
$.ajax({
type: "post",
url: "/description/upload-csv/" ,
data: {
'deleted' : deleted }
}); // End ajax method
});
I checked with alert if maybe the variable deleted is empty but it return the selected values so the problem is in my ajax query.
This is the part where I retrieve the data in my views.py
if request.method == 'POST':
del_var = request.POST.getlist("deleted[]")
my_class.del_var = del_var
I changed the data type to text but it doesn't do anything
I cant help you on the Django side.
$.each($('#selector'), (i, e) => {
deleted.push($(e).val());
})
but this will add the value to the "deleted" variable.

Making Key Value pair for the form elements in JavaScript

I have a module where the forms created are dynamic. So the number of inputs can defer always. Also, the array key can also defer.
My current method of posting form is this:
name = form_options[option_1] value = 1
On submitting the form using POST, I get the form as array in $_POST, which looks like this.
form_options(
option_1 => 1
)
But, now I am trying to implement the same thing using AJAX. So, I would need a common module to get all form values.
I found a way to do it.
var objectResult = $('#options_form').serializeArray();
console.log(objectResult);
This gives me a result like this:
0: Object
name: "form_options[option_1]"
value: "1"
How can parse this result to get an array like $_POST array, which I can send as data in AJAX.
P.S: All the form elements have name field as form_options[key]
You should use this for get post data in PHP file.
// You can use like this
var objectResult = $('#options_form').serializeArray();
$.ajax({
type: "POST", // Enter Request type GET/POST
url: 'action.php', // Enter your ajax file URL here,
dataType: 'json', // If you are using dataType JSON then in php file use die( json_encode($resultArray) );
data: objectResult, // Put your object here
beforeSend: function(){
alert('before');
},
error: function(data) {
console.log(data);
},
success: function(response){
console.log(response);
}
});
// In php file get values like this way
$_POST['form_options']
try like this,
In JQuery:
var objectResult = $('#options_form').serializeArray();
$.ajax({
type: 'POST',
url: 'yoururl'',
data: objectResult ,
success:function(data){
alert(data);
}
});
In your php:
<?php echo var_dump($_POST);?>
You can use jquery serialize with ajax directly, there is no need to use serializeArray:
$.ajax({
type:"post",
url:"formHandleSkript.php",
data: $("#options_form").serialize(),
success: function(response){
$(".result").html(response);
}
});
For more information see http://api.jquery.com/serialize/

javascript or ajax to update database with asp.net mvc?

I have a function here from a change event on a dropdownlist. When the selection gets changed I want to update a row in my database. Should I use javascript or ajax. I don't want the page to be refreshed. I think it should be ajax, but not sure? If ajax, can anyone point me to a tutorial/video/etc?
Here is where I want to update my db row.
var statusdropdown = document.getElementById("enumstatus");
statusdropdown.addEventListener("change", function(event) {
// call db and update row
}, false);
Looks like you using asp.net mvc.
You can write your ajax calls with pure javascript Ajax docs or the easiest way, using JQuery.
You need to add one action on your controller to receive the ajax data, and then insert/update your db.
See this, this and this.
Most common scenario would be making an ajax call using HTTP POST/PUT to a controller method, which would then handle the data and update the database directly or pass through to your service/data layer code.
Probably the easiest way to make the call would be using the jQuery.ajax method. Documentation can be found here: http://api.jquery.com/jquery.ajax/
You can try something like this
<script type="text/javascript">
$(function () {
$('#btnSubmit').click(function () {
var name = $('#TextBox1').val();
var email = $('#TextBox2').val();
if (name != '' && email != '') {
$.ajax
({
type: 'POST',
url: 'Home/UpdateDB', //if it is plain asp.net then UpdateDB is declared as WebMethod
async: false,
data: "{'name':'" + name + "','email':'" + email + "'}",
contentType: 'application/json; charset =utf-8',
success: function (data) {
var obj = data.d;
if (obj == 'true') {
$('#TextBox1').val('');
$('#TextBox2').val('');
alert("Data Saved Successfully");
}
},
error: function (result) {
alert("Error Occured, Try Again");
}
});
}
})
});
</script>
fg
iuou
uouienter link description here
uiouidfgsdfgddfgdfgdfgdgdgd##
Heading
##*
uio
uiopomkl
hjlkdsg
dsf
dfgdg
Blockquote

Loading JSON Tags into Select2 with AJAX

Ok, so I am using the code below to grab a list of tags and load it up into a select2 box. The options are being returned as ["test1","test2"] which should be the correct format, but I am assuming they need to be processed in a loop somehow.
//This part is meant to grab the options. I am using model ID 473 for testing
$('#ticket_style_id').on("change", function(e) {
var tag_list = $.ajax({
url: "/grab_options/<%= 473 %>",
async: false
}).responseText;
//This part is meant to load the tag_list into a select2 box based on the
//selection above
$("#ticket_option_list").select2({
tags: [ tag_list ]
});
})
Interestingly if I substitute the following:
$("#ticket_option_list").select2({
tags: ["test1","test2"]
});
...everything generates fine.
The JSON is being returned by this controller code:
def grab_options
style = Style.find(params[:id])
respond_to do |format|
format.js { render json: style.option_list.to_json }
end
end
I would suggest the following approach for 2 reasons:
1) It forces the response to be interpreted as JSON (because of dataType: 'json')
2) It uses the success callback instead of using async: false
$('#ticket_style_id').on("change", function(e) {
var tag_list = $.ajax({
url: "/grab_options/<%= 473 %>",
dataType: 'json',
success: function(response) {
$("#ticket_option_list").select2({
tags: response
});
}
});
});
EDIT:
That being said, I believe Select2 has a built in AJAX method that you can see in their tutorial.

Sending several JSON requests creates a 500 error

This JSON post works, but if I start clicking them quickly, they start returning 500 errors. I'm guessing this is because they're not queueing correctly, and they fall apart when they can't go out one by one. Is there a way to queue this in JSON?
Here's my button in HAML :
= f.check_box :has_sticker, :style => 'width: 20px;', :class => "orgs_deals_admin_save"
And here's my jQuery :
$('.orgs_deals_admin_save').live('click', function() {
var button = $(this);
var form = button.closest('form');
var dataString = form.serialize();
$.ajax({
url: form.attr('action') + '.json',
dataType: 'json',
type: 'POST',
data: dataString,
success: function(data) {
}
});
});
This is because per default asynchronous is set to true. If you want them to be processed in the exact same order you sent them, set asynchronous to false.
500 is server error problem code, so i suppose that there is some problem with processing your script on the server side

Categories

Resources