how to pass jquery date parameters in php - javascript

Please help me.. I have the following codes..
//Get the value of Start and End of Week
$('#weeklyDatePicker').on('dp.change', function (e) {
var value = $("#weeklyDatePicker").val();
var firstDate = moment(value, "MM/DD/YYYY").day(0).format("MM/DD/YYYY");
var lastDate = moment(value, "MM/DD/yyyy").day(6).format("MM/DD/YYYY");
$("#weeklyDatePicker").val(firstDate + " - " + lastDate);
});
now I want to pass the firstDate and the lastDate to a php. How should I do this. and how can I retrieve the passed value in the php. I'm not very familiar with javascripts. Hope anyone can help me. Thanks in advance.
Here is my full code..
JS tags
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.css" rel="stylesheet"
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.1/moment.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/bootstrap.datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script>
HTML
<div class="input-group" id="DateDemo">
<input type='text' id='weeklyDatePicker' placeholder="Select Week" class="form-control" />
<span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span>
JS
$("#weeklyDatePicker").datetimepicker({
calendarWeeks:true,
format: 'MM/DD/YYYY'
});
//Get the value of Start and End of Week
$('#weeklyDatePicker').on('dp.change', function (e) {
var value = $("#weeklyDatePicker").val();
var firstDate = moment(value, "MM/DD/YYYY").day(0).format("MM/DD/YYYY");
var lastDate = moment(value, "MM/DD/yyyy").day(6).format("MM/DD/YYYY");
$("#weeklyDatePicker").val(firstDate + " - " + lastDate);
alert(firstDate);
$.post("SAMPLE1.php",{"fdate" : firstDate ,"ldate" : lastDate});
});
$('#DateDemo').on('dp.change', function (e) {
var kk = $("#weeklyDatePicker").val();
$("#output").html(
" Week Number: " + moment(kk, "MM/DD/YYYY").week() + " of " +
moment(kk, "MM/DD/YYYY").weeksInYear()
);
});
SAMPLE1 CODE
<?php
echo $_POST["fdate"]; //for firstdate
echo $_POST["ldate"]; //for lastdate
?>

You can use jquery for that. Try this code :
YOUR JS FILE CODE :
$('#weeklyDatePicker').on('dp.change', function (e) {
var value = $("#weeklyDatePicker").val();
var firstDate = moment(value, "MM/DD/YYYY").day(0).format("MM/DD/YYYY");
var lastDate = moment(value, "MM/DD/yyyy").day(6).format("MM/DD/YYYY");
$("#weeklyDatePicker").val(firstDate + " - " + lastDate);
$.post("main.php",{fdate : firstDate ,ldate : lastDate},function(data) {
alert(data);
});
});
YOUR PHP FILE CODE (main.php)
<?php
if(isset($_POST["fdate"])) {
echo $_POST["fdate"]; //for firstdate
}
if(isset($_POST["ldate"])) {
echo $_POST["ldate"]; //for lastdate
}
?>
Make sure both the files are in same folder.

I would use $.ajax() function, which will let you handle the error status as well, because it is both a good practice to handle errors for the users and an indicator of what is going wrong with your script.
$.ajax({
url: 'test.php',
type: 'POST',
data: {fdate : firstDate ,ldate : lastDate},
dataType: 'text',
beforeSend: function(){
// initiate some spinner or loading infobox
// to inform the user about the AJAX request
},
success: function(response){
alert(response);
// you may use result like any standard argument
// and call or trigger other functions according to its value
},
error: function(jqXHR, textStatus, errorThrown){
alert(textStatus + ': ' + errorThrown);
// call some error handler or do nothing
},
complete: function(){
// close the spinner or loading box
}
});
In your PHP file, you get the variables as $_POST['fdate'] and $_POST['lDate']. Once you complete the query and get the results, echo a response something like that:
echo 'success';
or
echo 'failure';
according to the result of the query. You may use any string, not just success or failure. Just don't forget that is what you will handle in the success part of your $.ajax() function and not the error part of it. The error part is only for whatever goes wrong with the request (e.g. file not found or server error).
Well, here is the tricky part: If the only thing you want to return is a status, you may use dataType: 'text' in your $.ajax() function as I did in this example. However, if you want to return an object with some useful data, such as what has gone wrong with the PHP query or what has been accomplished by the PHP query, then you'd better to use dataType: 'json' and get a JSON response. In such a case, the end of your PHP script will change too.
$result = ['statusCode'=>1,'details'=>'Some details according to the query here'];
echo json_encode($result);
The success handler of your $.ajax() function will get an object as the argument (i.e. response will be an object) which you can use like this:
alert(response.statusCode); // will alert 1

Ajax is probably the easiest.
Javascript:
$.get("test.php", { firstDate: firstDate, lastDate: lastDate } );
or
$.post("test.php", { firstDate: firstDate, lastDate: lastDate } );
and in php
<?php
echo $_REQUEST['firstDate'];
echo $_REQUEST['lastDate'];
?>

