Sending data using ajax to the controller in rails - javascript

I am new to JS and rails so recently facing lots of difficulties about using ajax in rails environment. I will very appreciate if you contribute to developing my project. What I am trying to do is that Once a user selects data from the modal, I want to send the selected data to an action in the controller so that I can handle the data. I am not really sure where I can start with that. Please help guys :( Thanks a lot
view:
<form id= "selected_form" action="" method="">
<div id= "selected_form">
<p id="checkids"></p>
</div>
</form>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<div>
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Select Task</h4>
</div>
<div class="modal-body">
<fieldset>
<% #tasks.each do |task|%>
<div>
<label><input type="checkbox" value="<%=task.id%>" name="selected"><%=task.title%></label>
</div>
<% end %>
</fieldset>
</div>
<div class="modal-footer">
<button type="button" id="save" class="btn btn-default" data-dismiss="modal">Save</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
</div>
JS
<script>
$(function(){
$(document).ready(function(){
$("#save").click(function(){
var checkedItem = [];
$.each($("input[name='selected']:checked"), function(){
checkedItem.push($(this).val());
});
$('#values').html("selected values are: " + checkedItem.join(", "));
$.ajax({
type: "POST", // request method for your action like get,post,put,delete
url: "/users/<%= current_user.id %>/test", // route of your rails action
data: {checked_items: checkedItem.join(", ")}, // attach data here you will get this data in your controller action with params[:checked_items]
success: function(data, textStatus, jqXHR){}, // do whatever you want when it success
error: function(jqXHR, textStatus, errorThrown){}
})
});
});
});
</script>

Please check script below
<script>
$(function(){
$(document).ready(function(){
$("#save").click(function(){
var checkedItem = [];
$.each($("input[name='selected']:checked"), function(){
checkedItem.push($(this).val());
});
$('#values').html("selected values are: " + checkedItem.join(", "));
$.ajax({
type: "POST", // request method for your action like get,post,put,delete
url: "/things", // route of your rails action
data: {checked_items: checkedItem }, // attach data here you will get this data in your controller action with params[:checked_items]
success: function(data, textStatus, jqXHR){...}, // do whatever you want when it success
error: function(jqXHR, textStatus, errorThrown){...}
})
});
});
});
</script>

For simplicity you can inject rails path to that controller as dataset attribute.
for e.g
<form method="post" data-url="<%= tasks_path %>">
and in js part
$('#save').on('click', function (e) {
e.preventDefault();
$.ajax({
type: $(this).method || "GET",
url: this.dataset.url,
data: $(this).serialize(),
success: function (response) {
console.log(response)
},
error: function (error) {
console.log(error);
}
});
});

Related

Why my ajax post is not working codeigniter? The page is refreshing

// save new employee record
$('#saveEmpForm').submit('click',function(){
var empInputId = $('#input_id').val();
var empJenis = $('#jenis').val();
var empJarak = $('#jarak').val();
$.ajax({
type : "POST",
url : "InputPembangunan/save",
dataType : "JSON",
data : {input_id:empInputId, jenis:empJenis, jarak:empJarak },
success: function(data){
$('#jenis').val("");
$('#jarak').val("");
$('#addEmpModal').modal('hide');
alert('Successfully called');
listEmployee();
},
error: function(jqxhr, status, exception) {
alert('Exception:', exception);
}
});
return false;
});
<form id="saveEmpForm" method="post">
<div class="modal fade" id="addEmpModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Add New Employee</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="form-group row">
<label class="col-md-2 col-form-label">Jenis</label>
<div class="col-md-10">
<input type="text" name="jenis" id="jenis" class="form-control" required>
<input type="hidden" id="input_id" name="input_id" class="form-control " value="{$input_id}">
</div>
</div>
<div class="form-group row">
<label class="col-md-2 col-form-label">Jarak</label>
<div class="col-md-10">
<input type="text" name="jarak" id="jarak" class="form-control" required>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save</button>
</div>
</div>
</div>
</div>
</form>
Save function in controller file
public function save(){
$data=$this->inputs_model->saveEmp();
echo json_encode($data);
}
Save function in Model
public function saveEmp(){
$data = array(
'input_id' => $this->input->post('input_id'),
'jenis' => $this->input->post('jenis'),
'jarak' => $this->input->post('jarak'),
'created_at' => date("Y-m-d h:i:sa"),
'updated_at' => date("Y-m-d h:i:sa")
);
$result=$this->db->insert('input_jenis_industri',$data);
return $result;
}
The code are as stated above, my ajax function to save the data is not working. It is not saving the data in the db. What can cause the problem?
My ajax function calls the InputPembangunan/save to save the data, then the controller try to the save data using the save() function. It is saved using the model saveEmp()
The following is incorrect, there is no click involved in a submit event
$('#saveEmpForm').submit('click',function(){
Change to
$('#saveEmpForm').submit(function(event){
event.preventDefault()// prevent normal form submit
without refreshing the page you have to call event.preventDefault() method after submit event.
replace this
$('#saveEmpForm').submit('click',function(){
with
$('#saveEmpForm').on('submit',function(){
event.preventDefault()
Change this
<button type="submit" class="btn btn-primary">Save</button>
to
<button type="button" class="btn btn-primary">Save</button>
You can onlick() method. Actually I used like this;
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" onclick="save()" class="btn btn-primary">Save</button>
</div>
than add jquery
function save() {
// ajax adding data to database
var formData = new FormData($('#form')[0]);
$.ajax({
URL: "<?php echo site_url('InputPembangunan/save')?>",
type: "POST",
data: formData,
contentType: false,
processData: false,
dataType: "JSON",
success: function(data) {
if(data.status) //if success close modal and reload ajax table
{
$('#modal_form').modal('hide');
reload_table();
} else {
//do something
}
},
error: function(jqXHR, textStatus, errorThrown) {
//do error form
}
});}
Use the following way,
$( "#saveEmpForm" ).submit(function( event ) {
event.preventDefault();
/** Your Existing Code ***/
var empInputId = $('#input_id').val();
var empJenis = $('#jenis').val();
var empJarak = $('#jarak').val();
$.ajax({
type : "POST",
url : "InputPembangunan/save",
dataType : "JSON",
data : {input_id:empInputId, jenis:empJenis, jarak:empJarak },
success: function(data){
$('#jenis').val("");
$('#jarak').val("");
$('#addEmpModal').modal('hide');
alert('Successfully called');
listEmployee();
},
error: function(jqxhr, status, exception) {
alert('Exception:', exception);
}
});
return false;
/** Your Existing Code ***/
});
Also, you can check the jQuery reference from this link:
https://api.jquery.com/submit/#submit
Replace
$('#saveEmpForm').submit('click',function(){
with
$(document).off('submit','#saveEmpForm').on('submit','#saveEmpForm',function(event) {
event.preventDefault(); //to prevent default submit action
...rest of the code
})
also check for any errors on the browser dev tool

Upload an image using a modal

I want to upload an image using modal. I know how to to that using an HTML form, but I am not sure how to use an ajax request to send data to the controller. Is it possible to use the controller that I have now? Thanks in advance!
The controller:
public function postCreatePost(Request $request)
{
...
$post->longitude = $request['longitude'];
if($request->user()->posts()->save($post))
{
$message = 'Post Successful';
};
$file = $request->file('image');
$filename = $post->id.'.jpg';
if($file)
{
Storage::disk('local')->put($filename, File::get($file));
}
return redirect()->route('dashboard')->with(['message' => $message]);
}
The ajax request that I have so far:
$('#modal-save').on('click',function(){
//create ajax request
$.ajax({
method: 'POST',
url: urlEdit, //url route is defined in the dashboard html script
//pass the post content and id to body and postId which will be used in the Post controller edit method
//need the token to avoid error
data: {body: $('#post-content').val(), postId: postId, _token: token}
})
.done(function (msg){
//console.log(msg['message']);
//console.log(JSON.stringify(msg));
$(postBodyElement).text(msg['new_content']); //update the post w/o refreshing the page
$('#edit-post').modal('hide'); //hide the modal
})
});
The modal:
<div class="modal" tabindex="-1" role="dialog" id="edit-post">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Edit Post</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form enctype="multipart/form-data">
<div class="form-group">
<label for="post-content">Edit Post</label>
<textarea class="form-control" name="post-content" id="post-content" rows="5"></textarea>
{{-- copy meta data using jquery?--}}
{{-- add a separate image form here--}}
<label for="image">Image (jpg only)</label>
<input type="file" name="image" class="form-control" id="image">
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" id="modal-save">Save changes</button>
</div>
</div>
</div>
</div>
The controller looks fine. But you are not passing the image:
Try this
$('#modal-save').on('click',function(){
//create ajax request
$.ajax({
method: 'POST',
url: urlEdit, //url route is defined in the dashboard html script
//pass the post content and id to body and postId which will be used in the Post controller edit method
//need the token to avoid error
data: {
body: $('#post-content').val(),
postId: postId,
_token: token,
image:$('#image').val()
}
})
.done(function (msg){
//console.log(msg['message']);
//console.log(JSON.stringify(msg));
$(postBodyElement).text(msg['new_content']); //update the post w/o refreshing the page
$('#edit-post').modal('hide'); //hide the modal
})
});
You can then get the image in the controller:
if( $request->hasFile('image') ) {
$file = $request->file('image');
$name = time().$file->getClientOriginalName();
$file->move(public_path().'/images/', $name);
}
You are not sending an image to the server end. Please use the formData object to send media to the server.
/** New form data object */
var formData = new FormData();
/** append post content */
formData.append('postcontent', $('#post-content').val());
/** append post id */
formData.append('postId', postId);
/** append token */
formData.append('_token', token);
/** append image */
formData.append('image', $("input[type=file]")[0].files[0]);
In your ajax call send formData in data
$.ajax({
method: 'POST',
url: urlEdit,
data: formData,
cache: false,
contentType: false,
processData: false
}).done(function (msg){
$(postBodyElement).text(msg['new_content']);
$('#edit-post').modal('hide'); //hide the modal
})

serialized form not sending ajax

I'm having trouble to send a serialized form through ajax to a php file. I can see the string on the client side, but on the server side I receive an empty array.
I'm trying to save the form data into a database, but a I can't seem to find a way to separate every input, and show it in my php file after I sent with ajax.
JavaScript
$(function() {
//twitter bootstrap script
$("button#guardar").click(function(e) {
//var info = $('#myform').serialize();
var info = $('form.contact').serialize();
$.ajax({
type: "POST",
url: "solicitudesProc.php",
data: info,
success: function(data) {
alert(info);
window.location.href = "solicitudesProc.php";
//window.location.reload();
$("#modalnuevo").modal('hide');
},
error: function(data) {
alert("failure");
}
});
});
});
<form class="contact" id="myform" method="post" name='alta'>
<div class="modal-body">
<div class="row">
<div class="col-md-2">
<label>Solicitante</label>
<input type="text" class="form-control pull-right" name='solicitante' maxlength="20" required />
</div>
<div class="col-md-2">
<label>Fecha Emision</label>
<input type="text" class="form-control pull-right" name='fechaEmision' maxlength="20" />
</div>
</div>
<div class="row">
<div class="col-md-2">
<label>Area Solicitante</label>
<input type="text" class="form-control pull-right" name='area' maxlength="20" />
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
<button type="submit" id="guardar" name='guardar' class="btn btn-danger pull-right" value="guardar">Generar</button>
</div>
</form>
server side solicitudesProc.php
<?php $info = $_POST;
echo $_POST["solicitante"]; print_r($_POST); ?>
Do not change location
Cancel the submit
I strongly suggest you either remove the form OR wire up the submit event:
$(function() {
$("form.contact").on("submit", function(e) {
e.preventDefault(); // stop the submit
var info = $(this).serialize();
$.ajax({
type: "POST",
url: "solicitudesProc.php",
data: info,
success: function(data) {
console.log(info);
$("#modalnuevo").modal('hide');
},
error: function(data) {
alert("failure");
}
});
});
});
I maked it work by doing this changes:
change the form action to the php file im sending.
<form action="solicitudesProc.php" class="contact" id="myform" method="post" name='alta' >
and my ajax changed to:
var info = $('#myform').serialize();
//var info = $('form.contact').serialize();
$.ajax({
type: "POST",
url: form.attr("action"),
data: $("#myform input").serialize(),
success: function(data){
//console.log(info);
window.location.href = "solicitudes.php";
//window.location.reload();
$("#modalnuevo").modal('hide');
},
error: function(data){
alert("failure");
}
});
});
});
Thanks for your help!

Select2 - not working in bootstrap 3 with tabindex removed?

Select2 has this bug where it refuses to work properly in a Bootstrap 3 modal unless one removes the tabindex element from the modal. I have done so with several modals on my page and they all work, however, there is one where I cannot get Select2 to activate at all.
I have a list of department names and positions which is displayed in a table, each row has its own "EDIT" button that calls up the modal to display the record details. The modal-body is empty but upon load is populated via AJAX.
I am using another select2 field on the same page (not inside that modal, but the main table) which is working well, just the select2 in this modal doesnt seem to work...
My thought is that due to the AJAX interaction, I might have to refresh select2 or load it before / after the modal is populated, but neither has yielded any results so far.
Any suggestions please?
PHP
<!-- Modal EditDepartmentModal -->
<div class="modal fade" id="EditDepartmentModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Edit Department Record</h4>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" id="SaveDepartmentButton" name="SaveDepartmentButton" class="btn btn-primary">Save Changes</button>
<button type="button" id="DeleteDepartmentButton" name="DeleteDepartmentButton" class="btn btn-danger">Delete Record</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- /.Modal EditDepartmentModal -->
AJAX:
<!-- JavaScript for Modal -->
<script type="text/javascript">
//Initialize Select2 Elements
$(function () {
$(".select2").select2();
});
// VIEW DEPARTMENT RECORD
$('#EditDepartmentModal').on('show.bs.modal', function(e) {
var modal = $(this);
var dataDeptName = $(e.relatedTarget).data('dname');
$.ajax({
type: "POST",
url: "../../plugins/MySQL/ajax_action.php",
data: { action:"view_department",Department_Name:dataDeptName}, // form data to post goes here as a json object
//dataType: "html",
//async: true,
cache: false,
success: function (data) {
console.log(data);
modal.find('.modal-body').html(data);
},
error: function(err) {
console.log(err);
},
});
});
</script>
AJAX return:
echo "
<!-- ID No. -->
<label>ID No.:</label>
<div class=\"input-group\">
<span class=\"input-group-addon\"><i class=\"fa fa-database\"></i></span>
<input type=\"number\" class=\"form-control\" id=\"dataDeptID\" name=\"dataDeptID\" size=\"5\" value=\"$dept_id\" disabled />
</div>
<!-- /.id number -->
<p> </p>
<!-- Department -->
<label>Department Name:</label>
<div class=\"input-group\">
<span class=\"input-group-addon\"><i class=\"fa fa-bars\"></i></span>
<input type=\"text\" class=\"form-control\" id=\"dataDeptName\" name=\"dataDeptName\" value=\"$dept_name\" />
</div>
<!-- /.department -->
<p> </p>
<!-- Positions -->
<label>Department Positions:</label>
<div class=\"input-group\">
<span class=\"input-group-addon\"><i class=\"fa fa-briefcase\"></i></span>
<select class=\"form-control select2\" style=\"width:100%;\" id=\"test\" name=\"test\">
<option value=\"1\">Option 1</option>
<option value=\"2\">Option 2</option>
<option value=\"3\">Option 3</option>
<option value=\"4\">Option 4</option>
</select>
</div>";
The code is working alright, its just select2 that doesnt want to show up -.-
Again, if I read this right, the html is contained in the ajax return so you cannot call the select2 on it until after that so try this...
<script type="text/javascript">
//Initialize Select2 Elements
$(function () {
// VIEW DEPARTMENT RECORD
$('#EditDepartmentModal').on('show.bs.modal', function(e) {
var modal = $(this);
var dataDeptName = $(e.relatedTarget).data('dname');
$.ajax({
type: "POST",
url: "../../plugins/MySQL/ajax_action.php",
data: { action:"view_department",Department_Name:dataDeptName}, // form data to post goes here as a json object
//dataType: "html",
//async: true,
cache: false,
success: function (data) {
console.log(data);
modal.find('.modal-body').html(data);
$(".select2").select2();
},
error: function(err) {
console.log(err);
},
});
});
});
</script>

get data From Bootstrap 3 modal form with jquery ajax

i wrote this to get form data and post it to a php page and do some proccess and get back a result to me,i start with getting post data from my bootstrap modal form and i found that the script can't take values from modal form,because the php part i can't upload it to fiddle or somewhere else.
i upload it on my server for rapid review
click on compose;
complete the fields
and when Send button clicked it expect to modal form sent some value to jquery ajax(on submit) but nothing sent from modal inputs to ajax and the whole $_POST array remain null,and whats going on?
hours and hours i searched for doc's and example's,but i couldn't found any answer,some examples works with bootstrap 2,and nothing for the bootstrap 3.
bootstrap 3.3.1,jquery 2.1.1
here is the modal code:
<div class="modal fade" id="largeModal" tabindex="-1" role="dialog" aria-labelledby="largeModal" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Compose</h4>
</div>
<div class="modal-body">
<form id="sendmail" data-async method="post" role="form" class="form-horizontal">
<div class="form-group">
<label class="col-sm-2" for="inputTo">To</label>
<div class="col-sm-10">
<input type="email" class="form-control" id="inputTo" placeholder="comma separated list of recipients">
</div>
</div>
<div class="form-group">
<label class="col-sm-2" for="inputSubject">Subject</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputSubject" placeholder="subject">
</div>
</div>
<div class="form-group">
<label class="col-sm-12" for="inputBody">Message</label>
<div class="col-sm-12">
<textarea class="form-control" id="inputBody" rows="18"></textarea>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary" value="Submit">Send</button>
<div id='response'></div>
</div>
</form>
</div>
</div>
</div>
jQuery:
$(document).ready(function () {
$('#sendmail').submit(function () {
$('#response').html("<b>Loading response...</b>");
$.ajax({
type: 'POST',
url: 'proccess.php',
data: $(this).serialize()
})
.done(function (data) {
$('#response').html(data);
})
.fail(function () {
alert("Posting failed.");
});
return false;
});
});
Simple PHP Code:
print_r($_POST);
In your code, this which is provided inside the $.ajax method's object refers ajax object. And it seems that you need to refer to the form from which you have to get the data and serialise it and send it into AJAX request.
Try following code,
$(document).ready(function () {
$('#sendmail').submit(function () {
var that = this;
$('#response').html("<b>Loading response...</b>");
$.ajax({
type: 'POST',
url: 'proccess.php',
data: $(that).serialize()
})
.done(function (data) {
$('#response').html(data);
})
.fail(function () {
alert("Posting failed.");
});
return false;
});
});
here I have referred the form object this by assigning it to that

Categories

Resources