Submit checkbox state without a submit button - javascript

I have a view with a few checkboxes that can be selected or unselected. I'd like to always register any change in a checkbox, without the use of a submit button (the user could forget to do it, and it would waste time).
So, is there a way to handle this inside the view? Up to now, I've only used the controller to do that job.
So, a piece of code :
#ModelType MvcApplication.OpportuniteDetails
#Code
ViewData("Title")="Details"
#End Code
<script type="text/javascript">
$(function () {
$(':checkbox').change(function() {
$.ajax({
url: '#Url.Action("update")',
type: 'POST',
data: { isChecked: $(this).is(':checked') },
success: function (result) { }
});
});
});
</script>
[... Some code here...]
#Html.Raw("Mail sent?") #Html.CheckBox(Model.Opportunite.Mail)
<input type="checkbox" name="mail" id="mail" onclick="test()" />

You could use AJAX:
$(function() {
$(':checkbox').change(function() {
var form = $(this).closest('form');
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: form.serialize(),
success: function(result) {
}
});
});
});
In this example we subscribe to the change event of each checkbox. When this event is trigerred we look for the containing form and send its contents to the server using an AJAX request.
And if you only wanted to submit the current checkbox state to the server and not the entire form:
$(function() {
$(':checkbox').change(function() {
$.ajax({
url: '#Url.Action("SomeAction")',
type: 'POST',
data: { isChecked: $(this).is(':checked') },
success: function(result) {
}
});
});
});
where you could have a controller action which will do the necessary processing:
[HttpPost]
public ActionResult SomeAction(bool isChecked)
{
...
}

If you don't need or want AJAX and just want to submit the form, this
$(':checkbox').change(function() {
var form = $(this).closest('form');
form.get( 0 ).submit();
});
would do it.

Related

jQuery Ajax submitting form multiple times

I am new to Ajax. I am currently submitting a form into my database using jQuery AJAX but it sends the same data multiple times in my database.
Here's my Ajax code :
$(document).ready(function () {
var id_js;
$(document).on('click', '.btn-success', function () {
id_js = $('#ID_TXT').val();
$('form').submit(function (e) {
e.preventDefault();
e.stopImmediatePropagation();
$.ajax({
type: "POST",
url: 'server.php',
data: {
'Mark': 1,
'id': id_js,
},
success: function (response) {
$('#result').html(response);
}
});
return false;
});
});
});
Also I have tried .one() and .stopImmediatePropogation() but still no results
I see both form submit and Ajax call are doing the same work. If you are going to post the data only with AJAX call then form submit is not required.
I hope this works well for you.
$(document).ready(function () {
function postDataToServer() {
var id_js = $('#ID_TXT').val();
$.ajax({
type: "POST",
url: 'server.php',
data: {
'Mark': 1,
'id': id_js,
},
success: function (response) {
$('#result').html(response);
}
});
}
$(document).on('click', '.btn-success', postDataToServer);
});
The submit handler shouldn't be inside the click handler. Every time you click on the button, it adds another submit handler. So when you finally submit the form, it will submit it as many times as you clicked on the button.
If you want to ensure that the form isn't submitted until you've clicked on the button, add a test in the submit handler.
$(document).ready(function() {
var id_js;
$(document).on('click', '.btn-success', function() {
id_js = $('#ID_TXT').val();
});
$('form').submit(function(e) {
if (id_js !== undefined) {
$.ajax({
type: "POST",
url: 'server.php',
data: {
'Mark': 1,
'id': id_js,
},
success: function(response) {
$('#result').html(response);
}
});
} else {
alert("You need to click on the success button first");
}
return false;
});
});

Preventing refresh upon AJAX request

