Knockoutjs foreach with if inside table - javascript

I have a foreach creating a table in one of my pages. My goal is when they checked the checkbox I would show additional elements for that table
My issue is when the table is first drawn everything works as expected. But if i check a checkbox after the table is drawn the ko if statement does not reevaluate. What is the best method to accomplish this goal? My current code is below.
<tbody data-bind="foreach: AvailableCerts">
<tr>
<td>
<label class="label-checkbox inline">
<input type="checkbox" data-bind="value: Id, checked: IsSelected">
<span class="custom-checkbox"></span>
<span data-bind="text:Name"></span>
</label>
</td>
<td data-bind="text:CertifyingBody"></td>
<td>
<!-- ko if: (IsSelected) -->
<input data-bind="value : EntryDate" required type="date" class="form-control input-sm">
<!-- /ko -->
</td>
<td>
<!-- ko if: ExitDateRequired -->
<input data-bind="value : ExitDate" required type="date" class="form-control input-sm">
<!-- /ko -->
</td>
<td>
<!-- ko if: CaseNumberRequired -->
<input data-bind="value : CaseNumber" required type="text" class="form-control input-sm">
<!-- /ko -->
</td>
</tr>
</tbody>
And my viewModel
function AppViewModel() {
var self = this;
self.rootUrl = window.location.protocol + "//" + window.location.host + "/Certs/";
self.AvailableCerts = ko.observableArray([]);
self.getAvailableCerts = function () {
$.ajax({
url: self.rootUrl + "AvailableCerts",
type: "GET",
cache: false,
dataType: "json",
success: function (results) {
if (results != null) {
self.AvailableCerts(results);
} else {
self.AvailableCerts([]);
}
}
});
};
self.getAvailableCerts();
}
ko.applyBindings(new AppViewModel());

The contents of the ko.observableArray AvailableCerts are not observable by default. If you plan on working with the data after downloading it, you need to make the data for each of the certs observable as well. So, something like this in your Ajax call:
self.getAvailableCerts = function () {
$.ajax({
url: self.rootUrl + "AvailableCerts",
type: "GET",
cache: false,
dataType: "json",
success: function (results) {
if (results != null) {
for (var i = 0; i < results.length; i++) {
self.AvailableCerts().push({
'IsSelected': ko.observable(results[i].IsSelected),
'ExitDateRequired': ko.observable(results[i].ExitDateRequired),
'CaseNumberRequired': ko.observable(results[i].CaseNumberRequired)
});
}
} else {
self.AvailableCerts([]);
}
}
});
};
Or checkout the mappings plugin.

Related

How to send data from view to controller laravel with ajax?