Hi Kath Dee please check below code, I hope solve your problem using below code.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script type="text/javascript">
$('#weeklyDatePicker').on('dp.change', function (e) {
// I am using test value, you can change var value base on id.
var firstDate = '08/02/2016';
var lastDate = '10/02/2016';
//$("#weeklyDatePicker").val(firstDate + " - " + lastDate);
$.post("test.php",{fdate : firstDate ,ldate : lastDate},function(data) {
alert(data);
$("#weeklyDatePicker").val(data);
});
});
</script>
<input type="text" value="" id="weeklyDatePicker" />
test.php
<?php
// set your format as you want for display.
echo $_POST['fdate'].'-'.$_POST['ldate'];
?>
I hope this is working fine for you.

Related

php variable to javascript (via json)

I know this has been discussed before but I can't seem to make anything work. I'm trying to pass the variable $thedate from PHP file mainclass.php to the variable datestr in a JS function from the file footer_script.php
JS:
function getsched(str)
{
//some code
$.ajax({
type: 'POST',
url: 'mainclass.php',
data: 'date=' + str + '&form=getsched',
success: function(data) {
var datestr = <?php echo json_encode($thedate); ?>;
$("#" + str).html(data);
}
}).error(function() {
alert(data);
});
}
PHP:
case "getsched":
//some code
//some query
while($row = mysql_fetch_array($result))
{
//more code
$thedate = $_POST['date'];
}
//other code here
break;
When I alert datestr, I get undefined. How to fix this?
You can't use PHP like this. You should obtain the response from PHP and use it. In your PHP, you should output a response similar to this (just an example of JSON response):
echo json_encode(array('thedate', '2018-4-3'));
and you can obtain the value of 2018-4-3 in your JS with:
function getsched(str)
{
//some code
$.ajax({
type: 'POST',
url: 'mainclass.php',
data: 'date=' + str + '&form=getsched',
success: function(data) {
var datestr = data.thedate;
$("#" + str).html(datastr);
}
}).error(function() {
alert(data);
});
}
You need to replace the line:
var datestr = <?php echo json_encode($thedate); ?>;
with
var datestr = JSON.stringify(date);
alert(datestr);
It will convert the server response to a JSON encoded string. The encoded string is then displayed in the alert. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
Assign a global variable in HTML/PHP file before includeing JS file.
var datestr = <?php echo $thedate; ?>;
Then you can access the datestr variable from your JS file.

Ajax not working well

I'm trying to submit a form using Ajax , but it doesn't work here is my Ajax :
$(document).ready(function(){
$("#submit").click(function(event){
var ad1 = $("#ad1").val();
var ad2 = $("ad2").val();
var city = $("city").val();
var state = $("state").val();
var zip = $("zip").val();
var country = $("country").val();
var mm = $("mm").val();
var dd = $("dd").val();
var yy = $("yy").val();
var lname = $("lname").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'name1='+ name + '&ad11='+ ad1 + '&ad21='+ ad2 + '&city1='+ city + '&state1='+ state + '&zip1='+ zip + '&country1='+ country + '&mm1='+ mm + '&yy1='+ yy + '&dd1='+ dd + '&lname1=';
if(name=='')
{
alert("");
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "action.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
}
});
}
return false;
});
});
and it's not giving any result just giving data in header
the result is like :
I copied the javascript to the form page it's now working ,but the ajax is returning a blank alert while it should be "Form Submitted Succesfully"
I guess that it's an error of inclusion of the file , but i'm using the right directories.
here is action.php :
<?php
$con = mysqli_connect("server","user","pass","db");
$name=$_POST['name1'];
$ad1=$_POST['ad11'];
$ad2=$_POST['ad21'];
$city=$_POST['city1'];
$state=$_POST['state1'];
$zip=$_POST['zip1'];
$country=$_POST['country1'];
$mm=$_POST['mm1'];
$dd=$_POST['dd1'];
$yy=$_POST['yy1'];
$dob=$dd."/".$mm."/".$yy;
$mm=$_POST['mm1'];
$name=$_POST['name1'];
$lname=$_POST['lname1'];
$r2=rand(10000,90000);
$query = mysqli_query($con,"insert into users values('$r2','$name','$lname','$ad1','$ad2','$city','$state','$zip','$country','$dob')");
mysqli_close($con);
echo "Form Submitted Succesfully";
?>
This name variable is not have defined in ajax file var dataString = 'name1='+ name + so name would be an empty string
=> if(name=='')
{
alert("");
} executed. Please add string into alert and check again :)

Voting a Poll using AJAX jQuery

