Query string sending value = 0, not new assigned value in jQuery - javascript

In Js
$(document).ready(function() {
var trxID=0;
var oHoldTable=$('#posHold').dataTable();
$('#posHold tbody tr').die();
$('#posHold tbody tr').live('dblclick', function () {
var oHData = oHoldTable.fnGetData( this );
trxID=oHData[0];
if (oHData[0] > 0) {
$.post("VoidTransaction",{
trxID:oHData[0]
},function(data){
if (data.rst==1) {
parent.tb_remove();
$('.btnPrint').trigger('click');
}
});
}else{
alert("No Transaction is Available for Void");
}
});
$(".btnPrint").printPage({
url: "receipts/void.jsp?trxID="+trxID,
attr: "href",
message:"Your document is being created"
})
});
I have declared a variable trxID and initialized with 0. Then assign a value in .live even handler such as:
trxID=oHData[0];
but query string still sending value = 0, not new assigned value.
url: "receipts/void.jsp?trxID="+trxID
how get updated value of trxID?

I have made a little change, hope it will work fine and I think no need to explain. You can guess easily!
$(document).ready(function() {
var trxID=0;
var oHoldTable=$('#posHold').dataTable();
$('#posHold tbody tr').off();
$('#posHold tbody tr').on('dblclick', function () {
var oHData = oHoldTable.fnGetData( this );
trxID=oHData[0];
if (oHData[0] > 0) {
$.post("VoidTransaction",{
trxID:oHData[0]
},function(data){
if (data.rst==1) {
parent.tb_remove();
$('.btnPrint').trigger('click');
}
});
}else{
alert("No Transaction is Available for Void");
}
$(".btnPrint").printPage({
url: "receipts/void.jsp?trxID="+trxID,
attr: "href",
message:"Your document is being created"
})
});
});

Related

How can I call my validate function before sending my ajax when a button is clicked?

