Update a value on a entry on the table - issue - javascript

I have these columns on my table:
CardNumber
DateRegister
TimeRegister
DateExit
TimeExit
I read a value that is in a box, and when I press enter, the
Cardnumber, DateRegister,TimeRegister is add to the SQL Database
So I'll have like
CardNumber|DateRegister|TimeRegister|DateExit|TimeExit
124455|23-10-2022|11:00|null|null|
My Issue is, If I read the same card again, before I need to see if there is already one entrance on database with that card number, that don't have still DateExit and TimeExit.
If dont, I need to update that line, with that information, of if is a new one, will add a new entrance on the database
This is my code:
#section readcard{
<script>
$(function () {
$("#readONchange").change(function () {
var param1 = new Date();
var param2 = param1.getDate() + '/' + (param1.getMonth() + 1) + '/' + param1.getFullYear();
var param3 = param1.getHours() + ':' + param1.getMinutes() + ':' + param1.getSeconds();
var es = {};
/*es.IdCartao = $("#readONchange").val();*/
/*es.DateRegister = param2;*/
//Le cartao / Le data / Le Hora
es.IdCartao = $("#readONchange").val();
es.DateRegister = param2;
es.TimeRegister = param3;
if (es.IdCartao != null)
{
} else if (es.IdCartao == null) {
empregados.IdCartao = es.IdCartao(id);
(es.IdCartao == $("#readONchange").val && es.DateRegister != null && es.TimeRegister != null)
es.TimeExit = param3;
alert(es.IdCartao == $("#readONchange").val);
} else {
alert("erro")
}
alert("Register ADD!")
$.ajax({
type: "POST",
url: '#Url.Action("AddReport")',
data: '{es: ' + JSON.stringify(es) + '}',
dataType: 'json',
contentType: "application/json; charset=utf-8",
sucess: function () {
alert("Data Insert with Sucess");
},
error: function () {
alert("ERROR! on the regist");
}
});
});
});
</script>

Related

Trying to store ajax response to input hidden?

