JQuery in MVC - Send form data as array with getJson - javascript

I have an MVC view which updates the elements on the page by using getJSON pointing at a method in my controller periodically and parsing the returned Json.
Method blueprint in controller:
public JsonResult GetAttendeeJson()
{
//Code which creates the Json I need.
return Json(result, JsonRequestBehavior.AllowGet);
}
Call from View:
function showDetects() {
// This is the main AJAX that retrieves the data.
$.getJSON('/Attendee/CardDetections', function (data) {
$.each(data, function (i, country) {
// perform actions using data.
});
});
}
It's not important to understand what I'm doing but my circumstances have changed and I have now added to my view a form containing a variable amount of checkboxes (depending on which user uses the page the number of checkboxes will be different).
Checkbox form creation:
<form onsubmit="#Url.Action("Index", "Attendee")" method="post" id="checkboxform">
#{int i = 0;}
#{foreach (string s in ViewBag.LocationNames)
{
<div class="radio-inline">
#s
<input class="checkboxcontrol" onchange="this.form.submit()" type="checkbox" id="CheckBoxes" name="CheckBoxes" value="#ViewBag.LocationIds[i]">
</div>
i++;
}
}
</form>
The addition of this form means I now require my controller method which returns the Json to be able to use the data of these checkboxes. The GetAttendeeJson now needs to know which checkboxes are currently checked on the form.
So I want the method blueprint to be like:
public JsonResult GetAttendeeJson(int[] checkBoxValues)
{
//Code which creates the Json I need using the checkbox values.
return Json(result, JsonRequestBehavior.AllowGet);
}
Is it possible to do this without submitting the form? I use the submit to do something else which leads to reloading the page. I use the getJson to just update page content.
Ideally I'd just like to get the Value field of the checked checkboxes in an array and send it to the GetAttendeeJson function as a parameter when calling it.
Thanks,
JK

Lets say you have following HTML -
<input type="checkbox" name="chk" value="1" /> 1
<input type="checkbox" name="chk" value="2" /> 2
<input type="checkbox" name="chk" value="3" /> 3
<input type="checkbox" name="chk" value="4" /> 4
<input type="button" id="submit" value="Submit"/>
Then we can push the checked checkboxes to an action method using AJAX POST as shown below -
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
$(function () {
$("#submit").click(function () {
var vals = [];
$('input:checkbox[name=chk]:checked').each(function () {
vals.push($(this).val());
});
$.ajax({
url: "/Home/GetAttendeeJson",
type: "post",
dataType: "json",
data: JSON.stringify({ checkBoxValues: vals }),
contentType: 'application/json; charset=utf-8',
success: function (result) {
if (result.success) {
}
else {
}
}
});
});
});
</script>
When we click on the button, the checked checkboxes can be obtained in following controller action -
public JsonResult GetAttendeeJson(int[] checkBoxValues)
{
//Code which creates the Json I need using the checkbox values.
return Json("true", JsonRequestBehavior.AllowGet)
}
View renders as follows where we can check/uncheck the checkboxes -
Then when you put a breakpoint and debug the code, output would be as shown below -

Try triggering ajax call periodically. So that without submitting form you can send it to your function.

Related

After reload the page checkbox should not reset