I have problem to send data from view to controller laravel version 7
i send data from form and ul li
i have array data in javascript
my html code is :
I have problem to send data from view to controller laravel version 7
i send data from form and ul li
i have array data in javascript
<ul name="ali" id="singleFieldTags" class="tagit ui-widget ui-widget-content ui-corner-all">
<li class="tagit-choice ui-widget-content ui-state-default ui-corner-all tagit-choice-editable">
<span class="tagit-label">reza</span>
<a class="tagit-close">
<span class="text-icon">×</span>
<span class="ui-icon ui-icon-close"></span>
</a>
</li>
<li class="tagit-choice ui-widget-content ui-state-default ui-corner-all tagit-choice-editable">
<span class="tagit-label">ali</span>
<a class="tagit-close">
<span class="text-icon">×</span>
<span class="ui-icon ui-icon-close"></span>
</a>
</li>
<li class="tagit-new">
<input type="text" class="ui-widget-content ui-autocomplete-input" autocomplete="off">
</li>
</ul>
<form id="form" method="post" action="/save_new" enctype="multipart/form-data">
#csrf
<div class="form-group">
<label for="title">title</label>
<input type="text" name="title" class="form-control">
</div>
<div class="form-group">
<label for="choose-file" class="custom-file-upload" id="choose-file-label">
Click Here to upload image
</label>
<br/>
<br/>
<label >no image selected !</label>
<input name="uploadDocument" type="file" id="choose-file"
accept=".jpg,.jpeg,.pdf,doc,docx,application/msword,.png" style="display: none;" />
</div>
<div class="form-group">
<label for="title">Description</label>
<textarea name="meta_description" class="form-control"></textarea>
</div>
<div class="form-group">
<label >keywords</label>
<input name="tags" id="mySingleField" value="reza,ali" type="hidden" disabled="true">
<ul name="ali" id="singleFieldTags"></ul>
</div>
<button type="submit" onclick="myF()" class="btn btn-success pull-left"> save</button>
</form>
in my javascript
<Script type="text/javascript">
function myF() {
var data2 = [];
var inputs = $(".tagit-choice");
for (var i = 0; i < inputs.length; i++) {
data2[i] = $(inputs[i]).text();
}
$.ajax({
url:'/save_new',
type: 'POST',
dataType:'json',
// data: JSON.stringify(data2),
data: JSON.stringify(data2),
contentType: 'application/json; charset=utf-8',
success: function( data ){
console.log('ok');
console.log(data);
},
error: function (xhr, b, c) {
console.log('error');
console.log("xhr=" + xhr + " b=" + b + " c=" + c);
}
});
}
when i send data from ajax i have error in console
error reza:263:37
xhr=[object Object] b=error c=
but in Request JSON
i see
0 "reza×"
1 "ali×"
Please help me Thanks
my controller is :
public function save_new(Request $request){
// dd($request->all());
dd($request->getContent());
}
my route is :
Route::POST('/save_new','Backend\AdminPostController#save_new')->name('save_new');
edit:
my problem is solved thans you all
var fd = new FormData();
var file = $("#form input[name=uploadDocument]")[0].files;
fd.append('file', file[0]);
fd.append('title', $("#form input[name=title]").val());
fd.append('description', $("#form textarea[name=meta_description]").val());
fd.append('tags', JSON.stringify(data2));
$.ajax({
type: 'post',
url: '/ok2',
contentType: false,
processData: false,
data: fd,
success: function(response) {
},
error: function (response) {},
});
I'm not sure about your work but this is one of the basic method to send data via jquery make sure to put ajaxSetup in document.ready function
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#form').on('submit',function(){
$.ajax({
type:'post',
url:$("#form").attr('action'),
data:$("#form").serializeArray(),
success:function(data){
//response
console.log(data);
}
});
});

How can i store at a time 3 value same textbox?

<script type="text/javascript">
document.getElementById("subcategory").addEventListener("change", function() {
console.log(this.value);
});
$(function(){
$('.categoryList').click(function(){
console.log($(this).attr("name"));
var cat_id = event.target.value;
var url = "http://localhost:8000/api/getSubcategory/"+cat_id;
$.ajax({
type: "GET",
url: url,
dataType: "JSON",
success: function(res)
{
var html = "";
$.each(res, function (key, value) {
html += "<li class="+'subcategorys'+" value="+key+" name="+value+">"+value+" </li>";
});
$('#subcategory').html($(html).addClass('subcategoryList'));
$('.subcategorys').on('click', function(event) {
console.log($(this).attr("name"));
var subcat_id =event.target.value;
console.log(subcat_id);
});
}
});
});
});
$(document).ready(function() {
$('#subcategory').on('click', function(event) {
var subcat_id =event.target.value;
console.log(subcat_id);
var url = "/api/getSubcategorytwo/"+subcat_id;
$.ajax({
type: "GET",
url: url,
dataType: "JSON",
success: function(res)
{
var html = "";
$.each(res, function (key, value) {
html += "<li value="+key+">"+value+"</option></li>";
});
$("#subcategorytwo").html(html);
}
});
});
$('#subcategorytwo').on('click', function(event) {
var opt_subcat_two =event.target.value;
var opt = $(event.target).text();
console.log(opt,opt_subcat_two);
$( "#fetchvalue" ).replaceWith("<input type='text' class='form-control' name='subcategorytwo' value="+opt_subcat_two+" id='fetchvalue' data-toggle='modal' data-target='#myModal'> "+opt+"</input>");
$('#myModal').modal('hide');
$('.modal-backdrop').remove();
});
});
</script>
<input type="text" class="form-control" name="subcategorytwo" id="fetchvalue" data-toggle="modal" data-target="#myModal" ></input>
<!-- The Modal -->
<div class="modal" id="myModal">
<div class="modal-dialog modal-lg" >
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<a type="button" class="close" data-dismiss="modal" aria-hidden="true">×</a>
</div>
<div class="modal-body">
<div class="row">
<table class="table table-striped">
<thead>
</thead>
<tbody class="table">
<tr>
<td style="background-color: green">
<div class="col-md-7" >
#foreach($categories as $category)
<option class="categoryList" name="{{$category->category}}" value="{{$category->id}}">{{$category->category}}</option>
#endforeach
</div>
</td>
<td>
<div class="col-md-7">
<ul style="list-style: none" id="subcategory"></ul>
</div>
</td>
<td>
<div class="col-md-7">
<ul style="list-style: none" name="subcategorytwo" id="subcategorytwo" ></ul>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
Here is javascript code and modal code...I have total 4 table...
category subcategory
subcategory
subcategorytwo
post table
all are connected to a foreign key
Post table structure
When try to save category value, subcategory value, subcategorytwo value error is
How can I store 3 value at a time different place in db
Modal show like this
Modal like this
MySQL is most likely in STRICT mode try to
change the column to allow null:
ALTER TABLE `posts` CHANGE `subcategory2` `subcategory2` varchar NULL
Or try running
SET GLOBAL sql_mode='' or

