I hope I am able to explain what I'm trying to do properly, but I am trying to use AJAX to pass (using POST) quite a number of Dates to PHP file, to do checks if dates are valid (e.g. 31-FEB, 31-Apr).
I am not sure how many dates there will be, there are 12 entry boxes, maximum case 12 dates, minimum case 1. So the number of dates passed to the PHP file could be anything.
I want to be able to "roll" through (using numbers 0 1 2 like in an array) all the dates (and their D, M, Y) inside the PHP file, and also "roll" through dates passed back to the JS from PHP.
Jquery
var DAT = {}; //is such a declaration valid for an array?
k=0;
for(x=1;x<=12;x++)
{ I = "#ED" + x;
d= $(I).children('.dd').val();
m= $(I).children('.mmm').val();
y= $(I).children('.yyyy').val();
c= date_chk(d,m,y); //returns '1' if date ok
if(c==1) //Date OK
{ DATE[k] = [d,m,y];
alert(DATE[k][0]+" "+DATE[k][1]+" "+DATE[k][2]);
k++;
}
}
AJ.onreadystatechange = function(){
if((AJ.readyState == 4) && (AJ.status == 200))
{ var PH_RP = AJ.responseText;
alert("PHP REPLY:: " + PH_RP);
var DATE_Lst = JSON.parse(PH_RP);
alert("DATE1 Day::" + DATE_Lst.DT[0][0] + "DATE1 Month::" + DATE_Lst.DT[0][1] +"DATE1 Year::" + DATE_Lst.DT[0][2] );
alert("DATE2 Day::" + DATE_Lst.DT[1][0] + "DATE2 Month::" + DATE_Lst.DT[1][1] +"DATE2 Year::" + DATE_Lst.DT[1][2] );
}
var para = "DATESS=" + DATE; //? how do I send the whole stack of dates to the PHP file?
AJ.open("POST", "PHP/4_PHP_Check_Dates.php", true);
AJ.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
AJ.send(para);
Here is the PHP file::
$LOGARRY['DT'] = $_POST['DATESS'];
or
$LOGARRY['DT1'] = $_POST['DATESS'][1];
$LOGARRY['DT2'] = $_POST['DATESS'][2];
echo json_encode($LOGARRY);
Thanks.. any help appreciated
If you just want to check if a date is valid, you do not need the roundtrip to PHP, you can do that right in Javascript.
Detecting an "invalid date" Date instance in JavaScript
You asked how to send an array to PHP via XMLHttpRequest.
Since I avoid JQuery like the plague, I cannot really comment on your code, but here is a simple way to send X dates to you PHP script:
Three things:
it is simple (no errorchecking etc)
it used GET. Feel free to make it into a POST.
Open your javascript console to see the result.
<html>
<body>
<script>
// I assume you have an array with strings that might represent dates, like:
// dates[0] = "2022-10-09";
// dates[1] = "2021-13-09";
// ....
// dates[19] = "I am surely not a date";
// dates[20] = "2000-01-05";
var dates = [];
dates[0] = "2022-10-09";
dates[1] = "2021-13-09";
dates[2] = "I am surely not a date";
dates[3] = "2000-01-05";
var myTestDates = JSON.stringify(dates);
var myReq = new XMLHttpRequest();
myReq.addEventListener("load", reqListener);
var url = "dateChecker.php?dates=" + encodeURIComponent(myTestDates);
url += "&rand=" + Math.random();
myReq.open("GET", url , true);
myReq.send();
function reqListener () {
let passeddates = JSON.parse(this.responseText);
console.log(passeddates);
}
</script>
</body>
</html>
And the PHP script (named dateChecker.php):
<?php
$passedDates = json_decode( $_GET["dates"] );
$checkedDates = [];
foreach ($passedDates as $oneDate){
$d = DateTime::createFromFormat('Y-m-d', $oneDate);
$valid = ($d && $d->format('Y-m-d') === $oneDate) ? "valid" : "not valid";
$checkedDates[] = $oneDate . " is {$valid}";
}
echo json_encode($checkedDates);
?>
Related
Sometimes function reload(); does't update the div's content. I call this function when clicking a button. Sometimes only one div won't update. Random div, on a random click. Sometimes first click won't work. The div content won't show any error, just a previous not updated number. and when I click the button again it updates and shows the correct one.
Example of the bug (Increasing the #number_input by one every time I click):
div content shows: 1, 2, 2, 4
The problem is with those 2s, 3 is missing. In database the number is correct.
I'm running a local server (XAMPP). Same problem in Firefox, Chrome and IE.
No errors in firebug console. Requests are done correctly but returned value sometimes wrong. Usually only one array item is wrong, the one returned from the database.
Exactly same ajax code with different parameters (on complete) on different button works fine.
PS: Changed my var names into shorter ones so they are eye friendly
Button HTML:
<button id="xButton" class="btn btn-info">Text</button>
Button JS:
document.getElementById('xButton').onclick = function() {
var val = $('#number_input').val();
if (val > 0)
{
var xx = 1;
var yy = 1;
properties(xx, yy, val); //this updates the database by current val + val. Works correctly. Values always updated, no errors there. Clean and simple code. No way this is the source of problem.
number_input.value = 0;
xButton.textContent = ("bla bla"); //just resets the text
p1_reload();
}
}
jQuery:
function reload() {
$.ajax({
type: 'POST',
url: 'example.php',
cache: false,
data: {reload: "action"},
dataType:"json",
success: function(data) {
var xres = new Array();
xres = data;
document.getElementById("x1").textContent = xres[0];
document.getElementById("x2").textContent = xres[1];
document.getElementById("x3").textContent = xres[2];
document.getElementById("x4").textContent = xres[3];
//these two functions has not connection with the updated divs. They don't update or even read them. So, there shouldn't be any problems.
xFunction();
yFunction();
}
});
}
PHP:
if(isset($_POST['reload'])) {
if ( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
try
{
require_once("session.php");
$auth_user = new xClass();
$user_id = $_SESSION['user_session'];
$stmt = $auth_user->runQuery("SELECT * FROM blabla WHERE user_id=:user_id LIMIT 1");
$stmt->execute(array(":user_id"=>$user_id));
$userRow=$stmt->fetch(PDO::FETCH_ASSOC);
$xxx = $userRow['xxx'];
$yyy = $userRow['yyy'];
$zzz = $userRow['zzz'];
$qqq = ($xxx * $yyy) + ($zzz + $yyy + $xxx);
$xres = array();
$xres[0] = $xxx;
$xres[1] = $yyy;
$xres[2] = $zzz;
$xres[3] = $qqq;
$result = json_encode($xres);
echo $result;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
}
Database return simple integer numbers. No triggers or decimal numbers.
jQuery version: 1.12.4 min.
Clicking every few second (no frequent clicking). Request and response complete in 10-38 ms.
The problem is somewhere in your button js as well as jQuery source. Try replacing textContent with innerHTML(for plain js) or html(JQuery)After replacement it would be
document.getElementById("x4").innerHTML = xres[3]; or as you are using jQuery you could have $("#x4").html(xres[3]).
I want to add the result value plus already exists value in that textbox. but addition is not working concatenation is working
$.post('includes/ajax_timesheet.php', {
'action': 'add_kitamount',
'jobnumber': jobno,
'invoiceno': inv_no
}, function (data) {
var tot1 = $('#tot_dayrate').val();
var tot2 = $.trim(data);
var tot = tot1 + tot2;
alert(tot);
$("#tot_dayrate").val(tot);
});
Concatenation is happening because the values are being treated as string by + operator . Parse the values to number using any of the availaible javascript functions and then you will get correct total.
Ofcourse you need to handle for invalid inputs . Below is only showing an example for parse to number function.
var tot = parseInt(tot1) + parseInt(tot2);
Check here for string to number conversion and good explanation of difference between Number() and parseInt() , parseFloat() functions.
var tot = parseFloat(tot1) + parseFloat(tot2);
Convert to number
var tot = Number(tot1) + Number(tot2);
Or
var tot = parseInt(tot1) + tot2;
.val() returns the value of the element in String. You will first need to convert to to Number for performing arithmetic operations.
You can use Number() to convert the string into numbered format.
So your code would look something like this,
var tot1 = $('#tot_dayrate').val();
if(tot1!='') {
tot1=Number(tot1);
}
var tot2 = $.trim(data);
if(tot2!='') {
tot2=Number(tot2);
}
var tot = tot1 + tot2;
Make sure to check for blank value before converting String into int.
I have a json response from php to ajax. The thing is depending on the value entered in a text box the number of json arrays vary. Example: sometimes it may return {"count1":10, "ccc1":30} and sometimes like this {"count1":10, "ccc1":32, "count2":40, "ccc2":123,"count3":32,"ccc3":21}. I extract the value in jquery this way:
success: function(response){
var count = response.count1;
//do something
}
But now since the number of counts are different I used a loop. Question is I can figure out how many of them I am receiving but how can I process them? The var count = response.count needs to be specific right? I cannot just concate any strings like this:
var count = 0;
while(something){
count = count + 1;
var str = "count"+count;
var whatever = response.str;
}
So, can someone please help me with a suitable solution in this case?
You are on the right track there. Something like this should work for you.
var i = 1;
while(response['count' + i]) {
var count = response['count' + i++];
}
You can access the properties as if they were array indices. so response['count'+i] works.
Loop through all properties and add them in a variable like following.
var response = { "count1": 10, "ccc1": 32, "count2": 40, "ccc2": 123, "count3": 32, "ccc3": 21 };
var count = 0;
for (var prop in response) {
if (prop.startsWith('count'))
count += response[prop];
}
console.log(count);
To retrieve all values use jQuery $.each function.
var data_tmp = '{"count1":10, "ccc1":32, "count2":40, "ccc2":123,"count3":32,"ccc3":21}';
var data = $.parseJSON(data_tmp);
$.each(data, function(k,val){
if(k.toLowerCase().indexOf("count") >= 0){
$('.wr').append('<div>' + val + '</div>')
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="wr"></div>
success: function(response){
var count = response.count1;
var object = JSON.parse(response);
alert(object.length);
for (i = 0; i < object.length; i++) {
console.log(object[i]);
}
}
I have a problem with jQuery to obtain each value from jSon string and modify a div or span or other id with value obtained from a jSon string.
At the start of each PHP file i have an SQL request generate an hidden input with a jSon string as value. This is for multilanguage for example in english the generated string is
<input type="hidden" id="page_json_language_home" value='{
"label_title":"My WebSite",
"label_settings":"Settings",
"label_subscription":"Subscription"
}' />
for french :
<input type="hidden" id="page_json_language_home" value='{
"label_title":"Mon site web",
"label_settings":"Parametres",
"label_subscription":"Abonnement"
}' />
this is work fine !
After that i have a javascript using jquery to match each label_xxx with value
i have many html code like this
<title id="label_title></title>
<div id="label_settings"></div>
or
<span id="label_subscription"></span>
This is my (partial) code in my javascript file i called to obtain the json string from hidden input :
var _getPageJsonLanguage = function(id) {
if (!id)
id = "page_json_language";
else
id = "page_json_language_" + id;
var json = $("#" + id).val();
var data = bsc.data.jsonParse(json);
return data;
};
This is work fine too !
The code in problem is :
data_language = bsc.page.getPageJsonLanguage("home");
var j = 0;
var language = [];
for (i in data_language) {
console.log("i in language = " + i);
language[j] = i;
console.log("language[j] = " + language[j]);
$("#" + i).html(language[j]);
j++;
}
The result can i obtain in browser 1) undefined for each label or 2) label_xxx for each label_xxx
I need help to access each value of each label_xxx .
I can't obtain the value, this is my last try....
I believe the problem is in your for in loop, you never actually grab the value, only the key:
for (i in data_language) {
console.log("i in language = " + i);
language[j] = data_language[i]; //changed this line to actually grab the value
console.log("language[j] = " + language[j]);
$("#" + i).html(language[j]);
j++;
}
If you are receiving undefined, it may be due to the JSON not being parsed correctly. Since your using jQuery, you can always run $.parseJSON(json) to be sure.
Fiddle accessing your JSON in a for in loop and logging: http://jsfiddle.net/tymeJV/CKBLc/1/
I hope this will work -
var data_language = JSON.parse($("#page_json_language_home").val());
var language = [];
var j = 0;
for (i in data_language) {
console.log("i in language = " + i);
language[j] = data_language[i];
console.log("language[j] = " + language[j]);
$("#" + i).html(language[j]);
j++;
}
I want to do a calculation between selectbox values. The problem with my code is that the first part of the calculation only gives me 0, which Motherboard valuequantity. the second part works fine which Chassisquantity. My formulas is motherbord*Quanity+chassis*quantity.
Here is my code:
function calculate() {
var parsedMotherboard = parseFloat(document.calcform.Motherboard.value || 0);
var parsedQuantity = parseFloat(document.calcform.Quantity.value || 0);
var parsedChassis = parseFloat(document.calcform.Chassis.value || 0);
var parsedQuantity1 = parseFloat(document.calcform.Quantity1.value || 0);
document.calcform.total.value = (parsedMotherboard * parsedQuantity + parsedChassis * parsedQuantity1);
}
It helps if you format your code more neatly:
function calculate() {
var parsedMotherboard = parseFloat(document.calcform.Motherboard.value || 0);
var parsedQuantity = parseFloat(document.calcform.Quantity.value || 0);
var parsedChassis = parseFloat(document.calcform.Chassis.value || 0);
var parsedQuantity1 = parseFloat(document.calcform.Quantity1.value || 0);
document.calcform.total.value = (parsedMotherboard * parsedQuantity +
parsedChassis * parsedQuantity1);
}
Have you checked that you are getting the correct values from the form? Make sure that the default option (I'm assuming the first one with a value of 0) has the selected attribute set so that one option is always selected.
Some other tips:
store a reference to the form, it's more efficient and makes for neater code
Since you set the value, you know it's formatted correctly so rather than using parseInt, just use the uary + operator to convert to number
Personal preference, but use shorter variable names so they're easier to work with
I don't understand the need for || 0. If the user doesn't select something, isn't the default value 0?
Here is an updated version:
function calculate() {
var form = document.calcform;
var mb = +form.Motherboard.value;
var mbQty = +form.Quantity.value;
var ch = form.Chassis.value;
var chQty = form.Quantity1.value;
form.total.value = mb*mbQty + ch*chQty;
}
Because each string value is involved in a multiplication, there is no need to explicitly convert to number, that will happen as a consequence of the multiplication, so you could write:
function calculate() {
var form = document.calcform;
form.total.value = form.Motherboard.value * form.Quantity.value +
form.Chassis.value * form.Quantity1.value;
}
do it with jQuery ...
$('#selectbox1').change(function() {
// do ajax if you want or store
var x = $('#selectbox1').attr('value'); // or you can use this.value
// and so on
});
and sum up the other selectboxes