return when duplicate html table - javascript

I have a function that can remove the duplicate in my html table.
var seen = {};
$('#tblSerial tr').each(function() {
var txt = $(this).text();
txt = txt.trim();
if (seen[txt]) {
isExist = true;
alertify.error("This serial is already on contract.");
$(this).remove();
return; //this should return
} else
seen[txt] = true;
});
But the problem now is that, below that code there's an AJAX call which always call even I return in the duplicate error.
$.ajax({
type: "GET",
url: siteURL + '#Url.Action("valcontract", "contract")',
data: data_model,
success: function (response) {
if (response.success) {
} else {
$('#serial').val("");
alertify
.error(response.responseText);
return;
}
},
error: function (response) {
alertify
.error(response.responseText);
return;
}
});
I want to block the AJAX call if there's a duplicate in my serial table.

Related

How to apply a function on an element without any event handler after just creating it

I made a dynamic element on javascript. Actually i am retrieving some data from db and on response i made an element in javascript
$.ajax({
url: 'php/count_comments.php',
type: 'post',
data: {
},
success: function(response) {
var data = JSON.parse(response);
if(data!='') {
$.each(data, function(i, item) {
var span3=document.createElement("span");
span3.appendChild(document.createTextNode("No Comments"));
span3.setAttribute("id",n+newsid);
span3.setAttribute("class","ment");
p1.appendChild(span3);
});
}else if(data==''){
alert("Admin has not uploaded any news yet");
return false;
}
}
});
Now when the element has been created and every element has a unique id now i want to run a function without any event handler for each element
this is function i want to run
function comments{
var target = event.target || event.srcElement;
var ids = target.id;
var id = ids.slice(-14);
// alert(id);
$.ajax({
url: 'php/count_comments.php',
type: 'post',
data: {
id:id
},
success: function(response) {
var data = JSON.parse(response);
if(data!='') {
$.each(data, function(i, item) {
// var target = event.target || event.srcElement;
// var ids = target.id;
// alert(ids);
// alert(document.getElementById(ids).innerHTML);
document.getElementById(ids).innerHTML=data[i].comments+ " Comment(s)";
});
}else if(data==''){
//alert("No comments yet");
return false;
}
}
});
}
You can call your function immediately in the loop which creates elements.
$.each(data, function(i, item) {
var span3=document.createElement("span");
span3.appendChild(document.createTextNode("No Comments"));
span3.setAttribute("id",n+newsid);
span3.setAttribute("class","ment");
p1.appendChild(span3);
//call from here with the id
comments(n+newsid)
});
Also, comments function is wrongly declared, correct it and have id as parameter.
function comments(id) {
// do your stuff
}
if you want to call comment method silently then use a timeout function while calling
setTimeout(function() {
comments(n+newsid);
}, 0)

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.

When submitting an ajax request, how can you "put the original request on hold" temporarily until a condition is met?