Variable value lost before Ajax call

In the following piece of code, I am trying to pass 4 values to my controller through an AJAX call. The variable "NewType" loses its value, while the other three variables do not. NewType is pulling its value from a drop down list, while the other three are from text boxes. If I debug and step through the code, the variable retains its value. If I run the code through, the value is cleared out. Looking through similar problems, it seems obvious that it has something to do with the asynchronous Ajax call. Any ideas appreciated!!!
HTML
<tbody>
<!--Row created for each pesticide listed in Pesticides db table pulled in by Owner-->
#foreach (PesticideModel p in Model)
{
// Only show rows where IsDeleted == 0 (false)
if (#p.IsDeleted == false)
{
<tr class="toggler ui-sortable-handle" onclick="GetPestDetails()">
<!--Column for Owner-->
<td class="OwnerTD" id="OwnerBox">#p.Owner</td>
<!--Column for Brand Name-->
<td class="form-group-sm"><input type="text" name="BrandName" id="BrandName" disabled style="width:100%" value="#p.BrandName" /></td>
<!--Column for Original Brand Name-->
<td class="form-group-sm" style="display:none" id="OrigBrandName">#p.BrandName</td>
<!--Column for Pesticides Id-->
<td class="form-group-sm" style="display:none" id="PestIdBox">#p.PesticidesID</td>
<!--Column for EPA Reg No-->
<td class="form-group-sm"><input type="text" name="EPARegNo" id="EPARegNoBox" disabled style="width:100%" value="#p.EPARegNo" /></td>
<!--Column for Type-->
<td class="form-group-sm">
#*<td class="form-group-sm"><input type="text" name="Type" id="TypeBox" style="width:100%" value="#p.Type" disabled /></td>*#
#Html.DropDownListFor(x => #p.Type, (SelectList)ViewBag.Types, #p.Type, new { #class = "form-group-sm", #disabled = "disabled", id = "PType", name = "PType", onchange = "SetHiddenField(); return true;" } ) </td>
<!--Column for HiddentType --hidden column-->
<td class="HiddenType" id="HiddenType" hidden>#p.Type</td>
<!--Column for Editing Buttons-->
<td class="btn-group-sm">
<button type="button" class="btn btn-primary btn-warning" id="EditPesticideButton" name="EditButton" onclick="EditPesticideAction()">Edit</button>
<button type="button" class="btn btn-primary" id="SavePesticideButton" style="display:none" onclick="SavePesticideConfirm()">Save</button>
<button type="button" class="btn btn-primary" id="DeleteButton" style="display:none" onclick="DeletePesticideConfirm()">Delete</button>
<button type="button" class="btn btn-primary" id="CancelPesticideButton" style="display:none" onclick="CancelPesticideAction()">Cancel</button>
</td>
<!--Column for IsDeleted --hidden column-->
<td class="IsDeleted" id="IsDeleted" hidden>#p.IsDeleted</td>
</tr>
} // end if statement
} #*end foreach statement*#
</tbody>
JavaScript
var SavePesticide = function () {
var NewActiveIngredientName; //saves new textbox ActiveIngredient field
var NewEPARegNo;
var NewType;
var PesticideID;
// SaveButton click events
$("#PesticideTable").on("click", '#SavePesticideButton', function (event) {
// variables to set Name, Owner, and Id values
NewType = $(event.currentTarget).closest('tr').find('.PType').text();
NewActiveIngredientName = $(event.target).closest('tr').find('#ActiveIngredient').val();
NewEPARegNo = $(event.target).closest('tr').find('#EPARegNoBox').val();
PesticideID = $(event.currentTarget).closest('tr').find('.PesticideId').text();
// Make sure values are not empty or null
if ((NewActiveIngredientName != "" && NewActiveIngredientName != null) && (NewEPARegNo != "" && NewEPARegNo != null)) {
// send values to UpdatePestices function in controller, then to update database with new values
$.ajax({
type: "POST",
url: '#Url.Action("UpdatePesticides")',
datatype: 'json',
contentType: "application/json",
data: JSON.stringify({PType: NewType, PesticideID: PesticideID, ActiveIngredient: NewActiveIngredientName, EPARegNo: NewEPARegNo}),
success: function (data) {
alert(data);
// on success: disable all textbox fields
$("#PesticideTable").find("input[type=text]").prop("disabled", true);
$(event.target).closest('tr').find("input[type=text]").prop("disabled", true);
// on success: show edit button AND hide save, cancel, and delete buttons
$(event.target).closest('tr').find('#EditButton').show();
$(event.target).closest('tr').find('#SavePesticideButton').hide();
$(event.target).closest('tr').find('#CancelBrandButton').hide();
$(event.target).closest('tr').find('#DeleteButton').hide();
// enable edit buttons
$(".btn-warning").prop("disabled", false);
// refresh values
GetPesticideBrands();
}
});
} else {
// refresh values
GetPesticideBrands();
alert("Active Ingredient and EPA Number must contain a value")
}
})
}
Controller
public string UpdatePesticides(string Owner, string PestType, string OrigBrandName, string BrandName, string EPARegNo)
{
try
{
ADOHelper helper = new ADOHelper();
helper.UpdatePesticides(Owner, OrigBrandName, BrandName, EPARegNo, PestType);
return "Updated Successfully";
}
catch (Exception e)
{
AgRSys.Classes.Utility.Elmah_Helper.RaiseException(e);
return null;
}
}

How to use ajax post data from a row

<table>
<tr data-id="1">
<input type="text" name="name_1" value="abc">
<input type="text" name="value_1" value="1">
Edit
</tr>
<tr data-id="2">
<input type="text" name="name_2" value="def">
<input type="text" name="value_2" value="2">
Edit
</tr>
<tr data-id="3">
<input type="text" name="name_3" value="ghi">
<input type="text" name="value_3" value="3">
Edit
</tr>
</table>
function load_edit_row(input) {
var ID = $(input).parent().attr('data-id');
var dataString = [];
$("tr[data-id="+ID+"] :input").each(function(e){
dataString.push(this.value);
});
$.ajax({
type: 'POST',
url: 'update-row.php',
data: dataString,
success: function(itemJson) {
},
dataType: 'json'
});
}
Error post data key and data value, how to fix it?
You could use JSON.stringify(dataString) to encode your array in JavaScript, and then use $array=json_decode($_POST['string']); in your PHP script to retrieve it.
function load_edit_row(input) {
var ID = $(input).parent().attr('data-id');
var dataString = [];
$("tr[data-id="+ID+"] :input").each(function(e){
dataString.push(this.value);
});
var string = JSON.stringify(dataString);
$.ajax({
type: 'POST',
url: 'update-row.php',
data: 'string='+string,
success: function(itemJson) {
}
});
}
Try something like:
function load_edit_row(input) {
var ID = $(input).parent().attr('data-id');
var dataString = [];
$("tr[data-id="+ID+"] :input").each(function(e){
dataString.push(this.value);
});
$.ajax({
type: 'POST',
url: 'update-row.php',
data: {data:dataString},
success: function(itemJson) {
},
dataType: 'json'
});
}
<table>
<tr id="1">
<input type="text" name="name_1" id="1-data1" value="abc">
<input type="text" name="value_1" id="1-data2" value="1">
Edit
</tr>
<tr data-id="2">
<input type="text" name="name_2" id="2-data1" value="def">
<input type="text" name="value_2" id="2-data2" value="2">
Edit
</tr>
<tr data-id="3">
<input type="text" name="name_3" id="3-data1" value="ghi">
<input type="text" name="value_3" id="3-data2" value="3">
Edit
</tr>
</table>
Now the JS:
function load_edit_row(input) {
var dataString = [];
dataString.push($("#"+input+"-data1").val());
dataString.push($("#"+input+"-data2").val());
});
$.ajax({
type: 'POST',
url: 'update-row.php',
data: dataString,
success: function(itemJson) {
},
dataType: 'json'
});
}
You can't simply send a javascript 0-indexed array to POST's Form Data and expect receive it correctly on server side.
Use JSON.stringify(dataString) formatting dataString to a json string and then assign the json string value to a named key like:
var dataString = JSON.stringify(dataString);
$.ajax({
type: 'POST',
url: 'update-row.php',
data: {namedKey: dataString}
success: function(itemJson) {
}
});
On server side, use json_decode decode json back to array :
$data = filter_input(INPUT_POST, 'namedKey');
$dataArr = json_decode($data, true);