I've created a simple poll that would be sent to the server side using AJAX JSON jQuery and would be echoed back. It's not properly working. Please tell me where i've gone wrong. I'm new to jQuery and JSON.
JavaScript
<script>
function sendVote(){
var voteS = $("#vote").val();
$(document).ready(function(){
$("#vote").click(function(){
$.ajax({
type : "POST",
url : "poll_vote.php",
data : "vote="+voteS,
dataType: "JSON",
success : function(data){
concole.log("Data Submitted " + data);
$("#result").html(data);
},
complete :function(data){},
error : function(error, data){
console.log("Error. not Working" + error+" "+ data);
alert("Error. not Working"+ error);
$("#result").html(error+ data);
}
});
});
});
}
</script>
PHP
<?php
$vote = $_POST['vote'];
if (isset($vote)) {
$list = array('vote' => $vote);
$encode = json_encode($list);
echo $encode;
}
?>
HTML
<body>
<h3> What is your Gender? </h3>
<form>
Male :
<input type = "radio" name = "vote" value= "0" id="vote" onclick = "return sendVote()" />
<br />
Female :
<input type = "radio" name = "vote" value = "1" id="vote" onclick = "return sendVote()">
</form>
<p><div id= "result"></div></p>
</body>
You have picked ambiguous selector, having used invalid markup with non-unique id.
Change this:
var voteS = $("#vote").val();
to:
var voteS = $("input[name='vote']:checked").val();
And, as you specified by dataType: "JSON", you are expecting an json object in success section, so you only need to access this object's vote attribute here:
$("#result").html(data.vote);
Also in success you have typo: concole.log instead of console.log
And in your PHP file, you should check if $_POST['vote'] is set:
if (isset($_POST['vote'])) {
$vote = $_POST['vote'];
$list = array('vote' => $vote);
$encode = json_encode($list);
echo $encode;
}
And remove $(document).ready(function(){ from this function, it will not bind this event to that element before you actually call this function it is in.

How do you input javascript variable into php script?

I'm trying to get a function called that calls a php function with an input.
javascript function (picNum is an integer):
function hello(picNum) {
var pictureNumber = picNum;
var phpFunc = "<?php
include 'otherfile.php';
otherFileFunc(" + pictureNumber + ") //This is where the problem is, the input(pictureNumber) wont go through
?>";
echo phpFunc;
}
otherfile.php
<?php
function otherFileFunc($i) {
$final = $i + 1;
echo $final;
}
?>
this code pretty much says if you do onclick="hello(1)" then the output or phpFunc should be 2 because you add one in the otherfile.php, but no matter the input the output is always 1 so I'm guessing the input at where I marked just isn't going through.
DONT TELL ME IT DOESNT WORK BECAUSE IT DOES.
if i put an integer instead of " + pictureNumber + " it works perfectly!
any help is appreciated :)
Unfortunately you won't be able to call php from javascript.
Php is run from the server and javascript is run on a client (usually, the exception being node.js. However even in the instance of node.js, php is not used as javascript has replaced its functionality)
If you need to have javascript "call" a server function you will need to look into ajax requests so that the server can then run a function and return it to the client.
You have to use Ajax bro:
Javascript:
function hello(picNum) {
var pictureNumber = picNum;
$.ajax({
url: "otherfile.php",
data: {"picNum":pictureNumber},
type:'post',
dataType:'json',
success: function(output_string){
PictureNumber = output_string['picturenumber'];
alert(PictureNumber);
}
});
}
PHP otherfile.php:
$picNum = $_POST['picNum'];
function otherFileFunc($pic){
$final = $pic + 1;
return $final;
}
$outputnumber = function($picNum);
$array = ('picturenumber' => $outputnumber);
echo json_encode($array);
Note: Untested
EDIT, tested:
javascript:
function hello(picNum) {
var pictureNumber = picNum;
$.ajax({
url: "otherfile.php",
data: {"picNum":pictureNumber},
type:'post',
dataType:'json',
success: function(output_string){
pictureNumber = output_string['picturenumber'];
alert(pictureNumber);
}
});
}
hello(1); //sample
PHP otherfile.php:
$picNum = $_POST['picNum'];
$picNum = 1;
function otherFileFunc($pic){
$final = $pic + 1;
return $final;
}
$outputnumber = otherFileFunc($picNum);
$array = array('picturenumber' => $outputnumber);
echo json_encode($array);

Javascript alert when new row is added to database

I need to give a javascript alert to users browser when a new record is added to database. So far i have done this:
PHP chatalert.php
require("../system/config.php");
$result = mysql_query("SELECT * FROM chat");
$rows = mysql_num_rows($result);
echo $rows;
Javascript: test.php
<?php
define('BASEPATH', true);
require("../system/config.php");
?>
<script>
var old_count = 0;
setInterval(function(){
$.ajax({
type : "POST",
url : "chatalert.php",
success : function(data){
if (data > old_count) {
alert('new record on i_case');
old_count = data;
}
}
});
},1000);
</script>
But I always recive an error: "Uncaught ReferenceError: $ is not defined". So I will need some advice on this.
Mairo
Have you included jquery? if not try adding this in your head tags
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
also make sure to parse the string to integer/Float for accurate result. The data returned by php can also be in string format:
var old_count = 0;
setInterval(function(){
$.ajax({
type : "POST",
url : "chatalert.php",
success : function(data){
if (parseFloat(data) > old_count) {
alert('new record on i_case');
old_count = data;
}
}
});
},1000);

Categories

Resources