Hello everyone I have a table that's dynamically generated from database.
This is the table.
I have all the code that works fine,but I only need proper timing of execution
1) Check if all mandatory fields are populated on button click, if not don't send ajax.
2) When all mandatory fields are populated on button click then call ajax and send proper values to c# and later to database.
First I need to check if all mandatory fields are filled in(check Mandatory column(yes or no values):
$(function () {
$("#myButton").on("click", function () {
// Loop all span elements with target class
$(".IDMandatory").each(function (i, el) {
// Skip spans which text is actually a number
if (!isNaN($(el).text())) {
return;
}
// Get the value
var val = $(el).text().toUpperCase();
var isRequired = (val === "TRUE") ? true :
(val === "FALSE") ? false : undefined;
// Mark the textbox with required attribute
if (isRequired) {
// Find the form element
var target = $(el).parents("tr").find("input,select");
if (target.val()) {
return;
}
// Mark it with required attribute
target.prop("required", true);
// Just some styling
target.css("border", "1px solid red");
}
});
})
});
If not don't call ajax and send values. If all fields are populated then call ajax to send values to c#.
This is the ajax code that takes values from filed and table and send's it to c# WebMethod and later to database.
$(function () {
$('#myButton').on('click', function () {
var ddl = $('#MainContent_ddlBusinessCenter').val()
var myCollection = [];
$('#MainContent_gvKarakteristike tbody').find('tr:gt(0)').each(function (i, e) {
var row = $(e);
myCollection.push({
label: valuefromType(row.find(row.find('td:eq(1)').children())),
opis: valuefromType(row.find(row.find('td:eq(3)').children()))
});
});
console.log(myCollection);
function valuefromType(control) {
var type = $(control).prop('nodeName').toLowerCase();
switch (type) {
case "input":
return $(control).val();
case "span":
return $(control).text();
case "select":
('Selected text:' + $('option:selected', control).text());
return $('option:selected', control).text();
}
}
var lvl = $('#MainContent_txtProductConstruction').val()
if (lvl.length > 0) {
$.ajax({
type: "POST",
url: "NewProductConstruction.aspx/GetCollection",
data: JSON.stringify({ 'omyCollection': myCollection, 'lvl': lvl, 'ddl': ddl }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (parseInt(response.d) > 0)
alert("Saved successfully.");
else
alert("This object already exists in the database!");
console.log(response);
location.reload(true);
},
error: function (response) {
alert("Not Saved!");
console.log(response);
location.reload(true);
}
});
}
else {
alert("Please fill in the Product Construction field!")
}
});
});
I need code to execute first mandatory fields and when they are all filled in then call ajax part of the code!
Can anyone please help !
If you need more explanation just ask !
Thanks in advance !
Update Liam helped allot me but ajax is not working on button click.
function validate() {
// Loop all span elements with target class
$(".IDMandatory").each(function (i, el) {
// Skip spans which text is actually a number
if (!isNaN($(el).text())) {
return;
}
// Get the value
var val = $(el).text().toUpperCase();
var isRequired = (val === "TRUE") ? true :
(val === "FALSE") ? false : undefined;
// Mark the textbox with required attribute
if (isRequired) {
// Find the form element
var target = $(el).parents("tr").find("input,select");
if (target.val()) {
return;
}
// Mark it with required attribute
target.prop("required", true);
// Just some styling
target.css("border", "1px solid red");
}
});
}
function sendAjax() {
var ddl = $('#MainContent_ddlBusinessCenter').val()
var myCollection = [];
$('#MainContent_gvKarakteristike tbody').find('tr:gt(0)').each(function (i, e) {
var row = $(e);
myCollection.push({
label: valuefromType(row.find(row.find('td:eq(1)').children())),
opis: valuefromType(row.find(row.find('td:eq(3)').children()))
});
});
console.log(myCollection);
function valuefromType(control) {
var type = $(control).prop('nodeName').toLowerCase();
switch (type) {
case "input":
return $(control).val();
case "span":
return $(control).text();
case "select":
('Selected text:' + $('option:selected', control).text());
return $('option:selected', control).text();
}
}
var lvl = $('#MainContent_txtProductConstruction').val()
if (lvl.length > 0) {
$.ajax({
type: "POST",
url: "NewProductConstruction.aspx/GetCollection",
data: JSON.stringify({ 'omyCollection': myCollection, 'lvl': lvl, 'ddl': ddl }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (parseInt(response.d) > 0)
alert("Saved successfully.");
else
alert("This object already exists in the database!");
console.log(response);
location.reload(true);
},
error: function (response) {
alert("Not Saved!");
console.log(response);
location.reload(true);
}
});
}
else {
alert("Please fill in the Product Construction field!")
}
}
$(function () {
$('#myButton').on('click', function () {
if (validate()){
sendAjax();
}
})
});
If you want to execute these in order why don't you just add one click handler that calls each function:
function validate(){
// Loop all span elements with target class
$(".IDMandatory").each(function (i, el) {
// Skip spans which text is actually a number
....etc.
}
function sendAjax(){
var ddl = $('#MainContent_ddlBusinessCenter').val()
var myCollection = [];
..etc.
}
$(function () {
$('#myButton').on('click', function () {
validate();
sendAjax();
}
});
Seems it would make sense if your validate function actually returns true or false if your form was valid too. then you could:
$(function () {
$('#myButton').on('click', function () {
if (validate()){
sendAjax();
}
}
});
I'm not really sure why your doing this:
// Mark it with required attribute
target.prop("required", true);
when you validate? If you just add this into your HTML it will handle required. adding it here seems a bit strange. I'm guessing your not actually submitting the form? It'd make more sense to add the validation message yourself rather than use this attribute.
Your codes not working because your not returning anything from your validate function. It's not 100% clear to me what is valid and what isn't so I can't alter this. But you need to add return true; for valid cases and return false;for invalid cases for the if statement if (validate()){ to work.

How to call a jQuery function when textbox is edited

In my code there is one text box which is disabled. when user click on edit pencil icon textbox is enabled for edit something. and when user edit the textbox it must check whether edited value is already exit or not. for that i have call checkOwnerId method. but there is no any call goes to that function.
This is my jQuery code
var parcel = $('#parcel_no').val();
$('#pin-edit').click(function () {
$('#owner_id_txt').removeAttr("disabled");
$("#pin-edit").hide();
$("#save-pin").show();
oldOwnerId = $('#owner_id_txt').val();
});
$('#save-pin').click(function () {
if ($("#owner_id_txt").val() == "") {
displayErrorMessage('Please enter owner Id');
$("#owner_id_txt").focus();
$('#owner_id_txt').val(oldOwnerId);
return;
}
$("#pin-edit").show();
$('#owner_id_txt').attr("disabled", true)
$("#save-pin").hide();
var data = { 'owner_id': $("#owner_id_txt").val(), 'parcel_no': parcel };
BlockUI();
var urlstring = "#Url.Content("~")Parcel/UpdateOwnerId";
$.post(urlstring, data, function (result) {
UnblockUI();
if (result.success == true) {
displaySuccessMessage('Owner Id updated successfully!');
}
else {
displayErrorMessage('There was an error while updating Owner Id!');
}
});
$('#owner_id_txt').change(function () {
//alert("Check Exist or Not");
var data = { 'owner_id': $("#owner_id_txt").val() };
var urlString = "#Url.Content("~")Parcel/CheckOwnerId";
urlString = sanitize_url_path(urlString);
$.post(urlString, data,
function (result) {
if (result) {
displayErrorMessage("Owner Id already exists");
$("#pin-edit").show();
$('#owner_id_txt').attr("disabled", true);
$("#save-pin").hide();
}
});
})
});
Your '$('#owner_id_txt').change(function () {' is called inside ' $('#save-pin').click(function () {' so its not getting called once you type the text box. Put the function outside of it, then it will check the value. Refer the below jsfiddle sample
code: JS
$(document).ready(function() {
$('#pin-edit').click(function () {
$('#owner_id_txt').removeAttr("disabled");
$("#pin-edit").hide();
$("#save-pin").show();
oldOwnerId = $('#owner_id_txt').val();
});
$('#save-pin').click(function () {
if ($("#owner_id_txt").val() == "") {
$("#owner_id_txt").focus();
$('#owner_id_txt').val(oldOwnerId);
return;
}
$("#pin-edit").show();
$('#owner_id_txt').attr("disabled", true)
$("#save-pin").hide();
});
$('#owner_id_txt').change(function () {//alert("Check Exist or Not");
console.log($(this).val());
});
$('#owner_id_txt').attr("disabled", true);
});
code: HTML
<input type="text" id="owner_id_txt" >
<div id="pin-edit">edit</div>
<div id="save-pin">save</div>
https://jsfiddle.net/pitchiahn/fr6gdeyd/
this can be archived using jquery change :
$( "'textboxid" ).change(function() {
// Check input( $( this ).val() ) for validity here using ajax call
});

Getting data from datatable then passing it to php with ajax

I am using jQuery DataTables, I can get data from selected row using this code
var str = $.map(table.rows('.selected').data(), function (item) {
return item[5]+" "+item[0]
});
where item[5] is id, item[0] is a string.
I want to split return string for passing id and string.
the error founded in ajax code specifically in
data : {}
where is the problem in this code.
<script>
$(document).ready(function() {
var table = $('#liveSearch').DataTable();
$('#liveSearch tbody').off('click', 'tr').on( 'click', 'tr', function () {
if ( $(this).hasClass('selected') ) {
$(this).removeClass('selected');
}
else {
table.$('tr.selected').removeClass('selected');
$(this).addClass('selected');
}
} );
$('.example3-1').on('click', function () {
if ((table.rows('.selected').data().length) > 0) {
var str = $.map(table.rows('.selected').data(), function (item) {
return item[5]+" "+item[0]
});
console.log(str);
$.confirm({
confirmButtonClass: 'btn-info',
cancelButtonClass: 'btn-danger',
confirm: function () {
$.ajax({
type: 'post',
url: 'delete.php',
data: {
str1 : str.substr(0,str.indexOf(' ')),
str2 : str.substr(str.indexOf(' ')+1)
},
success: function( data ) {
console.log( data );
}
});
table.row('.selected').remove().draw(false);
}
});
}
});
} );
CAUSE
You're only allowing only one row selected. But you're using $.map which returns Array not a string as you expect. There is no sense in using $.map for just one row.
SOLUTION
Use the following code instead to get data for selected row and produce the string needed.
var rowdata = table.row('.selected').data();
var str = rowdata[5] + " " + rowdata[0];
It could be simplified further:
var rowdata = table.row('.selected').data();
// ... skipped ...
$.ajax({
// ... skipped ...
data: {
str1: rowdata[5],
str2: rowdata[0]
}
// ... skipped ...
});
NOTES
The solution would be different if you allow multiple row selection.

Multiple POSTs with jQuery and AJAX

I'm having an issue with posting data via AJAX through a drag and drop interface. The data indeed is hitting my POST URL as defined, however, each and every time, the POST hits twice thereby causing the processing URL to handle the data again.
The premise of my application (at least this piece of it) was starting by basically using the code found at http://jsfiddle.net/UjQVw/2/ and to modify it for my needs.
I needed to have a container of items (in this case names) that were draggable to a user-defined number of divs on the opposite side of the screen -- whereby making 'room assignments' with a list of people.
Everything, except for the double POST is working well. If anyone can assist, I'd be most appreciative!
SAMPLE HTML CODE:
<div class="parent_list">
<h1>Registrants</h1>
<ul id="unplaced" class="group">
<?
foreach ($obj->function as $key => $value)
{
?>
<li data-group-id="0" data-post-id="<?=$value["rmid"]?>">
<?=$value["lname"]?>, <?=$value["fname"]?>
</li>
<?
}
?>
</ul>
</div>
<div class="lists">
<h1>Rooms</h1>
<ul style="display:none" id="new_list" class="group"></ul>
</div>
<input type="button" id='add' value="+ Add Room"/>
SAMPLE JS
<script>
var count = 0;
$("#add").click(function() {
count++;
var $clone = $("#new_list").clone();
$clone.attr({
id: count,
style: "" // remove "display:none"
});
$clone.find(".group").each(function(){
$(this).attr({
id: $(this).attr("id") + count
});
});
$(".lists").append($clone);
$('.group').sortable({
connectWith: '.group',
update: function(event, ui) {
var lodging = new Array();
$('.group li').each(function(i) {
var id = $(this).attr('data-post-id');
var group = $(this).parent().attr('id');
lodging.push(group+'_'+id);
});
console.log(event);
$.ajax({
type : "POST",
cache : false,
url : 'lodging_process.php',
data: {
'lodging[]': lodging
},
});
}
});
});
</script>
You could always buffer it with a boolean.
<script>
var sending = false; //Buffering variable
var count = 0;
$("#add").click(function() {
count++;
var $clone = $("#new_list").clone();
$clone.attr({
id: count,
style: "" // remove "display:none"
});
$clone.find(".group").each(function(){
$(this).attr({
id: $(this).attr("id") + count
});
});
$(".lists").append($clone);
$('.group').sortable({
connectWith: '.group',
update: function(event, ui) {
var lodging = new Array();
$('.group li').each(function(i) {
var id = $(this).attr('data-post-id');
var group = $(this).parent().attr('id');
lodging.push(group+'_'+id);
});
console.log(event);
if(!sending) { //Make sure we are not already sending a request
sending = true;
$.ajax({
type : "POST",
cache : false,
url : 'lodging_process.php',
data: {
'lodging[]': lodging
},
success: {
sending = false; //Upon finishing, allow another ajax command of this type
},
error: {
sending = false;
}
});
}
}
});
});
</script>
See if that works.
After the response by #John, I did some more testing and looking around and found this gem that's apparently stumped several others by me. As stated in the original question, the POST was indeed working...it was simply posting TWICE after each event. The reason for this is that there were changes in BOTH lists, thereby initiating the callback for EACH list that's affected.
Adding this simple if check as outlined here: https://forum.jquery.com/topic/sortables-update-callback-and-connectwith
update:function(e,ui) {
if (this === ui.item.parent()[0]) {
//your code here
}
}
has done the trick for me. Hope this information helps others with multiple callbacks using jQuery sortable and connectWith functions.
So...the new JS looks like this:
<script>
var count = 0;
$("#add").click(function() {
count++;
var $clone = $("#new_list").clone();
$clone.attr({
id: count,
style: "" // remove "display:none"
});
$clone.find(".group").each(function(){
$(this).attr({
id: $(this).attr("id") + count
});
});
$(".lists").append($clone);
$('.group').sortable({
connectWith: '.group',
update: function(event, ui) {
if (this == ui.item.parent()[0]) {
var lodging = new Array();
$('.group li').each(function(i) {
var id = $(this).attr('data-post-id');
var group = $(this).parent().attr('id');
lodging.push(group+'_'+id);
});
$.ajax({
type : "POST",
cache : false,
url : 'lodging_process.php',
data: {
'lodging[]': lodging
},
});
}
}
});
});
</script>

Callback never called on Jquery.post();

I'm having some trouble using JQUERY Post function.
I have 2 functions that call JQUERY Post function.
Both of them is working fine, but the callback function is never called (handleLike).
When I call handleLike manually, it's works perfect.
(Even if handleLike has just an alert inside, the callback function is not called)
Could you please help me with this thing?
<script type="text/javascript">
$(document).ready(function() {
function handleLike(v_cb){
alert("Call back chamou!");
$('#erro').html(v_cb.mensagem);
if (v_cb.class == 'map'){
var elemento = $('#maplike');
}else{
var elemento = $('#commentlike'+v_cb.id);
}
if (!(elemento.hasClass('disabled'))){
elemento.addClass("disabled");
var likes = elemento.find('font').text();
likes++;
elemento.find('font').html(likes);
}
}
$('#maplike').click(function() {
//var map_id = $('#like').find('font').attr('value');
var id = $(this).attr("name");
if (!($(this).hasClass('disabled'))){
var JSONObject= {
"mensagem":"Testando Json",
"id":86,
"class":"map"
};
handleLike(JSONObject);
alert("Teste");
$.post(
'/cmap/maps/like',
{ id: id },
handleLike,
'json'
);
}
});
$('[id*="commentlike"]').click(function() {
//var map_id = $('#like').find('font').attr('value');
var id = $(this).attr("name");
if (!($(this).hasClass('disabled'))){
$.post(
'/cmap/comments/like',
{ id: id },
handleLike,
'json'
);
}
});
});
</script>
Diagnostic, not solution
Rationalizing and adding an error handler, you should get something like this :
$(document).ready(function() {
function handleLike(v_cb){
alert("Call back chamou!");
$('#erro').html(v_cb.mensagem);
var elemento = (v_cb.class && v_cb.class == 'map') ? $('#maplike') : $('#commentlike'+v_cb.id);
if (!elemento.hasClass('disabled')){
var f = elemento.addClass("disabled").find('font');
f.html(++Number(f.text()));
}
}
function ajaxError(jqXHR, textStatus, errorThrown) {
alert('$.post error: ' + textStatus + ' : ' + errorThrown);
};
$('#maplike').on('click', function() {
var $this = $(this);
if (!$this.hasClass('disabled')) {
$.post('/cmap/maps/like', { id: $this.attr("name") }, handleLike, 'json').fail(ajaxError);
}
});
$('[id*="commentlike"]').on('click', function() {
var $this = $(this);
if (!$this.hasClass('disabled')) {
$.post('/cmap/comments/like', { id: $this.attr("name") }, handleLike, 'json').fail(ajaxError);
}
});
});
untested
Barring mistakes, there's a good chance the error handler will inform you of what's going wrong.
I follow the Kevin B tip and use $ajax method.
It was a parseerror. Sorry.
The return of v_cb was not a json, it was a html. I correct my return, and everything was ok.

Categories

Resources