I am wanting to implement a recaptcha process that captures all ajax requests before they go through - the desired process would be as follows:
User completes an action which is going to cause an ajax request of some sort.
If the user has already completed the recaptcha process, the ajax request proceeds without further delay
If the user has not completed the recaptcha process, put the ajax request "on hold" temporarily until the recaptcha process is completed, then continue the ajax request.
I have got things to a state where I intercept the call, however I don't know how to put it on hold temporarily. Here's the relevant code:
<script>
var captchaValidated = null;
var currentRequests = [];
$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
if (options.url != "/ValidateCaptcha") {
if (captchaValidated == null || captchaValidated == false) {
if (captchaValidated == null){
openRecaptcha();
} else {
verifyCaptcha(); //see async question in method
}
if (!captchaValidated) {
jqXHR.abort();
} else {
//let the original request proceed now - but how?!
}
}
}
});
function verifyCaptcha() {
var grecaptcha = $("g-recaptcha-response");
var encodedResponse;
if (grecaptcha != null) {
encodedResponse = grecaptcha.val();
$.ajax({
async: false, //set to false so that the calling method completes rather than async - what do you think?
headers: headers,
cache: false,
url: "/ValidateCaptcha",
type: 'POST',
contentType: 'application/json',
success: function (data) {
//parse the data - did we get back true?
captchaValidated = data;
},
error: function (raw, textStatus, errorThrown) { captchaValidated = null; alert("Validate ReCaptcha Error: " + JSON.stringify(raw)); },
data: JSON.stringify({ "encodedResponse": encodedResponse })
});
}
}
function invalidateCaptcha(){
captchaValidated = null;
}
function openRecaptcha() {
grecaptcha.render('recaptcha', {
'sitekey': "thekey",
'callback': verifyCaptcha,
'expired-callback': invalidateCaptcha,
'type': 'audio image'
});
$("#recaptchaModal").modal('show');
}
</script>
Any suggestions of how to proceed would be appreciated, thanks in advance!
Thank you #Loading and #guest271314 for your help in pointing me in the right direction that helped me get things figured out. I've pasted how I accomplished it below - perhaps it will be of help to someone else. Of course if anyone would like to weigh in on my implementation please do.
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCaptcha&render=explicit&hl=en" async defer></script>
<script>
var captchaValidated = null;
var currentRequests = [];
var captchaPrompted = false;
var captchaReady = false;
var resetCaptcha = false;
function onloadCaptcha() {
captchaReady = true;
captcha = grecaptcha.render('recaptcha', {
'sitekey': '<yoursitekey>',
'callback': verifyCaptcha,
'expired-callback': invalidateCaptcha,
'type': 'audio image'
});
}
var deferredCaptcha = null;
var promiseCaptcha = null;
var captcha = null;
function openRecaptcha() {
if (!captchaReady) {
setTimeout(openRecaptcha, 50);
}
if (captchaPrompted) {
return;
}
captchaPrompted = true;
var captchaTimer = setInterval(function () {
if (captchaValidated != null) {
if (captchaValidated) {
deferredCaptcha.resolve();
} else {
deferredCaptcha.reject();
captchaValidated = null;
}
}
}, 100);
if (resetCaptcha) {
captcha.reset();
}
deferredCaptcha = $.Deferred();
promiseCaptcha = deferredCaptcha.promise();
promiseCaptcha.done(function () {
//captcha was successful
clearInterval(captchaTimer);
//process the queue if there's items to go through
if (currentRequests.length > 0) {
for (var i = 0; i < currentRequests.length; i++) {
//re-request the item
$.ajax(currentRequests[i]);
}
}
});
promiseCaptcha.fail(function () {
//captcha failed
clearInterval(captchaTimer);
currentRequests = []; //clear the queue
});
$("#recaptchaModal").modal('show');
}
function verifyCaptcha() {
resetCaptcha = true;
var response = $("#g-recaptcha-response").val();
var encodedResponse;
// confirm its validity at the server end
$.ajax({
headers: headers,
cache: false,
url: "/ValidateCaptcha",
type: 'POST',
contentType: 'application/json',
success: function (data) {
captchaValidated = data;
if (!data) {
captchaPrompted = false;
}
},
error: function (raw, textStatus, errorThrown) { captchaValidated = false; captchaPrompted = false; alert("WTF Validate ReCaptcha Error?!: " + JSON.stringify(raw)); },
data: JSON.stringify({ "encodedResponse": response })
});
}
function invalidateCaptcha(){
deferredCaptcha.reject();
captchaValidated = null;
resetCaptcha = true;
}
$.ajaxSetup({
beforeSend: function (xhr, settings) {
if (settings.url == '/ValidateCaptcha' || captchaValidated) {
// we're validating the captcha server side now or it's already been validated - let it through
} else {
if (typeof settings.nested === 'undefined'){
settings.nested = true; //this flag is to determine whether it's already in the queue
currentRequests.push(settings); //add the request to the queue to be resubmitted
//prompt them with the captcha
openRecaptcha();
}
return false; // cancel this request
}
}
});
</script>
At $.ajaxPrefilter() use .then() chained to openCaptcha to call verifyCaptcha
if (captchaValidated == null){
openRecaptcha().then(verifyCaptcha);
}
at verifyCaptcha use .is() with parameter "*" to check if an element exists in document
if (grecaptcha.is("*")) {
at openRecaptcha(), if grecaptcha.render does not return asynchronous result return jQuery promise object using .promise(); else chain to grecaptcha.render and $("#recaptchaModal").modal('show'); using $.when()
return $("#recaptchaModal").modal('show').promise()
or
return $.when(grecaptcha.render(/* parameters */)
, $("#recaptchaModal").modal('show').promise())
Something like this? (pseudo-code)
verified = false;
$('#myButton').click(function(){
if (!verified) verify_by_captcha();
if (verified){
$.ajax(function(){
type: 'post',
url: 'path/to/ajax.php',
data: your_data
})
.done(function(recd){
//ajax completed, do what you need to do next
alert(recd);
});
}
});//end myButton.click

Why trigger and click do not work in this case?

I have a piece of code that does:
$('td.unique').live('click', function () {
//function logic here
});
This works fine on I click on the td of my table. All fine!
Now I would like to be able to have the same functionality programatically in certain cases without the user actually pressing click.
I have tried:
$(document).ready(function() {
$(".clearButton").click( function () {
var username = $(this).closest('tr').find('input[type="hidden"][name="uname"]').val();
var user_id = $(this).closest('tr').find('label').val();
var input = [];
input[0] = {action:'reset', id:user_id,user:username,};
$.ajax({
url: 'updateprofile.html',
data:{'user_options':JSON.stringify(input)},
type: 'POST',
dataType: 'json',
success: function (res) {
if (res.status >= 1) {
//all ok
console.log("ALL OK");
$(this).closest('tr').find('.unique').trigger('click');
$(this).closest('tr').find('td.unique').trigger('click');
$(this).closest('tr').find('td.unique').click();
}
else {
alert('failed');
}
}
});
This button is in the same row that the td.unique is
None of these work. Why? Am I doing it wrong? Is the function that I have bind in live not taken into account when I click this way?
You need to cache the $(this) inside the ajax function.
var $this = $(this);
the $(this) inside the ajax function will not refer to the element that is clicked
$(".clearButton").click(function () {
var $this = $(this);
var username = $this.closest('tr').find('input[type="hidden"][name="uname"]').val();
var user_id = $this.closest('tr').find('label').val();
var input = [];
input[0] = {
action: 'reset',
id: user_id,
user: username,
};
$.ajax({
url: 'updateprofile.html',
data: {
'user_options': JSON.stringify(input)
},
type: 'POST',
dataType: 'json',
success: function (res) {
if (res.status >= 1) {
console.log("ALL OK");
$this.closest('tr').find('.unique').trigger('click');
$this.closest('tr').find('td.unique').trigger('click');
$this.closest('tr').find('td.unique').click();
} else {
alert('failed');
}
}
});
});

my javascript code will not proceed to delete my data from jqGrid

just want to ask regarding my javascript code. I have a function that will delete and edit a data in my jqgrid. But everytime i run my code, it will not delete and edit if I dont put an alert in some portion of the code. Why is it happening? How can i make my program run without the alert?
Below is my delete function:
function woodSpeDelData(){
var selected = $("#tblWoodSpe").jqGrid('getGridParam', 'selrow');
var woodID='';
var woodDesc='';
var codeFlag = 0;
var par_ams = {
"SessionID": $.cookie("SessionID"),
"dataType": "data"
};
//this part here will get the id of the data since my id was hidden in my jqgrid
$.ajax({
type: 'GET',
url: 'processjson.php?' + $.param({path:'getData/woodSpecie',json:JSON.stringify(par_ams)}),
dataType: primeSettings.ajaxDataType,
success: function(data) {
if ('error' in data)
{
showMessage('ERROR: ' + data["error"]["msg"]);
}
else{
$.each(data['result']['main']['rowdata'], function(rowIndex, rowDataValue) {
$.each(rowDataValue, function(columnIndex, rowArrayValue) {
var fldName = data['result']['main']['metadata']['fields'][columnIndex].name;
if (fldName == 'wood_specie_id'){
woodID = rowArrayValue;
}
if (fldName == 'wood_specie_desc'){
woodDesc = rowArrayValue;
alert($('#editWoodSpeDesc').val() +' '+ woodDesc); //program will not delete without this
if(selected == woodDesc){
codeFlag =1;
alert(woodID); //program will not delete without this
};
}
});
if (codeFlag == 1){
return false;
}
});
if (codeFlag == 1){
return false;
}
}
}
});
alert('program will not proceed without this alert');
if (codeFlag == 1) {
var datas = {
"SessionID": $.cookie("SessionID"),
"operation": "delete",
"wood_specie_id": woodID
};
alert(woodID);
alert(JSON.stringify(datas));
$.ajax({
type: 'GET',
url: 'processjson.php?' + $.param({path:'delete/woodSpecie',json:JSON.stringify(datas)}),
dataType: primeSettings.ajaxDataType,
success: function(data) {
if ('error' in data)
{
showMessage('ERROR: ' + data["error"]["msg"]);
}
else{
$('#tblWoodSpe').trigger('reloadGrid');
}
}
});
}
}
EDIT
My main purpose of putting an alert was just to know if my code really get the right ID of the description, and if would really go the flow of my code... But then i realized that it really wont work with it.

Categories

Resources