Here is my java code. I'd like to find a cleaner way to do this. How can I access the same data via serialize? I plan to have multiple forms on a single page that need processing. I'm looking to DRY up the code and not have to specifically name each field.
Thanks!
HTML:
ItemAmountDescription
<tr class="edit_tr" id="3">
<td class="edit_td">
<span class="text" id="name_3">Salary</span>
<input type="text" value="Salary" class="editbox" id="name_input_3"/>
</td> <td class="edit_td">
<span class="text" id="amount_3">100.00</span>
<input type="text" value="100.00" class="editbox" id="amount_input_3"/>
</td> <td class="edit_td">
<span class="text" id="description_3">Salary</span>
<input type="text" value="Salary" class="editbox" id="description_input_3"/>
</td> </tr>
</tbody>
</table>
Java code:
<script type="text/javascript">
$(document).ready(function()
{
$(".edit_tr").click(function()
{
var ID=$(this).attr('id');
$("#name_"+ID).hide();
$("#amount_"+ID).hide();
$("#description_"+ID).hide();
$("#description_input_"+ID).show();
$("#name_input_"+ID).show();
$("#amount_input_"+ID).show();
}).change(function()
{
var ID=$(this).attr('id');
var name=$("#name_input_"+ID).val();
var amount=$("#amount_input_"+ID).val();
var description=$("#description_input_"+ID).val();
var dataString = 'id='+ ID +'&name='+name+'&amount='+amount+'&description='+description;
$("#name_"+ID).html('<img src="load.gif" />'); // Loading image
if(name.length>0 && amount.length>0)
{
$.ajax({
type: "POST",
url: "{{url('budget/edit-income')}}",
data: dataString,
cache: false,
success: function(html)
{
$("#name_"+ID).html(name);
$("#amount_"+ID).html(amount);
$("#description_"+ID).html(description);
}
});
}
else
{
alert('Enter something.');
}
});
// Edit input box click action
$(".editbox").mouseup(function()
{
return false
});
// Outside click action
$(document).mouseup(function()
{
$(".editbox").hide();
$(".text").show();
});
});
</script>
You mentioned serialize... use $('form').serialize(); to create a string ready for the ajax data
Related
I have a code that waste my few hours. Here jquery closest with class not working in html table and not passing value. I use html, javascript, jquery and php here. Can anyone rewrite the code freshly.
<script>
$(document).ready(function () {
$(".senddata").on("click", function () {
var subans =
$(this).closest(".datadivision").find("input[name='subans']").val();
var data = 'subans=' + subans;
$.ajax({
type: "POST",
url: "test.php",
data: data,
cache: false,
success: function (html) {
alert(html);
}
});
});
});
</script>
<table>
<tr class="datadivision">
<input type="hidden" name="subans" value="A" >
<td class= "senddata">
<label><input type="radio" name="subans" value="something"> This is a
line</label>
</td>
</tr>
</table>
<?php
if (isset($_POST['subans'])) {
$subans = $_POST['subans'];
if (!empty($subans)) {
echo $subans;
}
}
?>
Assuming that you want the alert to show the value "A", JavaScript is not the issue. The problem is that you are printing the whole page, even when the request is POST.
Instead, you should conditionally print the page only when the request is not POST, or when it does not contain subans property. Like this:
<?php
if (isset($_POST['subans'])) {
$subans = $_POST['subans'];
if (!empty($subans)) {
echo $subans;
}
} else {
?>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script>
$(document).ready(function () {
$(".senddata").on("click", function () {
console.log(this)
var subans =
$(this).closest(".datadivision").find("input[name='subans']").val();
var data = 'subans=' + subans;
$.ajax({
type: "POST",
url: "stack.php",
data: data,
cache: false,
success: function (html) {
alert(html);
}
});
});
});
</script>
<table>
<tr class="datadivision">
<input type="hidden" name="subans" value="A" >
<td class= "senddata">
<label><input type="radio" name="subans" value="something"> This is a
line</label>
</td>
</tr>
</table>
<?php
}
?>
So i have this code. I want to send the data inside of my html inputs to the controllers parameters. In my jquery i have a line that looks like this
var currentRow = $(this).closest("tr");
But i have no clue how to get into the values of each input inside the currentRow Object how can i do that or do you maybe know a better way to do this?
// my html
#foreach (var discount in Model.DiscountList)
{
<tr>
<td>#Html.TextBox("codeTextBox", discount.Code) </td>
<td><input type="checkbox" name="freeShippingCheckBox" id="freeShippingCheckBox" checked="#discount.FreeShipping" /> </td>
#if (discount.isTwoForThree == true)
{
<td><input type="tel" value="Ta 3 betala för 2" readonly /></td>
}
else
{
<td><input type="number" value="#discount.PercentOffPrice"/></td>
}
<td><input type="checkbox" id="activeCheckBox" name="activeCheckBox" checked="#discount.Active" /></td>
<td><input type="datetime" value="#discount.CreatedDate" readonly /></td>
<td>
<input type="button" value="Radera" class="fa fa-remove" data-url="#Url.Action("DeleteDiscountCode","Discount",new { id= discount.Id})" />
<input type="button" value="Uppdatera" class="fa fa-update" data-url="#Url.Action("UpdateDiscount","Discount",new { id= discount.Id, })" />
<input type="button" value="Produkter" class="fa fa-products" />
</td>
<input id="#discount.Id.ToString()" type="hidden" value="#discount.Id" />
</tr>
}
//my jquery
$(".fa-update").on("click", function () {
var currentRow = $(this).closest("tr");
console.log(currentRow.children("#freeShippingCheckBox").val());
if (confirm("Are you sure you want to edit this discount code?"))
{
$.post($(this).data("url"), function (data) {
$.ajax({
url: '#Url.Action("DeleteUser","Discount")',
type: "POST",
data: "freeShipping=..........???????????",
success: function (data) {
if (data) {
}
location.reload();
}
});
location.reload();
alert("Deleted");
})
}
});
//my controller
[HttpPost]
public void UpdateDiscount(int id, bool freeShipping, int percentOfPrice, bool active)
{
Service.DiscountService.UpdateDiscount(id, freeShipping, percentOfPrice, active);
}
My proposal is:
$(function () {
$(".fa-update").on("click", function (e) {
var data = {};
var currentRowParams = $(this).closest("tr").find('input').each(function(index, element) {
var name = element.name ? element.name : 'undefined' + index;
data[name] = element.value || '';
});
var x = JSON.stringify(data);
console.log(x);
//
// If instead you want the params in a traditional GET
//
});
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<table>
<tbody>
<tr>
<td>#Html.TextBox("codeTextBox", discount.Code) </td>
<td><input type="checkbox" name="freeShippingCheckBox" id="freeShippingCheckBox" checked="#discount.FreeShipping" /> </td>
<td><input type="tel" value="Ta 3 betala for 2" readonly /></td>
<td><input type="checkbox" id="activeCheckBox" name="activeCheckBox" checked="#discount.Active" /></td>
<td><input type="datetime" value="#discount.CreatedDate" readonly /></td>
<td>
<input type="button" value="Radera" class="fa fa-remove" data-url="#Url.Action("DeleteDiscountCode","Discount",new { id= discount.Id})" />
<input type="button" value="Uppdatera" class="fa fa-update" data-url="#Url.Action("UpdateDiscount","Discount",new { id= discount.Id, })" />
<input type="button" value="Produkter" class="fa fa-products" />
</td>
<input id="#discount.Id.ToString()" type="hidden" value="#discount.Id" />
</tr>
</tbody>
</table>
You can access a value via .html(). As Vijai said, you can use serialize to make it a POST array like (&=, etc) format assuming you have a structured form. Or, to stay similar to your original code, you can just pass as usual JSON. like
data:{shippingInfo: "value", moreInfo: "blahblah"}
It is recommended to use a <form id="formID" ...> tag around yours inputs and use $("#formID").serialize() in the Ajax method if you are not doing processing of the input value in the View. Refer this sample link : Submit form using AJAX and jQuery
$.post($(this).data("url"), function (data) {
$.ajax({
url: '#Url.Action("DeleteUser","Discount")',
type: "POST",
data: $("#formID").serialize(),
success: function (data) {
if (data) {
}
location.reload();
}
});
I am trying to pass the data from a form to an insertion script without having the form data cleared. I am using this function to act on the press of the submit button but I get nothing. It is even set to throw an error if the form is missing data but it doesn't even get that far. I can only assume I am not calling it properly.
$(function() {
$(".submit").click(function() {
var facility = $("#facility").val();
var riskclient = $("#riskclient").val();
var riskdate = $("#riskdate").val();
var dataString = 'facitlity=' + facility + '&riskclient=' + riskclient + '&riskdate=' + riskdate;
if (facility == '' || riskclient == '' || riskdate == '') {
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
} else {
$.ajax({
type: "POST",
url: "insertriskass.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
<div class="body">
<div align='center'>
<div class="tablebackground">
<form method ="post" name= "form" id="form">
<table border='1' >
<tr>
<td>Facility</>
<td><input type="text" name= "riskFacility" id="facility"></td>
<td rowspan='4'><input type="submit" name="submit" value="New Client" class="submit"/</td>
</tr>
<tr>
<td>Client</td>
<td><input required type="text" name="riskClientId" id="riskclient" value="<?php echo htmlspecialchars($_POST['riskClientId']); ?>"></td>
</tr>
<tr>
<td>Audit Date</td><td> <input required type="text" id="datepicker" name="riskauddate" id="riskdate"></td>
</tr>
</table>
</form>
It is definitely not passing anything to the insertion script. So again, I think I am calling it incorrectly.
I see your html tags are not closed properly
<div class="body">
<form method="post" name="form" id="form">
<table border='1'>
<tr>
<td>Facility</td>
<td>
<input type="text" name="riskFacility" id="facility">
</td>
<td rowspan='4'>
<input type="submit" name="submit" value="New Client" class="submit" /> </td>
</tr>
<tr>
<td>Client</td>
<td>
<input required type="text" name="riskClientId" id="riskclient" value="">
</td>
</tr>
<tr>
<td>Audit Date</td>
<td>
<input required type="text" id="datepicker" name="riskauddate" id="riskdate">
</td>
</tr>
</table>
</form>
and check if it comes to error call back
I think it's useful..
$(document).ready(function () {
$('#submit').on('click', function (event) {
event.preventDefault();
var facility = $("#facility").val();
var riskclient = $("#riskclient").val();
var riskdate = $("#riskdate").val();
var dataString = 'facitlity='+ facility + '&riskclient=' + riskclient + '&riskdate=' + riskdate;
or
// var datastring = $("#form").serialize();
if(facility=='' || riskclient=='' || riskdate=='' )
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "insertriskass.php",
data: dataString,
success: function (msg) {
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
})
event.preventDefault used to stop submit and page reload.
datastring = $("#form").serialize(); used to submit all data values so no need to take each and every variable assign value.
You can refactor a little the code like this, revise your html tags. You have a double id property in an input, and missing clousure tags.
$(document).ready(function() {
$(".submit").click(function(event) {
event.PreventDefault();
var facility = $("#facility").val();
var riskclient = $("#riskclient").val();
var riskdate = $("#riskdate").val();
var dataString = 'facitlity=' + facility + '&riskclient=' + riskclient + '&riskdate=' + riskdate;
if (!facility || !riskclient || !riskdate) {
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
} else {
//send ajax post
}
});
});
$(document).ready(function () {
$("#addrow").click(function () {
var strToAdd = '<tr><td><input type="text" class="item_code form-control" placeholder="Item Code" name="item_code[]"></td><td><input type="text" class="price form-control" placeholder="price" name="price[]"><td></tr>';
$('#itemrow').append(strToAdd);
$('.item_code').keyup(function () {
var dataString = $('.item_code').val();
var request = $.ajax({
url: "itemcode.php",
method: "POST",
data: { item_code: dataString },
dataType: "html"
});
request.done(function (msg) {
$(".price").val(msg);
});
});
});
});
<table id="itemrow">
<tr>
<td>
<input type="text" class="item_code form-control" placeholder="Item Code" name="item_code[]">
</td>
<td>
<input type="text" class="price form-control" placeholder="price" name="price[]">
<td>
</tr>
<tr>
<td>
<input type="text" class="item_code form-control" placeholder="Item Code" name="item_code[]">
</td>
<td>
<input type="text" class="price form-control" placeholder="price" name="price[]">
<td>
</tr>
</table>
HTML Code is added through another javascript using append function. When I enter Item Code for both the fields it only displays data of first one.
It happends, because you use multiple instances of classes "item_code" and "price". Try this code.
$('.item_code').keyup(function() {
var dataString = $(this).val();
var request = $.ajax({
url: "itemcode.php",
method: "POST",
data: { item_code : dataString },
dataType: "html"
});
request.done(function(msg) {
$(this).parent().find('.price').val(msg);
});
});
});
});
Try this:
$(document).ready(function () {
$("#addrow").on('click',function () {
var strToAdd = '<tr><td><input type="text" class="invoice_id form-control" placeholder="Item Code" name="invoice_id[]"></td><td><input type="text" class="txtHint form-control" placeholder="Item Code" name="txtHint[]"><td></tr>';
$('#itemrow').append(strToAdd);
});
$('.item_code').on('keyup',function () {
var item = $(this);
var dataString = item.val();
})
var request = $.ajax({
url: "itemcode.php",
method: "POST",
data: { item_code: dataString },
dataType: "html"
});
request.done(function (msg) {
item.parentsUntil('tr').find('.price').attr('value',msg);
});
});
});
Thanks to everyone who helped me. Was able to correct the mistake by adding context: this, in the ajax request. Below is full code.
$(document).ready(function () {
$("#addrow").click(function () {
var strToAdd = '<tr><td><input type="text" class="item_code form-control" placeholder="Item Code" name="item_code[]"></td><td><input type="text" class="price form-control" placeholder="price" name="price[]"><td></tr>';
$('#itemrow').append(strToAdd);
$('.item_code').keypress(function () {
var dataString = $(this).closest('tr').find('.item_code').val();
var request = $.ajax({
url: "itemcode.php",
method: "POST",
data: { item_code : dataString },
context: this,
dataType: "html"
});
request.done(function (msg) {
$(this).closest('tr').find('.price').val(msg);
});
});
});
});
I am retrieving value from database and showing it in html table with check boxes.i am also having button, when user check the check box and it pass the rowid and redirect next page .if user not check the check box and check the button it will not pass the rowid and it will not redirect.
my problem is when first row in html table is checked and button pressed its working but if i am checking the second row in html table and click the button it not performing any action
below is my code
<tbody id="fbody" class="fbody" style="width:1452px" >
<?php
$clientid=$_GET['clientid'];
if($clientid!=""){
$sql = mysql_query("SELECT * FROM billingdatainputandexport WHERE clientid = '$clientid'");
while($rows=mysql_fetch_array($sql))
{
if($alt == 1)
{
echo '<tr class="alt">';
$alt = 0;
}
else
{
echo '<tr>';
$alt = 1;
}
echo '<td style="width:118px" class="edit clientid '.$rows["id"].'">'.$rows["clientid"].'</td>
<td id="CPH_GridView1_clientname" style="width:164px" class="edit clientname '.$rows["id"].'">'.$rows["clientname"].'</td>
<td id="CPH_GridView1_billingyear" style="width:168px" class="edit billingyear '.$rows["id"].'">'.$rows["billingyear"].'</td>
<td id="CPH_GridView1_billingmonth " style="width:169px" class="edit billingmonth '.$rows["id"].'">'.$rows["billingmonth"].'</td>
<td style="width:167px" class=" '.$rows["id"].'">
<input name="nochk" value=" '.$rows["id"].'" type="submit" style="margin:0 0 0 49px;background-image: url(/image/export.png);background-repeat: no-repeat;cursor:pointer;color:#C0C0C0;" ></td>
<td style="width:69px"><input type="checkbox" id="chk1" name="chk1" value=" '.$rows["id"].'"/></td>
</tr>';
}
}
?>
</tbody>
<input type="image" name="yousendit" id="yousendit" src="/image/export.png" style="margin:-5px 23px -28px 822px;cursor:pointer;" >
javascript
<script>
$(document).ready(function() {
$("#yousendit").click(function() {
if(document.getElementById('chk1').checked){
var ms = document.getElementById('chk1').value;
$.ajax({
type:"post",
data:"ms="+ms,
success:function(data) {
window.location = 'billingdatainputandexport/billingdatainputandexportdetailedreport.php?ms='+ms+''
$.post("billingdatainputandexport/billingdatainputandexportdetailedreport.php", { "test": ms } );
$("#result").html(data);
}
});
}
});
});
</script>
You can change this:
id="chk1"
name="chk1"
<input type="checkbox" id="chk1" name="chk1" value=" '.$rows["id"].'"/>
to this:
class="chk"
name="chk"'.$rows["id"].'
'<input type="checkbox" id="chk1" name="chk"'.$rows["id"].'" value=" '.$rows["id"].'"/>'
and update the jQuery code:
$("#yousendit").click(function() {
var $check = $('.chk:checked');
$.ajax({ //<-------------here you havn't mentioned the url
type:"post",
data:$check.serialize(),
success:function(data){
............
}
});
});
HTML page should have only 1 element with specified ID, in your case as code is running in loop and you are assigning id
<td style="width:69px"><input type="checkbox" id="chk1" name="chk1" value=" '.$rows["id"].'"/></td>
all the checkbox will have the same ID. Now once you try to get checked status by selector
if(document.getElementById('chk1').checked){
it will return true if only first checkbox is selected and ignore all the other instances.
You should use class selector and loop through elements to get comma-separated values and make ajax call.
First change id to class in HTML
<input type="checkbox" class="chk1" name="chk1" value=" '.$rows["id"].'"/>
and change JavaScript to process selected checkbox array
$(document).ready(function () {
$("#yousendit").click(function () {
var id_list = [];
$.each($(".chk1:checked"), function (index, element) {
var tmpVal = $(element).val();
id_list.push(tmpVal);
});
if (id_list.length > 0) {
var ms = id_list.join();
$.ajax({
type: "post",
data: "ms=" + ms,
success: function (data) {
window.location = 'billingdatainputandexport/billingdatainputandexportdetailedreport.php?ms=' + ms + ''
$.post("billingdatainputandexport/billingdatainputandexportdetailedreport.php", {
"test": ms
});
$("#result").html(data);
}
});
}
});
});