I have a form in my code, and I would simply like to display the fields from that form on my webpage, using AJAX. I tried e.preventDefault() and return false but none of these seem to be working.
I trigger the submit through a button click event.
My Jquery code:
$("body").on('click', '#save', function (e) {//button which triggers submit
$('form').submit();
e.preventDefault();
});
$('#form').on('submit', function(e){
e.preventDefault();
e.stopPropagation();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'POST',
url: '/results',
data: $('#form').serializeArray(),
success: function (data) {
//if no error from backend validation is thrown
return false;
$('#tabShow').html(data);
},
error: function () {
alert('error');
}
});
My form html is : <form class="form-horizontal" method="POST" action="/results" id="form">
In my web.php:
Route::post('/results', function() {
$m=Request::all();
var_dump($m);
});
The problem with this code is that it refreshes the current page that I am on.
I have a save button, which should submit the form. I can't use a type submit because of my other functions.
Thank you for the help.
Do the request in the Save button click event, eg.
HTML
<form id="contact-form" class="form-horizontal" action="/echo/html/" method="post">
<!-- many fields -->
<button id="save" class="btn btn-primary btn-lg">Submit</button>
</form>
JS
$("body").on('click', '#save', function (e) {//button which triggers
var contactForm = $('#contact-form');
e.preventDefault();
$.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader('X-CSRF-TOKEN', $('meta[name="csrf-token"]').attr('content'));
}
});
// Send a POST AJAX request to the URL of form's action
$.ajax({
type: "POST",
url: contactForm.attr('action'),
data: contactForm.serialize()
})
.done(function(response) {
console.log(response);
})
.fail(function(response) {
console.log(response);
});
});
Working demo
Try using return false at the end of your script (also remove preventDefault() )

Laravel & Ajax - Insert data into table without refreshing