Sending file together with form data via ajax post

I'm trying to upload a file via ajax together with some fields in a form. However, it doesn't work. I get this error.
Undefined Index :- File
Here's my code.
HTML
<!-- File Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="file">Upload Software / File</label>
<div class="col-md-4">
<input id="file" name="file" class="input-file" type="file">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label" for="price">Price($)</label>
<div class="col-md-4">
<input id="price" name="price" type="text" placeholder="Price" class="form-control input-md" required="">
</div>
</div>
Ajax
$("#add_product").click(function(e) {
e.preventDefault();
product_name = $("product_name").val();
//d = $("#add_new_product").serialize();
$.ajax({
type: 'POST',
url: 'ajax.php',
data: $("#add_new_product").serialize(),
success: function(response) {
//
alert(response);
}
})
});
PHP
if (0 < $_FILES['file']['error']) {
echo ":!";
} else {
echo "ASa";
}
What am I missing here?
Can you try using FormData():
$("form#files").submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: window.location.pathname,
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
The above is a sample code, but you may use it to modify it.
you can use FormData
$("#add_product").click(function(e) {
e.preventDefault();
var fdata = new FormData()
fdata.append("product_name", $("product_name").val());
if ($("#file")[0].files.length > 0)
fdata.append("file", $("#file")[0].files[0])
//d = $("#add_new_product").serialize();
$.ajax({
type: 'POST',
url: 'ajax.php',
data: fdata,
contentType: false,
processData: false,
success: function(response) {
//
alert(response);
}
})
});
<!-- File Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="file">Upload Software / File</label>
<div class="col-md-4">
<input id="file" name="file" class="input-file" type="file">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label" for="price">Price($)</label>
<div class="col-md-4">
<input id="price" name="price" type="text" placeholder="Price" class="form-control input-md" required="">
</div>
</div>
We need to acknowledge first is that we need to APPEND both Form Input Data and Form File(s) into a single FormData variable.
Here is my solution in which I have enabled Multi File option so that this solution can fit for all examples.
It is Important to include name attribute in the input controls to make it work properly on server side in most of cases. If you are using C# then you can use simply Request.Form["nameAttribute"] to simply get the function. It is similar for Java and other languages.
My Sample Code is
$(document).ready(function () //Setting up on Document to Ready Function
{
$("#btnUpload").click(function (event) {
//getting form into Jquery Wrapper Instance to enable JQuery Functions on form
var form = $("#myForm1");
//Serializing all For Input Values (not files!) in an Array Collection so that we can iterate this collection later.
var params = form.serializeArray();
//Getting Files Collection
var files = $("#File1")[0].files;
//Declaring new Form Data Instance
var formData = new FormData();
//Looping through uploaded files collection in case there is a Multi File Upload. This also works for single i.e simply remove MULTIPLE attribute from file control in HTML.
for (var i = 0; i < files.length; i++) {
formData.append(files[i].name, files[i]);
}
//Now Looping the parameters for all form input fields and assigning them as Name Value pairs.
$(params).each(function (index, element) {
formData.append(element.name, element.value);
});
//disabling Submit Button so that user cannot press Submit Multiple times
var btn = $(this);
btn.val("Uploading...");
btn.prop("disabled", true);
$.ajax({
url: "Handler.ashx", //You can replace this with MVC/WebAPI/PHP/Java etc
method: "post",
data: formData,
contentType: false,
processData: false,
success: function () {
//Firing event if File Upload is completed!
alert("Upload Completed");
btn.prop("disabled", false);
btn.val("Submit");
$("#File1").val("");
},
error: function (error) { alert("Error"); }
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form enctype="multipart/form-data" method="post" id="myForm1">
<p><textarea id="TextArea1" rows="2" cols="20" name="TextArea1"></textarea></p>
<p><input id="File1" type="file" multiple="multiple" /></p>
<input id="btnUpload" type="button" value="Submit" />
</form>
For a working example (asp.net C# with handlers) you can visit sample code on https://github.com/vibs2006/HttpFileHandlerFormDataSample

Categories