I am trying to set value of input hidden, but it returns me null or 0.
function addbettrack(odd){
if($(".leagues_arr").val()!='0' && $('.games_arr').val()!='0' && $('.bet_type').val()!='0' && $('.book').val()!='0'
&& $('.bet_venue').val()!='0'){
if(odd=='undefined') odd=0.00;
var datetime = $(".games_arr").children(":selected").data('value').DateTime;
var league = $(".leagues_arr").val();
var hometeam = $(".games_arr").children(":selected").data('value').HomeTeam;
var awayteam = $(".games_arr").children(":selected").data('value').AwayTeam;
var eventname = $(".games_arr").children(":selected").data('value').EventName;
var bettype = $(".bet_type").val();
var book = $('.book').children(":selected").data('book');
var bookid = $('.book').val();
var bet = $(".bet_venue").val();
//var odd = $(".odds").val();
var stake = 1;
var marked = '';
if (bet == "Visitor") {
marked = 'A';
} else if (bet == "Host") {
marked = 'H';
} else {
marked = '';
}
var source = 'bettrack';
var id = $('.hidden_id').val();
var mode = "insert";
if(id > 0){
mode = "edit";
}
console.log(id + " " + mode);
console.log(datetime + " " + league + " " + hometeam + " " + awayteam + " " + eventname + " " + bettype + " " + bet + " " + odd + " " + stake);
$.ajax({
type: "POST",
url: '/index.php?/bettrack/insert_bettip/'+id,
data: {
DateTime: datetime,
LeagueName: league,
HomeTeam: hometeam,
AwayTeam: awayteam,
EventName: eventname,
BetType: bettype,
Bet: bet,
Book: book,
BookID: bookid,
Odd: odd,
Stake: stake,
Marked: marked,
Source: source,
Id : id,
Mode : mode
},
dataType:"json",
success: function(data) {
console.log(data);
$('.hidden_id').attr('value',data.odd);
$('.hidden_id').val(data.odd);
alert($('.hidden_id').val()); //here returns nothing
},
error: function(xhr, textStatus, error) {
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
}
}
this function runs inside other function and ajax request:
function get_bettrack(eventname, bettype, betvenue, book, mode = "a", id = 0) {
console.log(eventname+" "+bettype+" "+betvenue + " " + book);
$.ajax({
type: "POST",
url: '/index.php?/bettrack/get_odds',
data: {
EventName: eventname,
BetType: bettype,
BetVenue: betvenue,
Book: book
},
dataType: 'json',
success: function(data) {
if (mode == "a") {
console.log(data.odd);
$(".odds").val(data.odd);
var stake = 1;
var towin = parseFloat(data.odd) * parseFloat(stake);
$(".towin").html(towin);
addbettrack(data.odd); //HEREEE <=====================
} else {
$(".myodd" + id).val(data.odd);
var stake = 1;
var towin = parseFloat(data.odd) * parseFloat(stake);
$(".towin" + id).html(towin);
}
},
error: function(xhr, textStatus, error) {
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
}
and also get_bettrack function runs inside an event inside ajax success:
$('.games_arr').change(function() {
var date = $(this).children(":selected").data('value').DateT;
var label = date;
$(".game_date").html(label);
if ($('.leagues_arr').val() != '0') {
$(".bet_type").val("ToWin");
$(".bet_venue").val("Host");
var eventname = $(".games_arr").children(":selected").data('value').EventName;
var betvenue = $(".bet_venue").val();
var bettype = $(".bet_type").val();
var book = $(".book").children(':selected').data('book');
load_book(eventname, bettype);
get_bettrack(eventname, bettype, betvenue, book);
}
});
<input type="hidden" class="hidden_id" value="0" />

How to use Delay for method execution in jquery

I am using jquery in my one of the form. where on click of submit button i call one function QuoteDetailValidation(). In which i validate fields. But after validate that fields i try to get all fields which have errorActive class. But unfortunately i can't get it.
See my code
$('#saveQuote').on('click', function(event) {
var descriptionData1 = $('input[name=\"QuoteDetail[description][]\"]');
QuoteDetailValidation(descriptionData1);
var selectors = document.querySelectorAll('#quote-quoteItems-form .errorActive').length;
alert(selectors);
return false;
});
function QuoteDetailValidation(descriptionData1) {
for (var i = 0; i < descriptionData1.length; i++) {
var id = descriptionData[i].id;
var value = descriptionData[i].value;
var costid = costData[i].id;
var costValue = costData[i].value;
$.ajax({
type: 'GET',
url: "<?php echo Yii::app()->createUrl('QuoteData/validatedata'); ?>",
data: 'descvalue=' + value + '&Descname=description&costValue=' + costValue + '&costName=cost&descId=' + id + '&costId=' + costid,
success: function(data) {
var obj = $.parseJSON(data);
var cost = obj.cost;
var desc = obj.desc;
if (desc != '' || cost != '') {
if (cost != '') {
$('#' + costid).addClass('errorActive');
$('#' + costid).prev().addClass('error');
$('#' + costid).next().remove();
$('#' + costid).after(cost);
$('#' + costid).parent().removeClass('success');
$('#' + costid).parent().addClass('error');
}
}
},
error: function(data) {
alert('Your data has not been submitted..Please try again');
}
});
}
}
Now What happens, When there is error QuoteDetailValidation() append errorActive class to fields.
By var selectors = document.querySelectorAll('#quote-quoteItems-form .errorActive').length; i try to get length of the fields which have errorActive class. but in alert of selectors, it always gives 0. But when i alert something before getting all errorActive Class then alert selectors give me perfect count. i think there is delay because of alert before getting class errorActive. so that it give me count. How to use it. Any help please. Thanks in advance.
You can determine the exact delay required for selectors to be initailized properly. Whatever we add as delay will be assumption and can be short for some scen
One options using below in your ajax request
async: false
like below:-
$.ajax({
type: 'GET',
async: false,
url: "<?php echo Yii::app()->createUrl('QuoteData/validatedata'); ?>",
data: 'descvalue=' + value + '&Descname=description&costValue=' + costValue + '&costName=cost&descId=' + id + '&costId=' + costid,
success: function(data) {}});
Setting async to false means that the statement you are calling has to complete before the next statement in your function can be called. If you set async: true(it is default) then that statement will begin it's execution and the next statement will be called regardless of whether the async statement has completed yet. Helpful question
But I still will advise you to move selectors part in success of ajax like below:-
$.ajax({
type: 'GET',
url: "<?php echo Yii::app()->createUrl('QuoteData/validatedata'); ?>",
data: 'descvalue=' + value + '&Descname=description&costValue=' + costValue + '&costName=cost&descId=' + id + '&costId=' + costid,
success: function(data) {
var obj = $.parseJSON(data);
var cost = obj.cost;
var desc = obj.desc;
if (desc != '' || cost != '') {
if (cost != '') {
$('#' + costid).addClass('errorActive');
$('#' + costid).prev().addClass('error');
$('#' + costid).next().remove();
$('#' + costid).after(cost);
$('#' + costid).parent().removeClass('success');
$('#' + costid).parent().addClass('error');
}
}
var selectors = document.querySelectorAll('#quote-quoteItems-form .errorActive').length;
alert(selectors);
//some logice here or move the above in some function and call it here
},
error: function(data) {
alert('Your data has not been submitted..Please try again');
}
});
or use call back functions.
Update: try something like below It will keep async as true and keep the count logic outside $.ajax.
function QuoteDetailValidation(descriptionData1,submitFormOrAddError) {
for (var i = 0; i < descriptionData1.length; i++) {
var id = descriptionData[i].id;
var value = descriptionData[i].value;
var costid = costData[i].id;
var costValue = costData[i].value;
$.ajax({
type: 'GET',
url: "<?php echo Yii::app()->createUrl('QuoteData/validatedata'); ?>",
data: 'descvalue=' + value + '&Descname=description&costValue=' + costValue + '&costName=cost&descId=' + id + '&costId=' + costid,
success: function(data) {
var obj = $.parseJSON(data);
var cost = obj.cost;
var desc = obj.desc;
if (desc != '' || cost != '') {
if (cost != '') {
$('#' + costid).addClass('errorActive');
$('#' + costid).prev().addClass('error');
$('#' + costid).next().remove();
$('#' + costid).after(cost);
$('#' + costid).parent().removeClass('success');
$('#' + costid).parent().addClass('error');
}
}
submitFormOrAddError(data);
},
error: function(data) {
alert('Your data has not been submitted..Please try again');
}
});
}
}
Call it like this:
$('#saveQuote').on('click', function(event) {
var descriptionData1 = $('input[name=\"QuoteDetail[description][]\"]');
QuoteDetailValidation(descriptionData1);
QuoteDetailValidation(descriptionData1,function(output){
// here you use the output
var selectors = document.querySelectorAll('#quote-quoteItems-form .errorActive').length; //This line is excuted only after call completes
alert(selectors);
//form submit here if error is zero.
});
alert("hii");//this line is executed without waiting for above call..
return false;
});
You need to do this on your success callback of the QuoteDetailValidation method, because the $.ajax runs async and after invoking the method it still hasn't completed.
$.ajax({
type: 'GET',
url: "<?php echo Yii::app()->createUrl('QuoteData/validatedata'); ?>",
data: 'descvalue=' + value + '&Descname=description&costValue=' + costValue + '&costName=cost&descId=' + id + '&costId=' + costid,
success: function(data) {
var obj = $.parseJSON(data);
var cost = obj.cost;
var desc = obj.desc;
if (desc != '' || cost != '') {
if (cost != '') {
$('#' + costid).addClass('errorActive');
$('#' + costid).prev().addClass('error');
$('#' + costid).next().remove();
$('#' + costid).after(cost);
$('#' + costid).parent().removeClass('success');
$('#' + costid).parent().addClass('error');
}
}
// Here you know that the elements will have the necessary classes.
var selectors = $('#quote-quoteItems-form .errorActive').length;
alert(selectors);
},
error: function(data) {
alert('Your data has not been submitted..Please try again');
}
});

jQuery ajax is calling infinily , showing too much recursion error in console

I am using jQuery.validationEngine plugin .I have a below ajax function to check duplicate unique value for a field.
function _is_unique(caller) {
var value = jQuery(caller).val();
var field_id = jQuery(caller).attr('id');
var field_name = jQuery(caller).attr('placeholder');
if (value != '') {
var uniqueObject = new Object();
uniqueObject.field_id = field_id;
uniqueObject.value = value;
var uniqueString = JSON.stringify(uniqueObject);
var getUrl = window.location;
//console.log(getUrl);
var baseUrl = getUrl.protocol + "//" + getUrl.host + "/" + getUrl.pathname.split('/')[1];
jQuery.ajax({
type: "POST",
url: baseUrl + "/dashboard/check_unique",
data: uniqueObject,
async: false,
cache: false,
dataType: "text",
success: function(msg) {
if (msg == "exist") {
isError = true;
promptText += " This " + field_name + settings.allrules["is_unique"].alertText + "<br />";
}
}
});
}
}
if the field value is present in server then from server I am returnning "exist" else I am returning "notexist".
Now while running my ajax script is calling infinitely . Can any please tell me what should I do to stop infinite loop of my ajax call.
Edited
This is the form Submit function . its also showing
too much recursion
error in console. By any chance am I having problem here ?
$('#searchform').on('submit', function(e){
var validateError ='';
var id='';
var fieldError = [];
$('#searchform :input:text').each(function(){
id = $(this).attr('id');
validateError = jQuery.fn.validationEngine.loadValidation(document.getElementById(id));
if(validateError)
{ fieldError.push(id);
}
});
if(fieldError.length!=0)
{
return false;
}
else{
$("form#searchform" ).submit();
return true;
}
});
});

Calling WebService using JQuery not working in all browsers but only in IE9?

I have this code in a js file which I am including in Default page to Create cookies at the clients' browser and using it in the Thankyou page to invoke my web service to track payment transactions.
// Read a page's GET URL variables and return them as an associative array.
$(document).ready(function () {
$.extend({
getUrlVars: function () {
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
getUrlVar: function (name) {
return $.getUrlVars()[name];
},
getCookie: function (name) {
var dc = document.cookie;
var prefix = name + "=";
var begin = dc.indexOf("; " + prefix);
if (begin == -1) {
begin = dc.indexOf(prefix);
if (begin != 0) return null;
}
else {
begin += 2;
var end = document.cookie.indexOf(";", begin);
if (end == -1) {
end = dc.length;
}
}
return unescape(dc.substring(begin + prefix.length, end));
}
});
{
var cookieStart, cookieEnd, cookieValue, UserGuid, productId, AffiliationURL, PricePerUnit, commissionAmount;
// Get object of URL parameters
if ($.getUrlVars() != null) {
var allVars = $.getUrlVars();
}
// Getting URL var by its name
//Now check if the user is from Seek Site??
//If this is not null that means the user is Refered from Seek Site
if ($.getUrlVar('clientId') != null) {
UserGuid = $.getUrlVar('clientId');
if ($.getUrlVar('productId') != null) {
productId = $.getUrlVar('productId');
}
if ($.getUrlVar('AffiliationURL') != null) {
AffiliationURL = $.getUrlVar('AffiliationURL');
}
if ($.getUrlVar('PricePerUnit') != null) {
PricePerUnit = $.getUrlVar('PricePerUnit');
}
if ($.getUrlVar('commissionAmount') != null) {
commissionAmount = $.getUrlVar('commissionAmount');
}
//Now Create the cookie for the user
var myCookie = $.getCookie("ReferedCookie");
alert(myCookie);
if (myCookie != null) {
// cookie exists
cookieStart = myCookie.indexOf("clientId=");
//alert(cookieStart = cookieStart + "ReferedCookie=".length);
cookieEnd = myCookie.indexOf(";", cookieStart);
//if there is no occurence of the semicolon character
//cookieEnd takes the length of the document.cookie property
if (cookieEnd == -1) cookieEnd = myCookie.length;
cookieValue = myCookie.substring(cookieStart, cookieEnd);
// check the Product Id
if (cookieValue.indexOf(productId + "&", "productId=") != -1) {
// that means the User clicked on the same Product again and there is already a cookie Exists for that product
alert("User clicked on the same Product again");
}
else {
// The Product Id is different ,We are going to add that product value as string to the cookie
}
}
else {
// Create Cookie
var expiryDate = new Date();
expiryDate.setTime(expiryDate.setDate(expiryDate.getDate() + 365)); // 365 days
document.cookie = "ReferedCookie=" + "clientId=" + UserGuid + "&productId=" + productId + "&AffiliationURL=" + AffiliationURL + "&PricePerUnit=" + PricePerUnit + "&commissionAmount=" + commissionAmount + ";" + "expires=" + expiryDate.toGMTString() + ";";
}
}
}});
And Here the Code which I want to run at Thankyou page but it runs in IE9 (at time I dnt know why???)
{
var cookieStart, cookieEnd, cookieValue, UserGuid, productId, AffiliationURL, PricePerUnit, commissionAmount;
$(window).load(function (e) {
e.preventDefault();
$.extend({
readCookie: function (name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
});
var x = new Array(3);
cookieValue = $.readCookie("ReferedCookie");
var s = 0;
var pos = cookieValue.indexOf("&");
while (pos > -1) {
x[s] = pos;
pos = cookieValue.indexOf("&", pos + 1);
// alert(x[s]);
s++;
}
var c1 = cookieValue.indexOf("clientId=");
alert(UserGuid = cookieValue.substring(c1 + 9, x[0]));
var p1 = cookieValue.indexOf("productId=");
alert(productId = cookieValue.substring(p1 + 10, x[1]));
var A1 = cookieValue.indexOf("AffiliationURL=");
alert(AffiliationURL = cookieValue.substring(A1 + 15, x[2]));
var pp1 = cookieValue.indexOf("PricePerUnit=");
alert(PricePerUnit = cookieValue.substring(pp1 + 13, x[3]));
var com1 = cookieValue.indexOf("commissionAmount=");
alert(commissionAmount = cookieValue.substring(com1 + 17));
var ServiceURL = 'http://localhost:12445/Service/TrackPayment.asmx/InsertCommissionRecord';
// var d = '{"ProductID": "' + productId + '" , "AffiliationURL": "' + AffiliationURL + '" , "Quantitiy": "' + 15 + '" , "PricePerUnit": "' + PricePerUnit + '" , "commissionAmount": "' + commissionAmount + '"}';
var d = '{"ProductID":"1","AffiliationURL":"1","Quantitiy":"1","PricePerUnit":"1","commissionAmount":"1"}';
alert(d);
$.ajax({
type: 'POST',
data: d,
url: ServiceURL,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success:
function (data, textStatus, XMLHttpRequest) {
alert(data);
alert(textStatus);
alert(XMLHttpRequest);
},
error:
function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
alert(errorThrown);
}
});
});}
In firebug console it show data.d is null
Kindly help me out and please point out where I am going wrong.
Thanks
JS:
$.ajax({
type: 'POST',
data: {'d': d},
url: ServiceURL,
dataType: 'json',
success:
function (data, textStatus, XMLHttpRequest) {
alert(data.ProductID); // returns '1'
},
error:
function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
alert(errorThrown);
}
});
test.php:
$data = json_decode($_POST['d']);
echo json_encode($data);

Synchronous AJAX...I know that sounds crazy

I have web methods that are called via AJAX in a .Net 4.0 web app. In many cases, the AJAX calls are made repeatedly in a for loop. My problem is, the information the web method is syncing to my server is time stamped and therefore must be synced in the order in which I am sending it to AJAX. Unfortunately, it seems whatever finishes first, simply finishes first and the time stamps are all out of order. I need to basically queue up my AJAX requests so that they execute in order rather than Asynchronously, which I know is the A in AJAX so this might be a totally dumb question.
How do I force the order of execution for AJAX calls done in a for loop?
Edit: Some code
for (var i = 0; i < itemCnt - 1; i++) {
try {
key = items[i];
item = localStorage.getItem(key);
vals = item.split(",");
type = getType(key);
if (type == "Status") {
var Call = key.substring(7, 17);
var OldStat = vals[0];
var NewStat = vals[1];
var Date1 = vals[2];
var Time1 = vals[3];
var miles = vals[4];
try {
stat(Call, OldStat, NewStat, Date1, Time1, miles, key);
}
catch (e) {
alert("Status " + e);
return;
}
}
else if (type == "Notes") {
var Call = key.substring(6, 16);
var Notes = item;
try {
addNotes(Call, Notes);
}
catch (e) {
alert("Notes " + e);
return;
}
}
else if (key == "StartNCTime" || key == "EndNCTime") {
var TechID = vals[0];
var Date = vals[1];
var Time = vals[2];
var Activity = vals[3];
var Location = vals[4];
var Type = vals[5];
try {
logTime(TechID, Date, Time, Activity, Location, Type,
}
catch (e) {
alert(key + ' ' + e);
return;
}
}
}
catch (e) {
alert(key + ' ' + e);
return;
}
}
function stat(Call, OldStat, NewStat, Date1, Time1, miles, key) {
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: "Service.asmx/update_Stat",
data: '{ CallNumber:"' + Call + '", OldStat:"' + OldStat + '", NewStat:"' + NewStat + '", Date1:"' + Date1 + '", Time1:"' + Time1 + '", Miles: "' + miles + '"}',
success: function (data) { },
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert("Sync Update Stat: " + err.Message);
location = location;
}
});
}
function logTime(TechID, Date, Time, Activity, Location, Type, key) {
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: "Service.asmx/nonCallTime",
data: '{ TechID:"' + TechID + '", Date1:"' + Date + '", Time1:"' + Time + '", Activity:"' + Activity + '", Location:"' + Location + '", Type: "' + Type + '"}',
success: function (data) { },
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert("Sync Non Call Time: " + err.Message);
location = location;
}
});
}
function addNotes(Call, Notes) {
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: "Service.asmx/addNote",
data: '{ Call:"' + Call + '", Notes:"' + Notes + '"}',
success: function (data) { },
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert("Sync Notes: " + err.Message);
location = location;
}
});
}
You have to use callbacks.
function ajax1(){
//..some code
//on ajax success:
ajax2();
}
//etcetera...
Or might I suggest using a javascript library like jQuery to synchronize your ajax requests for you.
set the third parameter in xmlhttp object's open method to false to make it synchronous.
http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
A general pattern for making actions serial would be such:
function doAjax(data, cb) {
...
// when ready call cb
}
(function (next) {
var xhr = doAjax(data, next);
})(function (next) {
var xhr = doAjax(data, next);
})(function (next) {
doAjax(data);
});
Doing so in a for loop would require recursion.
(function next() {
if ( i < n ) {
doAjax(data[i++], next);
}
})();

Categories

Resources