First of all, I have to say that I'm beginner with using Ajax... So help me guys.
I want to insert the data into db without refreshing the page. So far, I have following code...
In blade I have a form with an id:
{!! Form::open(['url' => 'addFavorites', 'id' => 'ajax']) !!}
<img align="right" src="{{ asset('/img/icon_add_fav.png')}}">
<input type="hidden" name = "idUser" id="idUser" value="{{Auth::user()->id}}">
<input type="hidden" name = "idArticle" id="idArticle" value="{{$docinfo['attrs']['sid']}}">
<input type="submit" id="test" value="Ok">
{!! Form::close() !!}
And in controller I have:
public function addFavorites()
{
$idUser = Input::get('idUser');
$idArticle = Input::get('idArticle');
$favorite = new Favorite;
$favorite->idUser = $idUser;
$favorite->idArticle = $idArticle;
$favorite->save();
if ($favorite) {
return response()->json([
'status' => 'success',
'idUser' => $idUser,
'idArticle' => $idArticle]);
} else {
return response()->json([
'status' => 'error']);
}
}
I'm trying with ajax to insert into database:
$('#ajax').submit(function(event){
event.preventDefault();
$.ajax({
type:"post",
url:"{{ url('addFavorites') }}",
dataType="json",
data:$('#ajax').serialize(),
success: function(data){
alert("Data Save: " + data);
}
error: function(data){
alert("Error")
}
});
});
Also in my web.php I have a route for adding favorites. But when I submit the form, it returns me JSON response like this: {"status":"success","idUser":"15","idArticle":"343970"}... It actually inserts into the db, but I want the page not to reload. Just to display alert box.
As #sujivasagam says it's performing a regular post action. Try to replace your javascript with this. I also recognized some syntax error but it is corrected here.
$("#ajax").click(function(event) {
event.preventDefault();
$.ajax({
type: "post",
url: "{{ url('addFavorites') }}",
dataType: "json",
data: $('#ajax').serialize(),
success: function(data){
alert("Data Save: " + data);
},
error: function(data){
alert("Error")
}
});
});
You could just replace <input type="submit"> with <button>instead and you'll probably won't be needing event.preventDefault() which prevents the form from posting.
EDIT
Here's an example of getting and posting just with javascript as asked for in comments.
(function() {
// Loads items into html
var pushItemsToList = function(items) {
var items = [];
$.each(items.data, function(i, item) {
items.push('<li>'+item.title+'</li>');
});
$('#the-ul-id').append(items.join(''));
}
// Fetching items
var fetchItems = function() {
$.ajax({
type: "GET",
url: "/items",
success: function(items) {
pushItemsToList(items);
},
error: function(error) {
alert("Error fetching items: " + error);
}
});
}
// Click event, adding item to favorites
$("#ajax").click(function(event) {
event.preventDefault();
$.ajax({
type: "post",
url: "{{ url('addFavorites') }}",
dataType: "json",
data: $('#ajax').serialize(),
success: function(data){
alert("Data Save: " + data);
},
error: function(data){
alert("Error")
}
});
});
// Load items (or whatever) when DOM's loaded
$(document).ready(function() {
fetchItems();
});
})();
You are using button type "Submit" which usually submit the form. So make that as button and on click of that call the ajax function
Change your button type to type="button" and add onclick action onclick="yourfunction()". and just put ajax inside your funciton.
Replace input type with button and make onClick listener. Make sure you use this input id in onclick listener:
So:
$('#test').on('click', function(event){
event.preventDefault()
... further code
I would also change the id to something clearer.

Passing data from javascript to action method in asp.net MVC

I have placed a bootstrap toggle switch in my application
Now i want is to send the On and Off values to my action method
Bellow is my razor syntax
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset style="height:60px">
<legend style="text-align:center; font-size:large; font-family:'Times New Roman'; background-color:#C8E6C9; color:red">Remote On/Off</legend>
<input id="test_id" name="cmdName" type="checkbox" checked data-toggle="toggle">
</fieldset>}
For passing data to controller from JS i have searched many articles and found that ajax is the way to do it
Bellow is my script for ajax inside JS
<script>
var cmdName = '#Session["cmdName"]';
$("#test_id").on("change", function (event) {
if ($(this).is(":checked")) {
$.ajax({
url: '#Url.Action("MultiGraph")',
type: 'Post',
data: 'On',
success: function () {
alert(data)
}
});
} else {
$.ajax({
url: '#Url.Action("MultiGraph")',
type: 'Post',
data: 'Off',
success: function () {
alert(data)
}
});
}
}); </script>
I have also used session variable but getting null value in it
Bellow is my controller code
public ActionResult MultiGraph(string search, string start_date, string End_date, string cmdName, int? page)
{
//search contain serial number(s)
//cmdName is for input checkbox
}
Bellow is the image for my switch button
When i switch it to Off then this Off string should be sent to my action method and vise versa
Updated Code
After reading comments i have done the following changes to my code
I have added a new action method of type Post
[HttpPost]
public ActionResult ToggleSwitch (string search, string cmdName)
{
List<SelectListItem> items = new List<SelectListItem>();
var dtt = db.ADS_Device_Data.Select(a => a.Device_Serial_Number).Distinct().ToList();
foreach (var item in dtt)
{
if (!string.IsNullOrEmpty(item))
{
items.Add(new SelectListItem { Text = item, Value = item });
}
}
ViewBag.search = items;
return View();
}
Bellow are changes in my razor
$("#test_id").on("change", function (event) {
if ($(this).is(":checked")) {
$.ajax({
url: '#Url.Action("ToggleSwitch")',
type: 'Post',
data: '{"cmdName": "On"}',
success: function () {
alert(data)
}
});
} else {
$.ajax({
url: '#Url.Action("ToggleSwitch")',
type: 'Post',
data: '{"cmdName": "Off"}',
success: function () {
alert(data)
}
});
}
});
But still i get no alert message, when i inspect element i found this error
I am stuck to this problem from almost 2 days
Any help would be appreciated
You need to use the $ character to invoque jQuery functions and pass your data from page to controller with the same name you defined in the action method using Json notation:
'{"cmdName": "On"}',
$.ajax({
url: '#Url.Action("ToggleSwitch")',
type: 'Post',
data: '{"cmdName": "On"}',
success: function () {
alert(data)
}
Furthermore, you might need to decorate your mvc action whith the [HttpPost] attribute.

How to Reloading a partial view from the view?

In my ASP.NET MVC project i have the following situation:
An ExController with this action:
public ActionResult Index()
{
//Get Data from Repository
return View(Model);
}
In the Ex View folther i have a Index.cshtml and a _PartialIndexGrid.cshtml.
In the Index i have a ribbon menu with a checkbox, and when i click on it i would like to refresh just the grid placed on the _PartialIndex.cshtml, is it possible?
The Index View:
//Ribbon Code here
#Html.Partial("_PartialIndexGrid", Model)
<script>
if (e.parameter) {
$.ajax({
url: '#Url.Action("Index")',
type: "get",
success: function (result) {
$("_PartialIndexGrid").html(result);
},
failure: function () {
alert('error');
}
});
</script>
This script actually do the ajax request, but is not reloading the grid partial view.
Thanks.
Create a container div and on checkbox change check if its checked reload the partial view via ajax call like this:
<div id="PartiaContainer">
#Html.Partial("_PartialIndexGrid", Model)
</div>
<input type="checkbox" id="checkbox1"/>
<script>
$('#checkbox1').change(function(){
if(this.checked)
{
$.ajax({
url: '#Url.Action("Index")',
type: "get",
success: function (result) {
$("#PartialContainer").html(result);
},
failure: function () {
alert('error');
}
});
}
});
</script>

Categories