Hello i m using an ajax function to get back the goog day from a script on my php file ... It' not working i don't understand why,
please help i need ajax dont want to reload each time a date is picked in my php calendar
my HTML is
<p class="texte choixDate"></p>
so my jquery code is
$("#calendrier td a").click(function(){
var jour=$(this).text();
var mois="<?php echo $mois2;?>";
var annee="<?php echo $year;?>";
$.ajax({
url : 'requete.php',
type : 'GET',
data : 'jour='+jour+'&mois='+mois+'&annee='+annee,
dataType : 'text',
success : function(text){ // code_html contient le HTML renvoyé
$(".texte.choixDate").empty();
$(".texte.choixDate").append("<i class='fa fa-arrow-circle-down fa-2x' aria-hidden='true'></i><br/>Vous avez choisi le " + text + " " + jour + " " + mois + " " + annee +"<br/><br/><a class='btn' href='accueil.php?val2=1#agenda1' title='Valider'>Valider</a>");
}
});
});
and my php file is
$semaine = array("Lundi","Mardi","Mercredi","Jeudi","Vendredi","Samedi","Dimanche");
$mois=$_GET["mois"];
$jour=$_GET["jour"];
$annee=$_GET["annee"];
$moisAtester2= mktime(0,0,0,$mois,$jour,$annee);
$jourSem=$semaine[date("w",$moisAtester2)];
echo $jourSem;
THANKS FOR HELP !!
just use the datetime picker where you can get do that
onClose: function () {
$scope.isSelected = true;
var iMonth = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
var iYear = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
$(this).datepicker('setDate', new Date(iYear, iMonth, 1));
}
Use onClose function to call ajax
Related
I wrote this php code to show server date and time but I'd like to display realtime change in server date and time every 1 Sec
<p><?php echo "Server Time " . date("Y-m-d h:i:s"); ?> (GMT) UTC +0 UK/London</p>
Pls help me, thank you
You will need to use Javascript, something like this:
<body>
<p id="time"></p>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
var timestamp = '<?=time();?>';
function updateTime(){
$('#time').html(Date(timestamp));
timestamp++;
}
$(function(){
setInterval(updateTime, 1000);
});
</script>
if you still need a real time clock that uses your server clock you could try this. im using twig {{now|date('Y/m/d H:i:s')}}. but you could also use php's <?php echo date('Y/m/d H:i:s');?>. its basically using localStorage to store the server date on localstorage and setSeconds updates the localstorage every 1 second , while the now variable loads the localstorage date and converts it to js date format. I then use the {{now|date('Y/m/d H:i:s')}} inside the date element for fallback in case localstorage is not enabled.
try {
localStorage.setItem('today', new Date("{{now|date('Y/m/d H:i:s')}}");
setInterval(function clock() {
var month = [
"Jan", "Feb", "Marh", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Octr", "Nov", "Dec"
];
var now = new Date(localStorage.getItem('today'));
now.setSeconds(now.getSeconds() + 1);
localStorage.setItem('today', now);
var G = format(now.getHours() % 12 || 12);
var i = format(now.getMinutes());
var s = format(now.getSeconds());
var M = month[now.getMonth()];
var d = format(now.getDate());
var Y = now.getFullYear();
function format(data) {
return (data < 10 ? data = "0" + data : data);
}
$("#date").html(M + ". " + d + ", " + Y + " " + G + ":" + i + ":" + s);
return clock;
}(), 1000);
} catch(e) {
console.log(e);
}
you can get server time when page loaded and use javascript function to update time locally persecond.
HTML PAGE
<script> var JS_BASE_URL = 'http://YOURSERVER/';</script>
<script src="assets/js/jquery-3.4.1.min.js" type="text/javascript"></script>
<script src="clock.js" type="text/javascript"></script>
</head>
<body>
Server Time <span id="server_time">00:00:00</span>
</body>
clock.js
var url = JS_BASE_URL+'/script.php';
var _h = 0;
var _m = 0;
var _s = 0;
$.ajax({
url: url,
type: 'GET',
dataType: 'JSON',
success: function(res) {
var timer = setInterval(serverTime,1000);
function serverTime(){
h = parseInt(res.hour)+_h;
m = parseInt(res.minute)+_m;
s = parseInt(res.second)+_s;
if (s>59){
s=s-60;
_s=_s-60;
}
if(s==59){
_m++;
}
if (m>59){
m=m-60;
_m=_m-60;
}
if(m==59&&s==59){
_h++;
}
_s++;
$('#server_time').html(append_zero(h)+':'+append_zero(m)+':'+append_zero(s)); }
function append_zero(n){
if(n<10){
return '0'+n;
}
else
return n;
}
}
});
script.php
<?php
$data = array('fulldate'=>date('d-m-Y H:i:s'),
'date'=>date('d'),
'month'=>date('m'),
'year'=>date('Y'),
'hour'=>date('H'),
'minute'=>date('i'),
'second'=>date('s')
);
echo json_encode($data);
?>
check on github: https://github.com/mdanielk/server_time
To display changing clock showing server time by using Ajax. Create two files for this one is the file sending request and receiving data with Ajax.
server-clock.php
develop a script where by clicking a button we can send a request to server to get the data. In the body of this file we have a button.
<input type=button value=
'Get Server Time' onclick="timer_function();">
To this script we will add a timer to recursively call the same Ajax function in every second. This will get data from every second so we can display a changing clock showing server time.
function timer_function(){
var refresh=1000; // Refresh rate in milli seconds
mytime=setTimeout('AjaxFunction();',refresh)
}
Timer function: timer_function()
On click of this button it trigger a function which uses a timer setTimeout. Inside this timer function it can change the refresh rate which is in milliseconds. Within this function we call our main Ajax function AjaxFunction()
function timer_function(){
var refresh=1000; // Refresh rate in milli seconds
mytime=setTimeout('AjaxFunction();',refresh)
}
At the end of AjaxFunction() call again timer_function() to make it recursive.
tt=timer_function();
In the main AjaxFunction() send request to clock.php file and get the server time. This data is displayed using a div layer.
if(httpxml.readyState==4)
{
document.getElementById("msg").innerHTML=httpxml.responseText;
document.getElementById("msg").style.background='#f1f1f1';
}
The second file is the simple PHP file with one line of code giving current date and time of server. clock.php
<?Php
echo date("d/m/y : H:i:s", time());
?>
download the files here
I'm trying using jquery onchange. Please take a look:
<script>
$(document).ready(function() {
$("#reservation").change(function() {
var date = $("#reservation").val();
$.ajax({
url: '<?=base_url();?>home',
type: 'POST',
data: {date_search : date},
success: function() {
location.reload();
}
});
});
});
</script>
here is my controller:
else if(isset($date_search)){
$data['var'] = "Range Date";
$explode = explode('-',$date_search);
$start_date = inggris_date($explode[0]);
$end_date = inggris_date($explode[1]);
$data['tgl'] = $this->modelmodel->showdata("select MONTH(tanggal) Tanggal from transaksi where (tanggal between '$start_date' and '$end_date')and outlet = '".$this->session->userdata('username')."' group by MONTH(tanggal)");
$data['angka'] = $this->modelmodel->showdata("select TOP 12 (cash + cc + dc + flash + piutang + reject + disc50) total from transaksi where (tanggal between '$start_date' and '$end_date')and outlet = '".$this->session->userdata('username')."'");
}
$view = 'dummy';
$this->go_to($view,$data);
There is no problem with my query. I'm able to get the result. My question is, how do i refresh my page with the result because when i'm use location.reload the result back to default.
My function above is a part of my controller. Here is the fullscript of my function http://pastebin.com/i5UeypGG
Create another function in your controller place the current logic of the above function in it, in the function for the ajax return a path to the new link,
with the help of window.location when the ajax is complete you redirect to the new controller function.
From what i can tell your function is only displaying data so it may be easier to just use a simple link to a new controller function
From now on. I change my Jquery. I'm using https://github.com/mgalante/jquery.redirect
<script>
$(document).ready(function() {
$("#reservation").change(function() {
var date = $("#reservation").val();
$.redirect('<?=base_url();?>home', {date_search : date});
});
});
</script>
And it's work for me
I need some help to resolve a problem.
I'm trying to send some datas from a form ROW to a php file.
Here's the first php code (It's inside an echo and value come from a MySQLi query):
<form id=\"comedivid\" method=\"post\">
<input class=\"numer-qua\" type=\"number\" id=\"dadivid\" min=\"0\" max=".$_GET['qua']." autofocus autocomplete=\"off\" name=\"dadivid\" maxlength=\"4\" size=\"5\">
<input type=\"hidden\" value=\"".$row["id_tes"]."\" name=\"ord\" id=\"ord\">
<input type=\"hidden\" value=\"".$_GET['codice']."\" name=\"cod\" id=\"cod\">
<input type=\"hidden\" value=\"".$_GET['qua']."\" name=\"arr\" id=\"arr\">
<input type=\"hidden\" value=\"".$row['descri']."\" name=\"desc\" id=\"desc\">
<input type=\"hidden\" value=\"".$row['unimis']."\" name=\"um\" id=\"um\">
<input type=\"hidden\" value=\"".$row['quanti']."\" name=\"qua\" id=\"qua\">
<input type=\"hidden\" value=\"".$row['prelis']."\" name=\"pre\" id=\"pre\">
<input type=\"hidden\" value=\"".$row['sconto']."\" name=\"sco\" id=\"sco\">
<input type=\"hidden\" value=\"".$row['codvat']."\" name=\"cva\" id=\"cva\">
<input type=\"hidden\" value=\"".$row['pervat']."\" name=\"iva\" id=\"iva\">
<input type=\"hidden\" value=\"".$row['codric']."\" name=\"ric\" id=\"ric\">
<button id=\"dividili\" class=\"btn btn-blue\" type=\"submit\"><i class=\"fa fa-copy\"> Dividi Riga</i></button>
\n";
The form is included in a table. The query may give more as one result.
Here's my AJAX code:
$("#dividili").click(function(){
$(this).closest("form#comedivid").submit(function(event) {
event.preventDefault();
var dadivid = $("#dadivid").val();
var ord = $("#ord").val();
var cod = $("#cod").val();
var arr = $("#arr").val();
var desc = $("#desc").val();
var um = $("#um").val();
var qua = $("#qua").val();
var pre = $("#pre").val();
var sco = $("#sco").val();
var cva = $("#cva").val();
var iva = $("#iva").val();
var ric = $("#ric").val();
$.ajax({
type: "POST",
url: "../../modules/acquis/dividi.php",
data: "dadivid=" + dadivid + "&ord=" + ord + "&cod=" + cod + "&arr=" + arr + "&desc=" + desc + "&um=" + um + "&qua=" + qua + "&pre=" + pre + "&sco=" + sco + "&cva=" + cva + "&iva=" + iva + "&ric=" + ric,
success: function(){alert('success');}
});
});
});
It's not working, no data are sent to URL.
Is it because the form is in more rows?
Or is there a mistake in my code?
I tried with serialize also, with no results.
Here's the code:
$("#dividili").click(function(e){
$.ajax( {
type: "POST",
url: "../../modules/acquis/dividi.php",
data: $('#comedivid').serialize(),
success: function( response ) {}
});
});
Thank you so much for your help!
I would suggest using serialize():
$("#dividili").click(function(){
$(this).closest("form#comedivid").submit(function(event) {
event.preventDefault();
var form_data = $('form#comedivid').serialize();
// or
var form_data = $(this).serialize();
// try to output that just to make sure you are doing it right
console.log( form_data );
// or
alert( form_data );
$.ajax({
type : "POST",
url : "../../modules/acquis/dividi.php",
data : form_data,
success : function(){alert('success');}
});
});
Since you already tried that, and if the output is ok, then it's a problem with your PHP, so try to output at the beginning of your file what was received:
<?php
echo '<pre>';
print_r( $_POST );// or $_REQUEST for both $_POST and $_GET
echo '</pre>';
die;
// the rest of your code...
If everything is received well in PHP, you need to make sure you are using the right way to fetch your data, like $dadivid = $_POST["dadivid"];
jQuery 'serialize' method made data like get query form.
so, Data length would be limited in apache configuration.
Try use this custom method.
(function($) {
$.fn.serializeObject = function () {
"use strict";
var result = {};
var extend = function (i, element) {
var node = result[element.name];
if ('undefined' !== typeof node && node !== null) {
if ($.isArray(node)) {
node.push(element.value);
} else {
result[element.name] = [node, element.value];
}
} else {
result[element.name] = element.value;
}
};
$.each(this.serializeArray(), extend);
return result;
};
});
How to use is same default jQuery 'serialize' method.
I am using an Ajax call to PHP to return a string of dates that a user is available, To make it dynamic.
I am returning the string back to my jQuery as :
['7-15-2013','7-16-2013','7-17-2013','7-18-2013','7-19-2013','7-20-2013','7-21-2013','7-22-2013']
However when I initialise the datePicker, That string of dates does not load.
I am not too sure as to why, I suspect its my success function after my Ajax call.
My jQuery code looks like this :
$('.vendor_id').change(function()
{
var vendor_id = $('option:selected', this).attr('title');
var url = "/admin/po/get_user_dates/" + vendor_id;
$.ajax({
type : "POST",
url : url,
success: function(unavaildates)
{
var disabledDays = unavaildates;
function disableAllTheseDays(date) {
var m = date.getMonth(), d = date.getDate(), y = date.getFullYear();
for (i = 0; i < disabledDays.length; i++) {
if($.inArray((m+1) + '-' + d + '-' + y,disabledDays) != -1) {
return [false];
}
}
return [true];
}
$('.booking-date').datepicker(
{
beforeShowDay: disableAllTheseDays,
numberOfMonths: 2,
dateFormat: 'DD, d MM, yy',
showButtonPanel: true
}
)
}
})
})
Hope someone call help me on this.
Quick Update.. On assigning disabledDays to ['7-15-2013','7-16-2013','7-17-2013','7-18-2013','7-19-2013','7-20-2013','7-21-2013','7-22-2013'] the datePicker works...?
Thanks in advance.
Because you are retrieving a string and not an array from the server.
I would suggest to return the string without square brakets "'7-15-2013','7-16-2013','7-17-2013','7-18-2013','7-19-2013','7-20-2013','7-21-2013','7-22-2013'" from the server and create the array like this :
var unavaildates = "'7-15-2013','7-16-2013','7-17-2013','7-18-2013','7-19-2013','7-20-2013','7-21-2013','7-22-2013'"
var disabledDays = unavaildates.split(',');
So I got a select menu and when an user select an option, it calls a post function via ajax that generates some table rows via PHP and then it returns the html coding for it. In it, there is an Add button.
What I am trying to do is that when the user clicks the add button, a form shows up.
But for some reason, it is not working...
Here is the code:
$(document).ready(function () {
$(".add_form").hide();
$("#console").change(function () {
var id = $(this).val();
var dataString = 'console_id=' + id;
$.ajax({
type: "POST",
url: "generate-games-list",
data: dataString,
cache: false,
success: function (html) {
$("#games_table_body").html(html);
}
});
});
$(".add_button").click(function () {
alert("HELLO");
var id = this.id;
$.post('manage_games', 'game_id=' + id, function (response) {
alert(response);
});
$("#game_id").val(id);
$(".add_form").show();
});
});
Here is the PHP code that returns the table rows:
$console = Console::find(Input::get('console_id'));
$type = GameType::find(Input::get('type_id'));
if(!Input::has('console_id'))
return "Error";
else{
foreach($console->games()->get() as $console_game){
$available_consoles_string = "";
$game_types_string = "";
//Get all the consoles the game can be played on
foreach($console_game->consoles()->orderBy('name', 'asc')->get() as $available_consoles){
$available_consoles_string = $available_consoles_string . " " .$available_consoles->name .", ";
}
//Get all the types that the game falls in
foreach($console_game->types()->orderBy('type', 'asc')->get() as $game_types){
$game_types_string = $game_types_string . " " .$game_types->type .", ";
}
return "<tr><td>" .$console_game->name. "</td><td>". $available_consoles_string. "</td><td>" .$game_types_string. "</td><td><input type='button' id='" .$console_game->id. "' class='add_button' value='Add'/> / View</td></tr>";
}
}
Any idea why it is not working? When I mean not working, I mean the alert is not showing up but I am not getting any error on the Chrome Console...
Thanks,
Ara
Simply use .on():
$(document).on("click", ".add_button", function(){
// your event code
});
When your js runs a click event is attached to all current elements with the .add_button class. However, you're adding extra buttons via ajax and these won't have trigger the same click event.
To fix this use the code above. It attaches the event to the document so even if you add buttons once the page has loaded the click event will be triggered by them.