I am using Angular-Js and Jquery. I am implementing disable all checkboxes in the page after click on checkbox. But When I reload the page my page is reset, I don't want to reset disable checkboxes after reload. Suppose I checked checkbox after that reload the page checkbox should be checked.
Below is the code example.
$('#mainChk').on('click', function(){
var categories = $('.disableCheck');
categories.prop('disabled', !categories.prop('disabled'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="mainChk" type="checkbox" > Main
<input type="checkbox" class="disableCheck"> First
<input type="checkbox" class="disableCheck"> Second
<input type="checkbox" class="disableCheck"> Third
When I reload the page, All checkbox is reset.
I can use Angular-Js also. I set checkbox value in query parameter like true or false.
$location.search({ checkbox: disableCheck.prop('disabled') })
But I did not get desired output.
You can use something like sessionStorage or localStorage to save checkboxes' state after page reloading.
There is an angularjs library, that I use.
You also can find same thing for jQuery.
The best way is to call ajax on page load via API method though SELECT query of Save Table.
<input type="checkbox" class="disableCheck" value="First"> First
<input type="checkbox" class="disableCheck" value="Second"> Second
<input type="checkbox" class="disableCheck" value="Third"> Third
$(document).ready(function () {
$.ajax({
url: 'abc.asmx',// Call List Method of Save Checkbox Table
success: function (data) {
callback(data);
},
})
});
function callback(data) {
$.each(data.d, function (index, item) {
$("#checkboxId option[value='" + item.SaveCheckboxColumnName + "']").prop("checked",
true);
$("#checkboxId option[value='" + item.SaveCheckboxColumnName +
"']").prop("disabled",
true);
});
}

Return two database results with the one jQuery AJAX form (or response)

What I have:
I have a form that uses jQuery AJAX to query a database and returns a series of <option> elements that are appended to a <select> element.
What I need:
Using the same form, I need to run a second query on a different table in the same database which will determine which radio button is checked in a radio button group. A URN is sent via AJAX to return which radio button should be selected.
My code:
HTML:
<form type="post" method="post" action="<?php $_SERVER['PHP_SELF']; ?>" id="adddetailstoanexistingclient_form" name="adddetailstoanexistingclient_form">
<input type="hidden" id="sendingclienturn_js" name="sendingclienturn_js"/>
<select id="factivity_buildproject_a" name="factivity_buildproject_a">
<option selected="selected"></option>
<!--AJAX HTML RESULTS GO HERE-->
<option value = "Build / Project non-specific">Build / Project non-specific</option>
</select>
<input type="radio" name="factivity_prospectstrength" value="1" /> 1
<input type="radio" name="factivity_prospectstrength" value="2" /> 2
<input type="radio" name="factivity_prospectstrength" value="3" /> 3
<input type="radio" name="factivity_prospectstrength" value="4" /> 4
<input type="radio" name="factivity_prospectstrength" value="5" /> 5
<input type="hidden" name="action" value="buildorprojects_ajax"/>
</form>
jQuery/AJAX:
$('#sendingclienturn_js').on('change keyup paste input',ajaxSubmit);
function ajaxSubmit(){
var adddetailstoanexistingclient_form = $('#adddetailstoanexistingclient_form').serialize();
$.ajax({
type:"POST",
url: "<?php echo admin_url('admin-ajax.php'); ?>",
data: adddetailstoanexistingclient_form,
success:function(data){
if (!$.trim(data)){
$('#factivity_buildproject_a').hide();
$('[name=factivity_buildproject_ro]').show();
}
else{
$('#factivity_buildproject_a').show();
$('[name=factivity_buildproject_ro]').hide();
}
$("#factivity_buildproject_a option.filterable_option").remove();
$("#factivity_buildproject_a option:first").after(data);
},
error: function(errorThrown){
alert(errorThrown);
alert("There is an error with AJAX!");
}
});
return false;
}
PHP:
function buildorprojects_ajax(){
global $wpdb;
$sendingclienturn_js = $_POST['sendingclienturn_js'];
$query_buildsorprojects = $wpdb->get_results(
"
SELECT *
FROM wp_crm_bplist
WHERE clienturn = '$sendingclienturn_js'
AND deleted <> '1'
ORDER BY buildorproject, recorddateandtime DESC
"
);
if($query_buildsorprojects===FALSE){
echo "Error";
}
else {
foreach ( $query_buildsorprojects as $query_buildorproject ) {
echo '<option class="filterable_option" value="'.$query_buildorproject->recordurn.'" data-clienturn="'.$query_buildorproject->clienturn.'">'.$query_buildorproject->buildprojecturn.' - '.$query_buildorproject->buildorproject.' ('.$query_buildorproject->buildorprojecttype.')</option>';
}
}
die();
}
add_action('wp_ajax_buildorprojects_ajax', 'buildorprojects_ajax');
add_action('wp_ajax_nopriv_buildorprojects_ajax', 'buildorprojects_ajax');
What I've tried:
I've duplicated the above code (HTML, jQuery AJAX and PHP), changing the necessary titles of ids, names, functions and variables which works but at the cost of my first AJAX function failing.
I've deduced that the problem occurs when adding the second hidden field to my HTML code. The second AJAX form submission breaks the first.
i.e.
Works with one hidden field:
<input type="hidden" name="action" value="buildorprojects_ajax"/>
Does not work with second hidden field:
<input type="hidden" name="action" value="buildorprojects_ajax"/>
<input type="hidden" name="action" value="prospectstrength_ajax"/>
yes, you can encode two segments into one response. All you then need to do is to decode the response into two segments. This could be done with substr, but as this is AJAX, you're perhaps just looking to create an array and json_encode it, so you've to two strings after json decoding.
Alternatively:
If you want to share the same response with multiple segments of data you want to pass along, you can create multiple segments with the help of JSON and PHP's global static state.
JSON should be handy because most AJAX javascript routines offer to parse it directly.
Global static static on the other hand is used big time in Wordpress, so you won't break with that.
For example at different places you could add to the response:
function ajax_callback_red() {
...
JsonResponse::add('<options/>');
}
function ajax_callback_green() {
...
JsonResponse::add('<checkboxes/>');
}
When the request finishes, that JsonResponse (here statically accessed) the can turn such into JSON:
[
"<options\/>",
"<checkboxes\/>"
]
Such code can be quickly written. Either with a class destructor or you register some shutdown action:
class JsonResponse
{
static $instance;
private $segments = array();
/**
* conditionally assign class instance to global variable and
* return it.
*
* #return JsonResponse
*/
public static function getInstance() {
self::$instance || self::$instance = new self;
return self::$instance;
}
public static function add($segment) {
self::getInstance()->addSegment($segment);
}
public function addSegment($segment) {
$this->segments[] = $segment;
}
public function __destruct() {
echo json_encode($this->segments, JSON_PRETTY_PRINT);
die();
}
}
Hope this helps.
Your approach of setting the action with hidden fields is flawed. If you need to run two queries on each change, keyup, paste, or input, then try something like
$('#sendingclienturn_js').on('change keyup paste input',function(){
ajaxSubmit('buildorprojects');
ajaxSubmit('prospectstrength');
});
function ajaxSubmit(action){
type:"POST",
url: "admin-ajax.php?action="+action,
data: [pull in the correct data for the action],
Better yet, if these two requests are always done together, you really need only one request and for your PHP to run the two actions and return a single object. Like Hakre says in his comment, you have the power, use it.

requesting a server by checking/unchecking checkboxes

I'm trying to code a web page that contains two checkboxes and to send a request to my web server for each check/uncheck. I have to check at server side which checkboxes are checked and which are not to make some specific operations.
Form (snippet of code) :
<form method="get" action="#Url.Action("Index")" data-monitoring-ajax="true" data-monitoring-target="#ListeAlertes">
<input type="checkbox" name="affiche" value="fixees" id="fixees" style="margin-left:40px;margin-right:3px;" checked /> Alertes fixées
<input type="checkbox" name="affiche" value="nonFixees" id="nonFixees" style="margin-left:10px;margin-right:3px;" checked /> Alertes non-fixées
</form>
monitoring.js
$(function () {
var ajaxFormSubmit = function () {
var $form = $(this);
var options = {
url: $form.attr("action"),
type: $form.attr("method"),
data: $form.serialize()
};
$.ajax(options).done(function (data) {
var $target = $($form.attr("data-monitoring-target"));
$target.replaceWith(data);
});
return false;
}
$("form[data-monitoring-ajax='true']").submit(ajaxFormSubmit);
});
Note : I've included monitoring.js into the web page.
Any brilliant idea, please ?
Since the options seem to represent the same item just in a different state, you really only need one checkbox.
The Html
<input type="checkbox" id="enableAlerts" style="margin-left:40px;margin-right:3px;" /> Alertes fixées
The javascript (jQuery)
With this, you can subscribe to the change event to know when to send the request to the server.
$("#enableAlerts").change(function(){
$.post("/Controller/UpdateAlerts",
{ enableAlerts: this.checked },
function(data){ console.log("Successfully saved user options!"); });
});
In the above script we listen for the change event to fire and when it does, we post our data to the server so it can process it. If the server returns a 200 status code, it will write to the console that it was successful. Since only one checkbox is being sent, there isn't any reason to wrap the checkbox in a form and serialize the form to send to the server.
The Server code
Now all you need is a controller/action to call to update the option on the server.
[HttpPost]
public HttpStatusCodeResult UpdateAlerts(bool enableAlerts)
{
//Save to database
return new HttpStatusCodeResult(HttpStatusCode.OK);
}
The above code allows the javascript code to post the data to the server. In this case I allowed the value to be nullable and default to false if so. After that, do what you need to and return a response code so the client-side code can inform the user of the status of their request.
In response to comment by user
In this case wrapping it in a form would be correct. The majority of the steps are similar with minor modifications.
Html
<form method="post" id="filterOptions">
<input type="checkbox" name="Checkbox1" value="true" />
<input type="checkbox" name="Checkbox2" value="true" />
</form>
Javascript
$("#filterOptions input[type='checkbox']").change(function () {
var form = $("#filterOptions").serialize();
$.post("/Controller/AjaxFilteredList",
form,
function (data) { console.log("Retrieved data successfully!") });
});
The Model
public class MyModel
{
public bool Checkbox1 { get; set; }
public bool Checkbox2 { get; set; }
}
The model's property names must match the name of the property, case-insensitive. This is made easier if you make this a ViewModel and pass it into the repective View and use Html.CheckboxFor(m => m.Checkbox1) to render the checkbox.
The controller action
[HttpPost]
public ActionResult AjaxFilteredList(MyModel model)
{
//check you viewmodel's variables to get your list
return PartialView("_FilteredList", filteredList);
}
The above assumes you have a partial view named "_FilteredList" and a variable named "filteredList" in-scope with the results you want to render.
Use .change()
$("form[data-monitoring-ajax='true'] input[type='checkbox']").change(function(){
//make your Ajax Call here and send name of the checkbox or id of the checkobox
});
Attribute Equals Selector [name="value"]

How to submit a form with specific fieldset

I have a form like this:
<form name="paymentForm" id="paymentForm" action="/submit.jsp" method="post">
<fieldset id="ccData">
<input id="ccNumber" name="ccNumber"/>
</fieldset>
<fieldset id="otherData">
<input id="requestId" name="requestId"/>
</fieldset>
</form>
When you slick submit, I would like to submit(via ajax) only #ccData filedset to some different url (e.g. submitCC.jsp) and based on response I want to submit full form to actual url.
How can I achieve that ?
Use jQuery's serialize method
var formData = $("#ccData").serialize()​;
$.post("TheUrl",formData);
You could do that with JavaScript - e.g jQuery. You build an eventHandler like
$('#paymentForm').on('click', function () {
$(this).preventDefault();
if ($(this).hasClass('first_send')) {
$.ajax({
url: "your_url",
data: { ccData: $('#ccData').val()}
}).done(function ( data ) {
$('#paymentForm').addClass('first_send')
// examin the data, insert stuff you need and send the form again
// with ajax
})
} else {
$(this).removeClass('first_send')
// this is the second send - so do stuff here - show a result or so
}
})
With the class first_send you can check if it is the first send or the second. This is just an untested, incomplete idea how you could do it. I guess you get the big picture ...

How to pass multiple checkboxes using jQuery ajax post

How to pass multiple checkboxes using jQuery ajax post
this is the ajax function
function submit_form(){
$.post("ajax.php", {
selectedcheckboxes:user_ids,
confirm:"true"
},
function(data){
$("#lightbox").html(data);
});
}
and this is my form
<form>
<input type='checkbox' name='user_ids[]' value='1'id='checkbox_1' />
<input type='checkbox' name='user_ids[]' value='2'id='checkbox_2' />
<input type='checkbox' name='user_ids[]' value='3'id='checkbox_3' />
<input name="confirm" type="button" value="confirm" onclick="submit_form();" />
</form>
From the jquery docs for POST (3rd example):
$.post("test.php", { 'choices[]': ["Jon", "Susan"] });
So I would just iterate over the checked boxes and build the array. Something like
var data = { 'user_ids[]' : []};
$(":checked").each(function() {
data['user_ids[]'].push($(this).val());
});
$.post("ajax.php", data);
Just came across this trying to find a solution for the same problem. Implementing Paul's solution I've made a few tweaks to make this function properly.
var data = { 'venue[]' : []};
$("input:checked").each(function() {
data['venue[]'].push($(this).val());
});
In short the addition of input:checked as opposed to :checked limits the fields input into the array to just the checkboxes on the form. Paul is indeed correct with this needing to be enclosed as $(this)
Could use the following and then explode the post result explode(",", $_POST['data']); to give an array of results.
var data = new Array();
$("input[name='checkBoxesName']:checked").each(function(i) {
data.push($(this).val());
});
Here's a more flexible way.
let's say this is your form.
<form>
<input type='checkbox' name='user_ids[]' value='1'id='checkbox_1' />
<input type='checkbox' name='user_ids[]' value='2'id='checkbox_2' />
<input type='checkbox' name='user_ids[]' value='3'id='checkbox_3' />
<input name="confirm" type="button" value="confirm" onclick="submit_form();" />
</form>
And this is your jquery ajax below...
// Don't get confused at this portion right here
// cuz "var data" will get all the values that the form
// has submitted in the $_POST. It doesn't matter if you
// try to pass a text or password or select form element.
// Remember that the "form" is not a name attribute
// of the form, but the "form element" itself that submitted
// the current post method
var data = $("form").serialize();
$.ajax({
url: "link/of/your/ajax.php", // link of your "whatever" php
type: "POST",
async: true,
cache: false,
data: data, // all data will be passed here
success: function(data){
alert(data) // The data that is echoed from the ajax.php
}
});
And in your ajax.php, you try echoing or print_r your post to see what's happening inside it. This should look like this. Only checkboxes that you checked will be returned. If you didn't checked any, it will return an error.
<?php
print_r($_POST); // this will be echoed back to you upon success.
echo "This one too, will be echoed back to you";
Hope that is clear enough.
This would be better and easy
var arr = $('input[name="user_ids[]"]').map(function(){
return $(this).val();
}).get();
console.log(arr);
The following from Paul Tarjan worked for me,
var data = { 'user_ids[]' : []};
$(":checked").each(function() {
data['user_ids[]'].push($(this).val());
});
$.post("ajax.php", data);
but I had multiple forms on my page and it pulled checked boxes from all forms, so I made the following modification so it only pulled from one form,
var data = { 'user_ids[]' : []};
$('#name_of_your_form input[name="user_ids[]"]:checked').each(function() {
data['user_ids[]'].push($(this).val());
});
$.post("ajax.php", data);
Just change name_of_your_form to the name of your form.
I'll also mention that if a user doesn't check any boxes then no array isset in PHP. I needed to know if a user unchecked all the boxes, so I added the following to the form,
<input style="display:none;" type="checkbox" name="user_ids[]" value="none" checked="checked"></input>
This way if no boxes are checked, it will still set the array with a value of "none".
function hbsval(arg) {
// $.each($("input[name='Hobbies']:checked"), function (cobj) {
var hbs = new Array();
$('input[name="Hobbies"]:checked').each(function () {
debugger
hbs.push($(this).val())
});
alert("No. of selected hbs: " + hbs.length + "\n" + "And, they are: " + hbs[0] + hbs[1]);
}

Categories

Resources